您可以使用一個布爾變量來將遊戲結束通知給循環。該命令必須在循環中查詢,並且由於在循環開始時不知道該命令,因此我會將循環條件放在循環結尾。
bool doExit = false;
do {
string command = Console.ReadLine().ToLower();
switch (command) {
case "exit":
case "quit":
doExit = true;
break;
case "otherCommand":
HandleOtherCommand();
break;
case "?":
case "h":
case "help":
PrintHelp();
break;
default:
Console.WriteLine("Invalid command!");
PrintHelp();
break;
}
} while (!doExit);
使用布爾變量的優點是,當滿足其他條件時可以輕鬆終止遊戲。例如當玩家贏得或失敗時。
現在的方法。您可以將方法放置在相同的源代碼(Program.cs)中或創建新的類。在計劃內。CS你會寫類似
private static void PrintHelp()
{
Console.WriteLine("Valid commands:");
Console.WriteLine("help, h, ?: Print this help.");
Console.WriteLine("exit, quit: End this game.");
Console.WriteLine("...");
}
注意,由於Main
方法是靜態的,這同一個類中的其他方法必須是靜態的了。如果您爲命令創建其他類,則可以選擇是否要創建靜態類。靜態類只是放置方法的地方。
static class GameCommands
{
// The `public` modifier makes it visible to other classes.
public static void PrintHelp()
{
...
}
public static void SomeOtherCommand()
{
...
}
}
您可以使用className.MethodName()
語法調用此類方法。
GameCommands.PrintHelp();
如果您必須存儲不同的狀態(例如分數)。創建非靜態類是合適的。您可以創建類稱爲類實例或對象的類的副本。這實際上只複製類的狀態,而不是方法代碼。非靜態方法可以作用於這種狀態(字段,屬性)。
class Player
{
// Constructor. Initializes an instance of the class (an object).
public Player (string name)
{
Name = name;
}
// Property
public int Score { get; private set; }
// Property
public string Name { get; private set; }
// Instance method (non-static method) having a parameter.
public void IncreaseScoreBy(int points)
{
Score += points;
}
public void PrintWinner()
{
Console.WriteLine("The winner is {0} with a score of {2} points." Name, Score);
}
}
可以使用這樣一類這樣的
Player player1 = new Player("John"); // Pass an argument to the constructor.
Player player2 = new Player("Sue");
player1.IncreaseScoreBy(5);
player2.IncreaseScoreBy(100);
if (player1.Score > player2.Score) {
player1.PrintWinner();
} else if (player2.Score > player1.Score)
player2.PrintWinner();
} else {
Console.WriteLine("The score is even!");
}
我們使用沒有返回值的方法到現在爲止。這通過替換返回類型的void關鍵字來表示。
void MethodWithNoReturnValue() { ... }
如果你有一個返回值(即你的方法是一個函數),你必須指定返回類型。 return
語句終止函數並指定返回值。
double Reciprocal(double x)
{
return 1.0/x;
}
你將同一類
double y = Reciprocal(x);
內或與對象名稱或類名前面加上它,如果它是靜態的稱呼它。
什麼問題? – Pete 2013-02-11 14:01:51
以後請格外小心。清理起來很麻煩! – PhonicUK 2013-02-11 14:04:23
我更新了帖子,使問題更加清晰。您向我們展示代碼的事實告訴我們您嘗試了什麼,並允許我們爲您提供幫助。在您展示您嘗試過的內容並解釋問題所在之處後,無需解釋「您可以在哪裏進行自己的研究」。一定要問更直接的問題以避免混淆。 – 2013-02-11 14:18:41