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;
}
/// <summary>
/// 将用户输入的数字转换成相应的拳头
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 从控制台接收数据并验证有效性
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
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;
}
}
裁判类示例代码