玩家類示例代碼
class Player
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int ShowFist()
{
Console.WriteLine("請問,你要出什麼拳? 1.剪刀 2.石頭 3.布");
int result = ReadInt(1, 3);
string fist = IntToFist(result);
Console.WriteLine("玩家:{0}出了1個{1}", name, fist);
return result;
}
///
/// 將用戶輸入的數字轉換成相應的拳頭
///
///
///
private string IntToFist(int input)
{
string result = string.Empty;
switch (input)
{
case 1:
result = "剪刀";
break;
case 2:
result = "石頭";
break;
case 3:
result = "布";
break;
}
return result;
}
///
/// 從控制台接收數據並驗證有效性
///
///
///
///
private int ReadInt(int min,int max)
{
while (true)
{
//從控制台獲取用戶輸入的數據
string str = Console.ReadLine();
//將用戶輸入的字符串轉換成Int類型
int result;
if (int.TryParse(str, out result))
{
//判斷輸入的范圍
if (result >= min && result <= max)
{
return result;
}
else
{
Console.WriteLine("請輸入1個{0}-{1}范圍的數", min, max);
continue;
}
}
else
{
Console.WriteLine("請輸入整數");
}
}
}
}
計算機類示例代碼
class Computer
{
//生成一個隨機數,讓計算機隨機出拳
Random ran = new Random();
public int ShowFist()
{
int result = ran.Next(1, 4);
Console.WriteLine("計算機出了:{0}", IntToFist(result));
return result;
}
private string IntToFist(int input)
{
string result = string.Empty;
switch (input)
{
case 1:
result = "剪刀";
break;
case 2:
result = "石頭";
break;
case 3:
result = "布";
break;
}
return result;
}
}
裁判類示例代碼
這個類通過一個特殊的方式來判定結果