就这样每个人都知道我刚刚开始编写 C#,这是练习。
我在互联网上找到了一个 GuessTheNumberGame 代码,并一直在尝试改进基本游戏以便给出反馈,并且用户可以更改数字。我让程序正常工作,但想将“NumberChange”模块与“代码”方法分开。
我在“GuessTheNumberGame”中创建了一个 Main() 方法,并执行“代码”方法。问题是当我去更改数字范围时,“NumberChange”模块不会更改“Public Static int from”或“Public static int to”的值;因此,数字的范围保持不变。
下面的代码:
using System;
namespace GuessThatNumber
{
class GuessTheNumberGame
{
static void Main()
{
Code(from, to, new_range);
}
public static int new_range = 0;
public static int from = 1;
public static int to = 10;
static void Code(int from, int to, int new_range)
{
//int from = 1; // The range the user will guess from.
//int to = 10; //The range the user will guess to.
int guessedNumber; //This will hold the value that the user guessed.
int Counter = 0; //Counter is used to count the number of guesses the user makes.
int selection = 0; //This value is for the selection at the start of the program
//int new_range = 0;
bool exit = false;
while (exit == false)
{
Console.WriteLine("What would you like to do?");
Console.WriteLine("1: Alter the range of guessed numbers? The range is currently from {0} to {1}.", from, to);
Console.WriteLine("2: Try to guess the number?");
Console.WriteLine("3: Exit the program?");
Console.WriteLine("Please enter a number:");
if (int.TryParse(Console.ReadLine(), out selection))
{
if (selection == 2)
{
int randomNumber = new Random().Next(from, to); //Generates a random number between the (from, to) variables.
Console.Write("The number is between {0} and {1}. ", from, to);
while (true)
{
Console.Write("Make a guess: ");
if (int.TryParse(Console.ReadLine(), out guessedNumber))
{
if (guessedNumber == randomNumber)
{
Console.WriteLine("You guessed the right number!");
if (Counter < 2)
{
Console.WriteLine("You guessed the number in only 1 turn! Amazing!");
Console.WriteLine(" ");
}
else
{
Console.WriteLine("You guessed " + Counter + " times.");
Console.WriteLine(" ");
}
break;
}
else
{
Console.WriteLine("Your guess was too {0}.", (guessedNumber > randomNumber) ? "high" : "low");
Counter = Counter + 1;
}
}
else
{
Console.WriteLine("Input was not an integer.");
}
}
//Console.WriteLine();
//Console.WriteLine("Press any key to exit.");
//Console.ReadKey();
}
else if (selection == 1)
{
NumberChange(from, to, new_range);
}
else
{
exit = true;
}
}
}
}
static int NumberChange(int from, int to, int new_range)
{
Console.WriteLine("Please enter the number that the guess will start from.");
int.TryParse(Console.ReadLine(), out new_range);
from = new_range;
Console.WriteLine("Now enter the number that the guess will go to.");
int.TryParse(Console.ReadLine(), out new_range);
to = new_range;
return new_range;
}
}
}