一个小的彩票游戏项目和挑战.C#


编辑:完成所有挑战。添加了最终代码。

当我等待我的编程教育开始(.NET/C#(时,我在这期间练习自己。我仍然是一名学徒编码员。

现在我正在编写一个小型彩票游戏,它应该像这样工作:

  • 输入名称和1-35之间的7个数字
  • 输入所有玩家及其号码后,只需按ENTER键继续
  • 生成正确的彩票行(共11个号码(
  • 数据按数字顺序排序
  • 数据已更正
  • 数据如下所示:
Correct lottery line: 7,8,9,10,11,12,15 
Additional numbers: 21,22,23,24
James: 1,4,6,7,8,20,21      2 correct, 1 additional number    
Jane: 1,6,8,12,14,15,35     3 correct, zero additional number*
  • 数据保存在硬盘上的文件中

下面添加的完整代码:

internal class Program
{
static List<Player> listOfPlayers = new List<Player>();
static List<int> lotto35 = new List<int>();
static List<int> lotto11 = new List<int>();
static List<int> lotto7 = new List<int>();
static List<int> lotto4 = new List<int>();
static Random rnd = new Random();
static string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\lottorad.txt";
static void Header()
{
Console.WriteLine("n*****************************************************************" +
"n*                                                               *" +
"n*ttWelcome to The Little Lottery Gamett*" +
"n*                                                               *" +
"n*****************************************************************");
}
static void LottoNumbers()
{
// Generate numbers 1-35 and add them to lotto35:
for (int i = 1; i <= 35; i++)
lotto35.Add(i); 
// Generate 11 random numbers from lotto35. No duplicates allowed!:
for (int i = 0; i < 11; i++)
{
// Gets a random number from lotto35 and stores it in "index":
int index = rnd.Next(lotto35.Count);
//Console.Write(lottoNumbers[index] + ", ");

lotto11.Add(lotto35[index]);
// Removes the last number retrieved from lotto35 to prevent duplicates:
lotto35.RemoveAt(index);
}
//lotto11.Sort();
//Console.ReadKey();
}
static void RunGame()
{
//Console.WriteLine(string.Join(", ", lotto11.GetRange(0, 11)));
Console.Write("nType in your Name or press ENTER to continue." +
"nName: ");
// Wait for name input:
string nameInput = Console.ReadLine();
if (!string.IsNullOrEmpty(nameInput))
{
int[] numberInput = new int[7];
for (int i = 0; i < 7; i++)
{
// Use this bool to keep looping until user input correct number:
bool moveon = false;
do
{
Console.Write($"Type in lotto nr {i + 1}: ");
string input = Console.ReadLine();
// First check if input is a number, next check that input is between 1 and 35.
// The function TryParse takes the string input and tries to parse it as an int.
// If it's parsed, it's returned as a new int 'useinput':
if (int.TryParse(input, out int useinput) && useinput >= 1 && useinput <= 35 && (!numberInput.Contains(useinput)))
{
// Add number to int[]:
numberInput[i] = useinput;
// Allow user to skip loop and enter new number.
// 'Continue' breaks directly out of loop:
moveon = true; continue;
}
else { Console.WriteLine($"Error: Only numbers between 1 and 35 and no duplicate:"); }
}
// Keep looping until moveon = true:
while (moveon == false);
}
// Sort every input in numberInput ascending:
Array.Sort(numberInput);
// Add name and sorted numbers to list of players:
listOfPlayers.Add(new Player(nameInput, numberInput));
}
else if (string.IsNullOrEmpty(nameInput))
{
// Add numbers to lotto7 and lotto4 and sort them
lotto7.AddRange(lotto11.GetRange(0, 7));
lotto7.Sort();
lotto4.AddRange(lotto11.GetRange(7, 4));
lotto4.Sort();
lotto11.Sort();
Console.Clear();
Header();

// Output the result
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("nLottery numbers: " + string.Join(", ", lotto7));
Console.WriteLine("Additional numbers: " + string.Join(", ", lotto4));
// List players and their lottery numbers:
foreach (Player player in listOfPlayers)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("{0} {1}", player.Name + ", Your numbers: ", string.Join(", ", player.Numbers));
// Save result in lottorad.txt
using (StreamWriter outputFile = new StreamWriter(path, true))
{
outputFile.WriteLine(DateTime.Now);
outputFile.WriteLine("{0} {1}", player.Name + ", Your numbers: ", string.Join(", ", player.Numbers));
}
// Check how many correct numbers each player have
int count1 = 0;
int count2 = 0;
for (int i = 0; i < player.Numbers.Length; i++)
{
if (lotto7.Contains(player.Numbers[i]))
count1++;
if (lotto4.Contains(player.Numbers[i]))
count2++;
}
Console.Write("You have ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(count1);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(" correct lottery numbers plus ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(count2);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(" additional numbers.");
Console.WriteLine();
}
// Ask player to quit or play again
bool moveon = false;
do
{
Console.ResetColor();
Console.Write("nTo quit press Q : To play again press ENTER : ");
string letter = Console.ReadLine();
letter = letter.ToUpper();

if ( letter == "Q")
{
Console.WriteLine("Thanks for playing!");
Environment.Exit(0);
}
else
{
// Clear all data before new game starts
Console.Clear();
Console.ResetColor();
listOfPlayers.Clear();
lotto35.Clear();
lotto11.Clear();
lotto7.Clear();
lotto4.Clear();
Header();
moveon = true; continue;
}

}
while (moveon == false);

}
// Start over again.
LottoNumbers();
RunGame();
}
static void Main(string[] args)
{
Header();
LottoNumbers();
RunGame();
}
public class Player
{
public string Name { get; set; }
public int[] Numbers { get; set; }
public Player(string name, int[] numbers)
{
Name = name;
Numbers = numbers;
}
}
}
}

您需要将numberInput移动到循环中,如下代码所示。

作为奖励,我确实应用了你即将推出的一些功能来帮助你:(

internal class Program
{
static List<Player> listOfPlayers = new List<Player>();
static void RunGame()
{
Console.Write("Type in your name or press ENTER to continue." +
"nName: ");
// Wait for name input:
string nameInput = Console.ReadLine();
if (!string.IsNullOrEmpty(nameInput))
{
int[] numberInput = new int[7];
for (int i = 0; i < 7; i++)
{
// Use this bool to keep looping until user input correct number:
bool moveon = false;
do
{
Console.Write($"Type in lotto nr {i + 1}: ");
string input = Console.ReadLine();
// First check if input is a number, next check that input is between 1 and 35.
// The function TryParse takes the string input and tries to parse it as an int.
// If it's parsed, it's returned as a new int 'useinput':
if (int.TryParse(input, out int useinput) && useinput >= 1 && useinput <= 35)
{
// Add number to int[]:
numberInput[i] = useinput;
// Allow user to skip loop and enter new number.
// 'Continue' breaks directly out of loop:
moveon = true; continue;
}
else { Console.WriteLine($"Error: Input a number between 1 and 35:"); }
}
// Keep looping until moveon = true:
while (moveon == false);
}
// Sort every input in numberInput ascending:
Array.Sort(numberInput);
// Add name and sorted numbers to list of players:
listOfPlayers.Add(new Player(nameInput, numberInput));
}
else
{
// List players and their lottery numbers:
foreach (Player player in listOfPlayers)
{
Console.WriteLine("{0} {1}", player.Name, string.Join(", ", player.Numbers));
}
}

// Start over again.
RunGame();
}
static void Main(string[] args) { RunGame(); }
public class Player
{
public string Name { get; set; }
public int[] Numbers { get; set; }
public Player(string name, int[] numbers)
{
Name = name;
Numbers = numbers;
}
}
}
}

当您将numberInput数组赋予Player变量时

此处:listOfPlayers.Add(new Player(nameInput, numberInput));

实际上是对同一数组的引用。所以基本上,所有的玩家都会在内存中引用同一个数组。

你想做的是为每个玩家注册一个这个数组的副本。

您可以使用.Clone()轻松地进行复制,并将其转换回int[]:

//old code
listOfPlayers.Add(new Player(nameInput, numberInput));`
//new code
listOfPlayers.Add(new Player(nameInput, (int[])numberInput.Clone()));`

最新更新