C# Winform实现石头剪刀布游戏
本文实例为大家分享了Winform实现石头剪刀布游戏的具体代码,供大家参考,具体内容如下
新建一个windows窗体程序,用数字1代表石头,用数字2代表剪刀,用数字3代表布,结果取玩家和电脑出拳之差,有三种结果
玩家赢:-1,2
平手:0
玩家输:其它值
新建3个类:
1)Computer.cs电脑随机出拳
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespace石头剪刀布 { classComputer { publicstringFist { get; set; } publicintShowFist() { Randomrnd=newRandom(); intfist=rnd.Next(1,4); switch(fist) { case1:Fist="石头";break; case2:Fist="剪刀";break; case3:Fist="布";break; } returnfist; } } }
2)、Judge.cs裁判类判断输赢
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespace石头剪刀布 { classJudge { publicenumRESULT { 玩家赢, 电脑赢, 平手 } publicstaticRESULTWhoWin(intplayerNum,intcomputerNum) { intresult=playerNum-computerNum; if(result==-1||result==2) { returnRESULT.玩家赢; } elseif(result==0) { returnRESULT.平手; } else { returnRESULT.电脑赢; } } } }
3)、Player.cs玩家,出拳
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespace石头剪刀布 { classPlayer { publicstaticintShowFist(stringfist) { switch(fist) { case"石头":return1; case"剪刀":return2; case"布":return3; default:return0; } } } }
界面后台实现代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.IO; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; namespace石头剪刀布 { publicpartialclassForm1:Form { publicForm1() { InitializeComponent(); } //////点击石头按钮 /// ////// privatevoidbtnStone_Click(objectsender,EventArgse) { Stringfist="石头"; Game(fist); } /// ///点击剪刀按钮 /// ////// privatevoidbtnScissors_Click(objectsender,EventArgse) { Stringfist="剪刀"; Game(fist); } /// ///点击布按钮 /// ////// privatevoidbtnCloth_Click(objectsender,EventArgse) { Stringfist="布"; Game(fist); } //背景图片轮播 String[]paths=Directory.GetFiles(@"C:\work\stone");//此目录里面必须有图片,否则会报错 privatevoidtimer1_Tick(objectsender,EventArgse) { this.BackgroundImage=Image.FromFile(paths[newRandom().Next(0,paths.Length)]); } staticintplayerWinTimes=0;//玩家赢的次数 staticintgameTimes=0;//总共次数 staticinttieTimes=0;//平手次数 /// ///通用方法 /// ///privatevoidGame(Stringfist) { gameTimes++; lbPlayer.Text=fist; intplayerNum=Player.ShowFist(fist); Computercpu=newComputer(); intcpuNum=cpu.ShowFist(); lbComputer.Text=cpu.Fist; Judge.RESULTresult=Judge.WhoWin(playerNum,cpuNum); lbJudge.Text=result.ToString(); lbStatistics.Text="统计信息:\n\n1.您赢了"+playerWinTimes+"场比赛!\n\n"+"2.平手了"+tieTimes+"次;\n\n"+"3.输掉了"+(gameTimes-playerWinTimes-tieTimes)+"场比赛;\n\n"+"4.共进行了"+gameTimes+"场比赛!\n\n"; if(result==Judge.RESULT.玩家赢) { playerWinTimes++; MessageBox.Show("恭喜,您已经赢了"+playerWinTimes+"场比赛!"+"共进行了"+gameTimes+"场比赛!"); } elseif(result==Judge.RESULT.平手) { tieTimes++; } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。