技术开发 频道

Windows Mobile下猜数字游戏的TDD实现

 功能代码

 功能代码的目的就是通过所以单元测试。

 public class Bingle

 {

 public int[] Answers { set; get; }

 private int attemptTimes;

 public int AttemptTimes

 {

 get

 {

 return attemptTimes;

 }

 }

 public Bingle()

 {

 Answers = new int[4];

 }

 public void BuildAnswers()

 {

 Random r = new Random();

 while(true)

 {

 int i = r.Next(9999);

 Answers[0] = i / 1000;

 Answers[1] = i % 1000 / 100;

 Answers[2] = i % 100 / 10;

 Answers[3] = i % 10;

 if (Answers[0] != Answers[1]

 && Answers[0] != Answers[2]

 && Answers[0] != Answers[3]

 && Answers[1] != Answers[2]

 && Answers[1] != Answers[3]

 && Answers[2] != Answers[3])

 {

 return;

 }

 }

 }

 public bool Match(int[] attemptNum, out int bingle, out int match)

 {

 bingle = 0;

 match = 0;

 if (attemptNum.Length != 4)

 {

 throw new ArgumentException("Should be 4 digits.");

 }

 if(!(attemptNum[0] != attemptNum[1]

 && attemptNum[0] != attemptNum[2]

 && attemptNum[0] != attemptNum[3]

 && attemptNum[1] != attemptNum[2]

 && attemptNum[1] != attemptNum[3]

 && attemptNum[2] != attemptNum[3]))

 {

 throw new ArgumentException("Should be non repeating 4 digits.");

 }

 ++attemptTimes;

 for(int i=0; i<4; ++i)

 {

 if (attemptNum[i] == Answers[i])

 {

 ++bingle;

 }

 else

 {

 for (int j = 0; j < 4; ++j)

 {

 if (attemptNum[i] == Answers[j])

 {

 ++match;

 }

 }

 }

 }

 return (bingle == 4);

 }

 }

 单元测试结果

 如果通过所有单元测试,说明功能代码编写完毕,每次修改都有run单元测试。

 NUnitLite version 0.2.0

 Copyright 2007, Charlie Poole

 Runtime Environment -

 OS Version: Microsoft Windows CE 5.2.21234

 .NET Version: 2.0.7045.0

 /Files/procoder/Bingle.rar3 Tests : 0 Errors, 0 Failures, 0 Not Run

 UI 处理

 功能代码写完以后,可以写UI了,具体UI代码见源代码,下面是执行效果。

作者:Jake.NET

查看原文地址
 

0
相关文章