C#初学者(3)

[复制链接]
查看11 | 回复0 | 2007-1-19 12:58:00 | 显示全部楼层 |阅读模式
实例学习:猜字游戏
软件规范:
猜双字母游戏的目的是让用户猜两个字母序列,而这两个字母由计算机程序在4个字母A、B、C和D中随机选出。允许字母重复。
用户通过输出两个字母来开始。程序将用户的猜测与隐藏的组合进行比较,并反馈两个评价此猜测的数字:
第一个数表示猜对字母及其位置的个数。此数字ccCounter。
第二个数表示猜测字母中有多少个正确,但它的位置是错误的。此数字叫cwCounter。
然后,用户输入另一个字母组合并看到另一个反馈。以上事件将重复进行,直到用户找到了正确的字母序列为止。
程序生成的隐藏组合是:BD
Guess
Response
Comment

CC
CW

AB
0
1
B 是正确字母,但位置错误
BC
1
0
B 是正确字母,且位置正确
DB
0
2
两个字母均正确,但位置错误
BD
2
0
两个字母均正确,且位置也正确
我们设计程序的目的就是要能玩此猜双字母游戏,并使输出结果与上面显示的相同。
此程序必须对用户找出此组合所猜测的次数进行适当的评论。
例如,如果猜测次数少于8次,则打印weIl Done!。
如果猜测次数等于或多于8次,则打Finally!。
最后,一旦程序结束,程序必须让用户选择是终止游戏还是继续玩另一个游戏。在用户决定终止程序前,游戏必须重复进行。
01: using System;
02:
03: class GuessTwoLetters
04: {
05: public static void Main()
06: {
07: string letterCode;
08: string letterGuess;
09: string letters = "ABCD";
10: int ccCounter;
11: int cwCounter;
12: int guessCounter = 0;
13: string anotherGame;
14: Random Randomizer = new Random();
15: do
16: {
17:
guessCounter = 0;
18:
letterCode = letters[Randomizer.Next(0,4)].ToString() +
19:
letters[Randomizer.Next(0,4)].ToString();
20:
Console.WriteLine("\nChoose two of the four letters A, B, C, D\n" +
21:
"CC: Correct letter Correct position\n" +
22:
"CW: Correct letter Wrong position\n" +
23:
"Please enter letter guesses\n\n" +
24:
" CC CW&quot

;
25:
do
26:
{
27:
ccCounter = 0;
28:
cwCounter = 0;
29:
letterGuess = Console.ReadLine().ToUpper();
30:
// Determine how many positions of the guess contains a
31:
// correct letter in a correct position (CC's)
32:
if(letterGuess[0] == letterCode[0])
33:
ccCounter++;
34:
if(letterGuess[1] == letterCode[1])
35:
ccCounter++;
36:
// If no CC's were found determine how many positions
37:
// of the guess contains a correct letter but incorrect position
38:
if(ccCounter == 0)
39:
{
40:
if(letterGuess[0] == letterCode[1])
41:
cwCounter++;
42:
if(letterGuess[1] == letterCode[0])
43:
cwCounter++;
44:
}
45:
Console.WriteLine(" {0} {1}", ccCounter, cwCounter + "\n&quot

;
46:
guessCounter++;
47:
} while (letterCode != letterGuess);
48:
// Use conditional operator to provide suitable comment
49:
Console.WriteLine((guessCounter < 8) ? "Well done! " : "Finally! &quot

;
50:
Console.WriteLine("You guessed the code in {0}guesses", guessCounter);
51:
Console.WriteLine("\nDo you wish to play another game? Y(es) N(o)&quot

;
52:
anotherGame = Console.ReadLine().ToUpper();
53: } while (anotherGame == "Y" || anotherGame == "YES&quot

;
54:
Console.WriteLine("Great playing with you. Hope you had fun!&quot

;
55: }
56: }
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行