C# 一个简单的刽子手游戏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16753744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# A simple Hangman game
提问by Radostin Angelov
I'm trying to create a simple Hangman game and i have gotten so far, to make it read all words from a text file, but I don't know how to make the code work for every single word. I have another project, working with 3/4 words but with repeating nested if statements. I want to make it as shorter as possible. This is the code i have so far :
我正在尝试创建一个简单的 Hangman 游戏,到目前为止我已经做到了,让它从文本文件中读取所有单词,但我不知道如何使代码对每个单词都有效。我有另一个项目,使用 3/4 个单词但重复嵌套的 if 语句。我想让它尽可能短。这是我到目前为止的代码:
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] words = System.IO.File.ReadAllLines(@"C:\Users\ADMIN\Desktop\Letters\Letters.txt");
int LengthOfArray = words.Length;
Random rnd = new Random();
int random = rnd.Next(1, 3);
char[] letters = words[random].ToCharArray();
bool WordIsHidden = true;
char hiddenChar = '_';
char GuessedLetter = hiddenChar;
var retry = true;
while (retry = true)
{
Console.WriteLine(letters);
letters = GuessedLetter.ToString().ToCharArray();
for (int i = 1; i <= LengthOfArray; i++)
{
Console.Write("{0} ", GuessedLetter);
}
Console.WriteLine("Enter a letter!");
char letter = char.Parse(Console.ReadLine());
if (words[random].Contains<char>(letter))
{
WordIsHidden = false;
GuessedLetter = letter;
Console.Write(letters);
}
else
{
if (WordIsHidden == true)
{
Console.Write("You guessed wrong!");
}
}
}
}
}
Also I'm trying to make the game show each letter, the user has guessed on it's corresponding position, but now the letter is one line higher than the rest of the word and it's not in it's right position.
另外我试图让游戏显示每个字母,用户已经猜到了它的对应位置,但现在这个字母比单词的其余部分高一行,而且位置不对。
Edited:
编辑:
Here is the result :
cat
___Enter a letter!
a
__
aaaEnter a letter!
t
aa
tttEnter a letter!
IF anyone have a clue for where does this come from and how can I fix it, any help will be greatly appreciated.
如果有人知道这是从哪里来的,我该如何解决,任何帮助将不胜感激。
采纳答案by thedajaw
Ok, I'm guessing at the problem here but I think you are describing an off by one error here:
好的,我在猜测这里的问题,但我认为您在这里描述了一个错误:
for (int i = 1; i <= LengthOfArray; i++)
should be:
应该:
for (int i = 0; i < LengthOfArray; i++)
As indexing in C# starts at 0. This is probably causing the issue you are seeing. However a foreach loop here would be better as you are not using the value 'i' at all.
由于 C# 中的索引从 0 开始。这可能会导致您看到的问题。但是,这里的 foreach 循环会更好,因为您根本没有使用值 'i'。
foreach(var c in words)
Console.Write(GuessedLetter);
as for making the program shorter, don't worry too much right now, get the program working and then refactor later. I'd advice starting with looking into LINQ/IEnumerable extensions, also type inference via the var keyword.
至于使程序更短,现在不要太担心,让程序运行,然后再重构。我建议从查看 LINQ/IEnumerable 扩展开始,还可以通过 var 关键字进行类型推断。
EDIT:
编辑:
Ok I spent 5 minutes looking over your code, I put in a couple of fixes (see comments). Please review against the original code. It is not a pretty, efficient or elegant solution but hopefully it behaves more inline with what you were expecting.
好的,我花了 5 分钟查看您的代码,我进行了一些修复(请参阅评论)。请对照原始代码进行检查。这不是一个漂亮、高效或优雅的解决方案,但希望它的行为更符合您的期望。
using System;
using System.Linq
using System.Collections.Generic;
class Program
{
static void Main()
{
string[] words = System.IO.File.ReadAllLines(@"C:\Users\ADMIN\Desktop\Letters\Letters.txt");
int LengthOfArray = words.Length;
Random rnd = new Random();
int random = rnd.Next(1, 3);
char[] letters = words[random].ToCharArray();
bool WordIsHidden = true;
char hiddenChar = '_';
//fix 1 use a list or hashset or similar to store the selected chars
var guessed = new List<char>();
var retry = true;
while (retry = true)
{
Console.WriteLine(letters);
//fix 2, loop over the letters, checking whether they have been guessed
foreach(var c in letters)
{
if (guessed.Contains(c))
Console.Write(c);
else
Console.Write("_");
}
Console.WriteLine("\nEnter a letter!");
char letter = char.Parse(Console.ReadLine());
if (words[random].Contains<char>(letter))
{
WordIsHidden = false;
guessed.Add(letter);
}
else
{
if (WordIsHidden == true)
{
guessed.Clear();
Console.WriteLine("You guessed wrong!");
}
}
}
}
};
回答by mohammed musah
Try this
尝试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HangMan.cs.hange_man
{
class HangManGame
{ // checking for word
static bool IsWord(string secreword, List<string> letterGuessed)
{
bool word = false;
// loop through secretword
for (int i = 0; i < secreword.Length; i++)
{
// initialize c with the index of secretword[i]
string c = Convert.ToString(secreword[i]);
// check if c is in list of letters Guess
if (letterGuessed.Contains(c))
{
word = true;
}
/*if c is not in the letters guessed then we dont have the
* we dont have the full word*/
else
{
// change the value of word to false and return false
return word = false;
}
}
return word;
}
// check for single letter
static string Isletter(string secretword, List<string> letterGuessed)
{
// set guessedword as empty string
string correctletters = "";
// loop through secret word
for (int i =0 ; i < secretword.Length; i++)
{
/* initialize c with the value of index i
* mean when i = 0
* c = secretword[0] is the first index of secretword
* c = secretword[1] is the second index of secretword and so on */
string c =Convert.ToString( secretword[i]);
// if c is in list of lettersGuessed
if (letterGuessed.Contains(c))
{
// add c to correct letters
correctletters += c;
}
else
{
// else print (__) to show that the letter is not in the secretword
correctletters += "_ ";
}
}
// after looping return all the correct letters found
return correctletters;
}
// The alphabet to use
static void GetAlphabet(string letters)
{
List <string> alphabet = new List<string>();
for (int i = 1; i <= 26; i++)
{
char alpha = Convert.ToChar(i+96);
alphabet.Add (Convert.ToString(alpha));
}
// for regulating the number of alphabet left
int num = 49;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("Letters Left are :");
for (int i = 0; i < num; i++)
{
if (letters.Contains(letters))
{
alphabet.Remove(letters);
num -= 1;
}
Console.Write("["+alphabet[i]+"] ");
}
Console.WriteLine();
}
/* random strings
static string RandomWord(string secretword)
{
Random rnd = new Random();
}*/
static void Main()
{
Console.Title = ("HangMan");
// secretWord
string secretword = "foreground";
List <string> letterGuessed = new List<string>();
int live = 5;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Welcome to Hangman Game");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Guess for a {0} letter Word ", secretword.Length);
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("You have {0} live", live);
Isletter(secretword,letterGuessed);
// while live is greater than 0
while (live > 0 )
{
Console.ForegroundColor = ConsoleColor.Yellow;
string input = Console.ReadLine();
// if letterGuessed contains input
if (letterGuessed.Contains(input))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You Entered letter [{0}] already",input);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Try a different word");
GetAlphabet(input);
continue;
}
// if word found
letterGuessed.Add(input);
if (IsWord(secretword,letterGuessed))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(secretword);
Console.WriteLine("Congratulations");
break;
}
// if a letter in word found
else if (secretword.Contains(input))
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("wow nice entry");
Console.ForegroundColor = ConsoleColor.Yellow;
string letters = Isletter(secretword, letterGuessed);
Console.Write(letters);
}
// when a wrong code is entered
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Oops, letter not in my word");
live-=1;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("You have {0} live", live);
}
Console.WriteLine();
// print secret word
if (live == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Game over \nMy secret Word is [ {0} ]",secretword);
break;
}
}
Console.WriteLine("press any key to Exit");
Console.ReadKey();
}
}
}

