2014-04-24 23:28
题目:玩象棋游戏,你要设计一个bool型的方法来检测一个棋子能否移动到指定位置。
解法:不同的棋子有不同的移动规则,那么应该采取棋子基类实现接口,各个棋子子类来实现的方式。棋子除了类型之外,还必须要记录当前位置,作为判断的依据。而要移到的位置,则作为参数传给方法。不过这个题目出现在软件测试的章节里,应该是要描述如何测试吧。没学过系统的测试方法,遇到这种题的话还真没办法。
代码:
1 // 12.3 You're testing a method canMoveTo(int x, int y), which is a member method of a class Piece. Piece represents a piece in the chess game. How would you perform the testing? 2 // Answer: 3 // 1. Apparently every kind of pieces in chess has its own rule of moving. So the class Piece must be an abstract class, which will inherited by various kinds of specific pieces. 4 // 2. You always have to check if (x, y) is out of border. So this will be included in base class Piece. 5 // 3. Every piece has its own rule of moving, so the derived class will have to implement its own rule(), which will be executed by canMoveTo(). 6 // 4. The class Piece should look like this: 7 // 5. The base class will have an interface named rule(), which will be implemented by derived class. 8 class Piece { 9 public: 10 virtual bool canMoveTo(int x, int y); 11 private: 12 // ... 13 virtual bool rule(int x, int y) = 0; 14 }; 15 // 6. Thus, the test should cover two parts: 16 // 6.a. The coordinates (x, y) will cover in-bound and out-of-bound cases. 17 // 6.b. Every rule() function will be executed inside canMoveTo(), thus the test will also be included here.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)