看到聊天室有人在問,所以試寫了一個看看當作練習,用目前自己能力所及的方式完成,如果有更好的建議也請各位多批評指教!
建立玩家時需先提供姓名與金錢
internal class Person
{
public Person(string name,int money)
{
Name = name;
Money = money;
}
public string Name { get; set; }
public int Money { get; set; }
public string Guess { get; set; }
public int WinCount { get; set; }
public int LoseCount { get; set; }
}
Bet: 賭注金額
RoundCount: 猜測進行輪數
internal class Game
{
public int Bet { get; set; }
public int RoundCount { get; set; }
public Person Player1 { get; set; }
public Person Player2 { get; set; }
}
使用random物件隨機產生數字1 or 2,分別代表正與反
internal static class ThrowCoinService
{
public static string GetThrowCoinResult()
{
var result = string.Empty;
Random random = new Random(DateTime.Now.Millisecond);
var num = random.Next(1, 3);
if (num == 1) result = "正";
else if (num == 2) result = "反";
else result = "Error";
return result;
}
public static void GameStart(Game game)
{
//當任一方錢歸零時才結束
while (!(game.Player1.Money == 0 || game.Player2.Money == 0))
{
//執行丟硬幣
var throwResult = ThrowCoinService.GetThrowCoinResult();
//判斷與紀錄
if (throwResult == "Error")
{
Console.WriteLine("Error");
break;
}
if (throwResult == game.Player1.Guess)
{
game.Player1.Money += game.Bet;
game.Player1.WinCount++;
}
else
{
game.Player1.Money -= game.Bet;
game.Player1.LoseCount++;
}
if (throwResult == game.Player2.Guess)
{
game.Player2.Money += game.Bet;
game.Player2.WinCount++;
}
else
{
game.Player2.Money -= game.Bet;
game.Player2.LoseCount++;
}
game.RoundCount++;
//輸出結果
LogService.WriteLog(game, throwResult);
}
}
}
internal static class LogService
{
public static void WriteLog(Game game,string throwResult)
{
Console.WriteLine($"第{game.RoundCount}次比賽,投擲結果為\"{throwResult}\":");
Console.WriteLine($"{game.Player1.Name}--勝:{game.Player1.WinCount} 敗:{game.Player1.LoseCount} 剩餘金額:{game.Player1.Money}");
Console.WriteLine($"{game.Player2.Name}--勝:{game.Player2.WinCount} 敗:{game.Player2.LoseCount} 剩餘金額:{game.Player2.Money}");
Console.WriteLine($"----------------------------------");
}
}
這邊將猜正反簡單化,讓2人固定分別猜正與反。
金額10元就好,比較快結束。
internal class Program
{
static void Main(string[] args)
{
//玩家
Person A = new Person("Amy", 10);
Person B = new Person("Bob", 10);
//雙方選擇正or反
A.Guess = "正";
B.Guess = "反";
Game game = new Game
{
//賭注金額
Bet = 1,
//遊戲次數
RoundCount = 0,
Player1 = A,
Player2 = B
};
ThrowCoinService.GameStart(game);
Console.ReadLine();
}
}