文曲星猜数游戏的非TDD实现
懒人王的TDD by example (1) -- 挑战让我想起了多年前抱着文曲星猜数的时光,逝者如斯夫……
我本人一直认为TDD是个很玄妙的东西,它对我们习惯的功能驱动的编程方式是一种颠覆。我一直想实践一下,但是没有机会。希望能够从懒人王的这个系列里学到想学的东西。
在此先实现一个非TDD的实现,回头再比较一下与TDD的方式有什么不同。
由于时间仓促,没有过多的OO。整个代码只有一个Game类。
namespace GuessGame { class Game { private static readonly int NUMBER_COUNT = 4; private static readonly int GUESS_TIME = 6; private int guessedTime; private int[] numbers; private int[] inputs; private int aCount; private int bCount; public Game() { Init(); } public void Play(string input) { Input(input); if (!Compare()) { Output(); aCount = 0; bCount = 0; guessedTime++; } else { Console.Write("猜对了,正确答案为"); Output(numbers); Console.WriteLine(); Init(); } if (guessedTime >= GUESS_TIME) { Console.Write("失败:您已经猜了" + guessedTime + "次"); Init(); } } private void Init() { aCount = 0; bCount = 0; guessedTime = 0; numbers = new int[NUMBER_COUNT]; GenerateDistinctRandomNumbers(); Console.WriteLine("请输入4位数字"); } private void GenerateDistinctRandomNumbers() { Random r = new Random(); bool allowZero = true; for (int i = 0; i < NUMBER_COUNT; i++) { int n = r.Next(10); if (n == 0 && allowZero) { numbers[i] = n; allowZero = false; } else { while (numbers.Contains(n)) { n = r.Next(10); } numbers[i] = n; } } } private void Output() { Output(inputs); Console.Write(" "); Console.Write(aCount); Console.Write("A"); Console.Write(bCount); Console.Write("B"); Console.WriteLine(); } private void Output(int[] array) { foreach (int i in array) Console.Write(i); } private bool Compare() { for (int i = 0; i < NUMBER_COUNT; i++) { if (numbers[i] == inputs[i]) { aCount++; } else if (numbers.Contains<int>(inputs[i])) { bCount++; } } return aCount == NUMBER_COUNT; } private void Input(string input) { if (String.IsNullOrEmpty(input)) throw new ArgumentNullException("输入不正确,重新输入"); if (input.Length != NUMBER_COUNT) throw new ArgumentOutOfRangeException("输入不正确,重新输入"); bool allowZero = true; inputs = new int[NUMBER_COUNT]; for (int i = 0; i < input.Length; i++) { int n = 0; bool isInt = int.TryParse(input[i].ToString(), out n); if (isInt) { if (n == 0 && allowZero) { allowZero = false; } else { if (inputs.Contains<int>(n)) { throw new ArgumentException("输入不正确,重新输入"); } } inputs[i] = n; } else throw new ArgumentException("输入不正确,重新输入"); } } } }
main方法很简单。
namespace GuessGame { class Program { static void Main(string[] args) { Game game = new Game(); while (true) { string input = Console.ReadLine(); try { game.Play(input); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } }
好久不写代码,手有点生锈。
好了,请懒人拍砖。