玩法分析:
把三种手势设置三个数
1、石头 2、剪刀 3、布
玩家 - 电脑
玩家赢:只有以下3种结果,,,2个数,-1 和2
1 - 2 = -1;
2 - 3 = -1;
3 - 1 = 2;
平手:结果为0即为平手
电脑赢:else电脑赢
创建3个类:
玩家类(Player):
方法:得到玩家的数,
电脑类(Computer):
方法:电脑出拳需要一个随机数
裁判(Judge):
方法:判断输赢
代码如下:
玩家类
class Player { public int ShowFist(string fist) { int num = 0; switch (fist) { case "石头": num = 1; break; case "剪刀": num = 2; break; case "布": num = 3; break; } return num; } }
电脑类
class Computer { ////// 存储电脑出的手势 /// public string Fist { get; set; } public int ShowFist() { Random r = new Random(); int rNum = r.Next(1, 4); switch(rNum) { case 1: this.Fist = "石头"; break; case 2: this.Fist = "剪刀"; break; case 3: this.Fist = "布"; break; } return rNum; } }
裁判类
public enum Result { 玩家赢, 电脑赢, 平手 } class Judge { public static Result Judged(int playerNum, int cpuNum) { if (playerNum - cpuNum == -1 || playerNum - cpuNum == 2) { return Result.玩家赢; } else if(playerNum - cpuNum == 0) { return Result.平手; } else { return Result.电脑赢; } } }
主窗体类:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label3_Click(object sender, EventArgs e) { } private void btnStone_Click(object sender, EventArgs e) { string str = "石头"; PlayGame(str); } private void PlayGame(string str) { lblPlayer.Text = str; Player player = new Player(); int playerNum = player.ShowFist(str); Computer cpu = new Computer(); int cpuNum = cpu.ShowFist(); lblComputer.Text = cpu.Fist; Result res = Judge.Judged(playerNum, cpuNum); lblJudge.Text = res.ToString(); } private void btnCut_Click(object sender, EventArgs e) { string str = "剪刀"; PlayGame(str); } private void btnNo_Click(object sender, EventArgs e) { string str = "布"; PlayGame(str); } }