适合新手学习,C#编程基础小练习
下载:源码下载链接
1 using System; 2 using System.Windows.Forms; 3 4 namespace 猜拳小游戏 5 { 6 public partial class Form1 : Form 7 { 8 public Form1() 9 { 10 InitializeComponent(); 11 // button1.Click += (s, e) => { shitou(); }; 12 button2.Click += (s, e) => { jiandao(); };//别忘了,事件只能出现在+=、-=左边 13 button3.Click += (d, e) => { bu(); }; 14 } 15 //其实button1.Click += (s, e) => { shitou(); };和下面的这写法是一样的 16 private void button1_Click(object sender, EventArgs e) 17 { 18 shitou(); 19 } 20 21 /// <summary> 22 /// 石头 23 /// </summary> 24 public void shitou() 25 { 26 label4.Text = button1.Text; 27 label3.Text = bj(toint(), pc()); 28 } 29 30 /// <summary> 31 /// 剪刀 32 /// </summary> 33 public void jiandao() 34 { 35 label4.Text = button2.Text; 36 label3.Text = bj(toint(), pc()); 37 } 38 39 /// <summary> 40 /// 布 41 /// </summary> 42 public void bu() 43 { 44 label4.Text = button3.Text; 45 label3.Text = bj(toint(), pc()); 46 } 47 48 /// <summary> 49 /// 电脑随机显示,还有相应的值替代它 50 /// </summary> 51 /// <returns></returns> 52 public int pc() 53 { 54 Random ran = new Random(); 55 int vpc = ran.Next(1, 4); 56 // string strpc;//这样写会浪费资源,在堆中要开辟很多空间 57 //这样,每次调用pc方法时strpc都是初始为空的。 58 //重要的是string类型是引用类型。 59 string strpc = string.Empty;//初始为空 60 switch (vpc) 61 { 62 case 1: 63 strpc = "石头"; 64 break; 65 case 2: 66 strpc = "剪刀"; 67 break; 68 case 3: 69 strpc = "布"; 70 break; 71 default: 72 throw new Exception("未知错误"); 73 } 74 label5.Text = strpc; 75 return vpc; 76 } 77 78 /// <summary> 79 /// 把剪刀石头布用数字表示 80 /// </summary> 81 /// <returns></returns> 82 public int toint() 83 { 84 int n; 85 switch (label4.Text) 86 { 87 case "石头": 88 n = 1; 89 break; 90 case "剪刀": 91 n = 2; 92 break; 93 case "布": 94 n = 3; 95 break; 96 default: 97 throw new Exception("出错了"); 98 } 99 return n; 100 } 101 102 /// <summary> 103 /// 比较 104 /// </summary> 105 /// <param name="user"></param> 106 /// <param name="pc"></param> 107 /// <returns></returns> 108 public string bj(int user, int pc) 109 { 110 int tmp = user - pc; 111 string bj = string.Empty; 112 if (tmp == 1 || tmp == -2) 113 { 114 bj = "你赢了"; 115 } 116 else if (tmp == 0) 117 { 118 bj = "平局"; 119 } 120 else 121 { 122 bj = "你输了"; 123 } 124 return bj; 125 } 126 } 127 }