初始界面:
要点:
1、生成随机数(我自己较多采用的Guid)
2、多个按钮绑定同一个事件
玩家类
namespace NET
{
public class Player
{
/// <summary>
/// 存储出拳的内容
/// </summary>
public string FistName { get; set; }
/// <summary>
///
/// </summary>
public int Play(string name)
{
// 存储出拳的内容
this.FistName = name;
switch (this.FistName)
{
case "石头":
return 1;
case "剪刀":
return 2;
case "布":
return 3;
default:
return 0;
}
}
}
}
电脑类
using System;
namespace NET
{
public class Computer
{
/// <summary>
/// 存储出拳的内容
/// </summary>
public string FistName { get; set; }
public int RandomPlay()
{
// 随机数
Random random = new Random(System.Guid.NewGuid().GetHashCode());
int num = random.Next(1, 4);
switch (num)
{
case 1: this.FistName = "石头"; break;
case 2: this.FistName = "剪刀"; break;
case 3: this.FistName = "布"; break;
}
return num;
}
}
}
裁判逻辑:
裁判类
namespace NET
{
public class Judge
{
public string Win(int play, int computer)
{
int result = play - computer;
switch (result)
{
case -1:
case 2:
return "玩家赢了";
case -2:
case 1:
return "电脑赢了";
default:
return "平手";
}
}
}
}
Form代码
using System;
using System.Windows.Forms;
namespace NET
{
public partial class 猜拳 : Form
{
public 猜拳()
{
InitializeComponent();
}
private void btnPlayer_Click(object sender, EventArgs e)
{
Button btnPlayer = (Button)sender;
Player p = new Player();
int playerName = p.Play(btnPlayer.Text); // 获取出拳内容的数字结果
lblPlayer.Text = p.FistName; // 显示玩家出拳内容
Computer c = new Computer();
int computerName = c.RandomPlay();
lblComputer.Text = c.FistName; // 显示出拳内容
Judge judge = new Judge();
lblResult.Text = judge.Win(playerName, computerName); // 显示输赢结果
}
}
}