把很多行封装成方法的时候,选中要封装的代码,右键--->重构----->提取方法
LIstBox 用法类似于ComboBox
doubleclick:双击
单击button:click事件中
namespace CardGames
{
public enum Result
{
玩家赢了,
电脑赢了,
打成了平手
};
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string str = "石头";
label4.Text = str;
PlayGame(str);
}
private void button1_Click(object sender, EventArgs e)
{
string str = "剪刀";
label4.Text = str;
PlayGame(str);
}
private void button3_Click(object sender, EventArgs e)
{
string str = "布";
label4.Text = str;
PlayGame(str);
}
public void PlayGame(string str)//调用PlayGame
{
Player play = new Player();
Computer comp = new Computer();
Judge jud = new Judge();
int comNum = comp.ComputerFist();
int playNum = play.PlayerShow(str);
Result res =jud.JudgePlay(comNum,playNum );
label5.Text = comp.Fist;
label6.Text = res.ToString();
}
}
public class Computer //声明一个电脑类
{
//根据电脑的随机出数,完成显示和传送数据跟裁判
//由于不能直接将电脑随机出来的string显示到label5.Text中,所以使用了属性,在类外面就可以直接访问了。
public string Fist { get; set; }
public int ComputerFist()
{
Random rand = new Random();
int num = rand.Next(1,4);
switch (num)
{
case 1:
this.Fist = "石头";
break;
case 2:
this.Fist = "剪刀";
break;
case 3:
this.Fist ="布";
break;
}
return num;
}
}
public class Player //声明一个玩家类
{
public int PlayerShow(string str)// 这里的string指的是由button决定的
{
int num = 0;
switch (str)
{
case "石头":
num = 1;
break;
case "剪刀":
num = 2;
break;
case "布":
num = 3;
break;
}
return num;
}
}
public class Judge
{
public Result JudgePlay(int play,int compu)//Result 是一种类型
{
if (play - compu == 0)
{
return Result.打成了平手;
}
else if ((play - compu == -2) || (play - compu == 1))
{
return Result.玩家赢了 ;
}
else
return Result.电脑赢了 ;
}
}
}