33.winform之实现剪刀石头布
效果
实现
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp3 {
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;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp3 {
class Computer {
/// <summary>
/// 自动属性,存储电脑出的拳头
/// </summary>
public string Fist {
get;
set;
}
public int ShowFist() {
Random r = new Random();
int rNumber = r.Next(1, 4);
switch (rNumber) {
case 1:
this.Fist = "石头";
break;
case 2:
this.Fist = "剪刀";
break;
case 3:
this.Fist = "布";
break;
}
return rNumber;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp3 {
public enum Result {
玩家赢,
电脑赢,
平手
}
class Referee {
public static Result Judge(int playerNumber, int computerNumber) {
if (playerNumber - computerNumber == -1 || playerNumber - computerNumber == 2) {
return Result.玩家赢;
} else if (playerNumber - computerNumber == 0) {
return Result.平手;
} else {
return Result.电脑赢;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
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 playerNumber = player.ShowFist(str);
//电脑出拳
Computer computer = new Computer();
int computerNumber = computer.ShowFist();
lblComputer.Text = computer.Fist;
//裁判
Result result = Referee.Judge(playerNumber, computerNumber);
lblReferee.Text = result.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);
}
}
}
石头 1 剪刀 2 布 3
通过相减来判断输赢情况
玩家赢了: 1 2=-1 2 3=-1 3 1=2
平手: 相减 =0
另外一种情况 :电脑赢了