先定義固定的手勢常數,這裡使用靜態類別(也可用枚舉或 Smart Enum):
public static class Options
{
public const string JianDao = "剪刀";
public const string ShiTou = "石頭";
public const string Bu = "布";
}
public interface IPlayer
{
string GetName();
string Show(); // 出拳
}
public class Grandpa : IPlayer
{
private static readonly Random _rnd = new Random();
public string GetName() => "爺爺";
public string Show()
{
int i = _rnd.Next(3);
return i switch
{
0 => Options.JianDao,
1 => Options.ShiTou,
_ => Options.Bu
};
}
}
public class Grandson : IPlayer
{
public string GetName() => "孫子";
public string Show() => Options.JianDao; // 永遠出剪刀
}
public class Game
{
public void PlayRound(IPlayer p1, IPlayer p2)
{
string g1 = p1.Show(), g2 = p2.Show();
Console.WriteLine($"{p1.GetName()} 出 {g1},{p2.GetName()} 出 {g2}");
string result = Judge(g1, g2);
Console.WriteLine(result);
}
private string Judge(string a, string b)
{
if (a == b) return "平手";
return (a, b) switch
{
(Options.JianDao, Options.Bu) => "剪刀勝",
(Options.Bu, Options.ShiTou) => "布勝",
(Options.ShiTou, Options.JianDao) => "石頭勝",
_ => "另一方勝"
};
}
}
爺爺 出 石頭,孫子 出 剪刀
石頭勝
爺爺 出 布,孫子 出 剪刀
剪刀勝
IPlayer 只定義必要契約,不綁定具體策略GameGame.Judge,玩家只負責出拳