/*
Playing a console-based game
To solve the problem, your program must be able to:
Choose a random word to use as the secret word. That word is chosen from a word list, as described in the following paragraph. Keep track of the user’s partially guessed word, which begins as a series of dashes and then updated as correct letters are guessed. Implement the basic control structure and manage the details (ask the user to guess a letter, keep track of the number of guesses remaining, print out the various messages, detect the end of the game, and so forth) */
简单说需求就是从一个单词集合中随机选取一个单词, 假设猜想单词school, 就在控制台上输出 _ _ _ _ _ _,根据英语普遍规律,绝大部分的单词都有元音字母,所以从元音字母开始猜比较容易。假设用户猜字母O,单词school中出现了,就在单词上预留的位置中填写此字母,_ _ _ o o _ 当用户们猜测的单词为school中并未出现的字母,则将在控制台中输出最近一次单词的状态。若给定猜测次数内,单词仍未猜出,则系统获胜,若猜出此单词,则为用户获胜。
以下给出代码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72 |
namespace
GuessWord { class
Program { static
int wrongGuess, lettersLeft; static
void Main() { string
wordToGuess = GetWordToGuess(); char [] maskedWord = GetHiddenLetters(wordToGuess, ‘-‘ ); lettersLeft = wordToGuess.Length; char
userGuess; wrongGuess = 3; while
(wrongGuess > 0 && lettersLeft > 0) { DisplayCharacters(maskedWord); Console.WriteLine( "Enter a letter?" ); userGuess = char .Parse(Console.ReadLine()); maskedWord = CheckGuess(userGuess, wordToGuess, maskedWord); } Console.WriteLine( "Well done! Thanks for playing." ); Console.ReadLine(); } static
string GetWordToGuess() { Random number = new
Random(); int
wordNumber = number.Next(0, 9); string [] words = { "picture" , "chinese" , "school" , "question" , "include" , "simple" , "difficult" , "understand" , "necessary" , "support"
}; string
selectWord = words[wordNumber]; return
selectWord; } static
char [] GetHiddenLetters( string
word, char
mask) { char [] hidden = new
char [word.Length]; for
( int
i = 0; i < word.Length; i++) { hidden[i] = mask; } return
hidden; } static
void DisplayCharacters( char [] characters) { foreach
( char
letter in
characters) { Console.Write(letter); } Console.WriteLine(); } static
char [] CheckGuess( char
letterToCheck, string
word, char [] characters) { if
(word.Contains(letterToCheck.ToString())) { for
( int
i = 0; i < word.Length; i++) { if
(word[i] == letterToCheck) { characters[i] = word[i]; lettersLeft--; } } } else { wrongGuess--; } return
characters; } } } |
原文:http://www.cnblogs.com/jameslif/p/3593580.html