Content Name:labPlayer
content Name:labComputer
Player Name:labResult
Player类的实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Guess
{
publicclass Player
{
//自动属性//publicstring Punch { get; set; }
publicintPlay(string punch)
{
this.Punch = punch;
int num = 0;
switch (punch)
{
case"tone":
num = 1;
break;
case"jian":
num = 2;
break;
case"bu":
num = 3;
break;
}
return num;
}
}
}
Computer类的实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Guess
{
publicclass Computer
{
publicstring Punch { get; set; }
publicintPlay()
{
Random r = new Random();//随机数//int num=r.Next(1,4);
switch(num)
{
case1:
this.Punch = "tone";
break;
case2:
this.Punch = "jian";
break;
case3:
this.Punch = "bu";
break;
}
return num;
}
}
}
Referee(裁判)类的实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Guess
{
publicclass Referee
{
//判断谁赢谁输publicstringWin(int playerNum,int computerNum)
{
if(playerNum-computerNum==0)
{
return"double win";
}
elseif(playerNum-computerNum==-1||playerNum-computerNum==2)
{
return"player win";
}
else
{
return"computer win";
}
}
}
}
主程序的实现
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 Guess
{
publicpartialclass Form1 : Form
{
publicForm1()
{
InitializeComponent();
}
//选中需要重构的代码,右键,Refactor->Extract MethodprivatevoidPlay(string name)
{
Player p = new Player();
int pNum = p.Play(name);
labPlayer.Text = p.Punch;
Computer c = new Computer();
int cNum = c.Play();
labComputer.Text = p.Punch;
Referee r = new Referee();
string result = r.Win(pNum, cNum);
labresult.Text = result;
}
//在图形化界面中,把各个按钮的click事件绑定该函数privatevoidbutton_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
Play(btn.Text);
}
}
}