C#实现剪刀石头布游戏
程序员文章站
2023-12-12 21:23:52
本文实例为大家分享了c#实现剪刀石头布游戏的具体代码,供大家参考,具体内容如下
游戏界面如下所示:
首先我们必须知道要创建三个类玩家类,电脑类,裁判类
1、玩家类...
本文实例为大家分享了c#实现剪刀石头布游戏的具体代码,供大家参考,具体内容如下
游戏界面如下所示:
首先我们必须知道要创建三个类玩家类,电脑类,裁判类
1、玩家类中的代码为
using system; using system.collections.generic; using system.linq; using system.text; namespace playgame { class player { public int showfist(string str) { int num = 0; switch (str) { case "剪刀": num = 1; break; case "石头": num = 2; break; case "布": num = 3; break; } return num; } } }
2、电脑类中的代码为
using system; using system.collections.generic; using system.linq; using system.text; namespace playgame { class computer { /// <summary> /// 存储电脑出的拳头 /// </summary> public string fist { get; set; } public int cpushowfist() { random r = new random(); int cnum=r.next(1,4); switch(cnum) { case 1: this.fist = "剪刀"; break; case 2: this.fist = "石头"; break; case 3: this.fist = "布"; break; } return cnum; } } }
3、裁判类中的代码为
using system; using system.collections.generic; using system.linq; using system.text; namespace playgame { class judge { public enum result { 电脑赢,玩家赢,平局 } public static result caipan(int playernum, int cpunum) { if ((playernum - cpunum) == 1 || (playernum - cpunum) == -2) return result.玩家赢; else if((playernum-cpunum)==0) return result.平局; else return result.电脑赢; } } }
4、其他的事件代码
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; namespace playgame { public partial class form1 : form { public form1() { initializecomponent(); } private void btncut_click(object sender, eventargs e) { newmethod(btncut.text); } private void newmethod(string str) { lblplayer.text = str; player player = new player(); int playernum = player.showfist(str); computer cpu = new computer(); int cpunum = cpu.cpushowfist(); lblcomputer.text = cpu.fist; playgame.judge.result res = judge.caipan(playernum, cpunum); lbljudge.text = res.tostring(); } private void btnstone_click(object sender, eventargs e) { newmethod(btnstone.text); } private void btnbu_click(object sender, eventargs e) { newmethod(btnbu.text); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。