對於新手的我,如今搞不了大項目,只有從小實驗小項目一點一滴作起。今天就把本身寫的猜拳小遊戲給你們分享一下。適合新手一塊兒學習。。dom
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 _10._5石頭剪刀布 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // button1.Click += (s, e) => { shitou(); }; button2.Click += (s, e) => { jiandao(); };//別忘了,事件只能出如今+=、-=左邊 button3.Click += (d, e) => { bu(); }; } //其實button1.Click += (s, e) => { shitou(); };和下面的這寫法是同樣的 private void button1_Click(object sender, EventArgs e) { shitou(); } //石頭 public void shitou() { label4.Text = button1.Text; label3.Text = bj(toint(), pc()); } //剪刀 public void jiandao() { label4.Text = button2.Text; label3.Text = bj(toint(), pc()); } //布 public void bu() { label4.Text = button3.Text; label3.Text = bj(toint(), pc()); } /// <summary> /// 電腦隨機顯示,還有相應的值替代它 /// </summary> /// <returns></returns> public int pc() { Random ran = new Random(); int vpc = ran.Next(1, 4); // string strpc;//這樣寫會浪費資源,在堆中要開闢不少空間 //這樣,每次調用pc方法時strpc都是初始爲空的。 //重要的是string類型是引用類型。 string strpc = string.Empty;//初始爲空 switch (vpc) { case 1: strpc = "石頭"; break; case 2: strpc = "剪刀"; break; case 3: strpc = "布"; break; default: throw new Exception("未知錯誤"); } label5.Text = strpc; return vpc; } /// <summary> /// 把剪刀石頭布用數字表示 /// </summary> /// <returns></returns> public int toint() { int n; switch (label4.Text) { case "石頭": n = 1; break; case "剪刀": n = 2; break; case "布": n = 3; break; default: throw new Exception("出錯了"); } return n; } //比較 public string bj(int user, int pc) { int tmp = user - pc; string bj = string.Empty; if (tmp == 1 || tmp == -2) { bj = "你贏了"; } else if (tmp == 0) { bj = "平局"; } else { bj = "你輸了"; } return bj; } } }