私が文字通り C# を書き始めたばかりであることをみんなが知っているように、これは練習です。
インターネットで GuessTheNumberGame コードを見つけ、基本的なゲームを改善して、フィードバックが提供され、ユーザーが数字を変更できるようにしました。プログラムは動作していましたが、「NumberChange」モジュールを「Code」メソッドとは別に配置したいと考えていました。
「GuessTheNumberGame」内に Main() メソッドを作成し、「Code」メソッドを実行しました。問題は、数値範囲を変更しようとすると、「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;
}
}
}