猜字遊戲原始碼
阿新 • • 發佈:2019-01-13
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; using System.Threading; namespace 製作猜字遊戲 { public partial class Frm_main : Form { public int G_int_num; //定義欄位,模擬全域性變數 public int G_int_temp;//定義欄位,模擬全域性變數 public int G_time_num;//定義欄位,模擬全域性變數 Thread G_th;//開闢一個程序 public Frm_main() { InitializeComponent();//初始化form上的控制元件 this.Text = "製作一個數字猜猜看小遊戲";//更改視窗的標題 } private void button1_Click(object sender, EventArgs e)//按鍵觸發事件 { //RemoveControl(); int P_int_x = 10;//x軸初始座標為10 int P_int_y = 60;//y軸初始座標為60 for (int i = 0; i < 100; i++)//新增100個按鈕 { Button bt = new Button(); //建立Button控制元件bt bt.Text = (i + 1).ToString();//設定button控制元件的文字值 bt.Name = (i + 1).ToString();//設定Button的Name屬性 bt.Width = 35;//按鈕的寬度 bt.Height = 35;//按鈕的高度 bt.Location = new Point(P_int_x, P_int_y);//定義button控制元件的位置 bt.Click += new EventHandler(bt_Click); P_int_x += 36; if ((i + 1) % 10 == 0) { P_int_x = 10; P_int_y += 36; } Controls.Add(bt); } G_th = new System.Threading.Thread(delegate () { int P_int_count = 0;//初始化計數器 while (true)//開始無限迴圈 { P_int_count = (++P_int_count > 100000) ? 0 : P_int_count; /* 三元表示式判斷P_int_count>10000是否成立,如果成立則P_int_count=0, 如果不成立則P_int_count=P_int_count;*/ this.Invoke((MethodInvoker)delegate { lb_time.Text = P_int_count.ToString(); }); System.Threading.Thread.Sleep(1000); G_time_num = P_int_count; } }); G_th.IsBackground = true; G_th.Start(); Random G_random = new Random();//建立一個隨機數函式 G_int_num = G_random.Next(1, 100);//產生一個隨機數,在1~100之間 button1.Enabled = false;//按鈕失效 } private void bt_Click(object sender, EventArgs e) { Control P_control = sender as Control; if (int.Parse(P_control.Name) == G_int_num) { P_control.BackColor = Color.Gold; P_control.Text = "命中"; MessageBox.Show("恭喜您!!猜中了!\n"+ string.Format("用了{0}秒鐘,按{1}次", G_time_num, GetCount())); G_th.Abort(); // 執行緒終止 RemoveControl();//清除所有按鍵 //goto ; //Environment.Exit(0); //強行關閉窗體 } else { if (int.Parse(P_control.Name) < G_int_num) { P_control.BackColor = Color.Green; //背景 設定 綠色 P_control.Enabled = false; //按鈕停用 P_control.Text = "小"; MessageBox.Show("小於隨機數"); } else { P_control.BackColor = Color.Red; //背景 設定 紅色 P_control.Enabled = false; //按鈕停用 P_control.Text = "大"; MessageBox.Show("大於隨機數"); } // } } } string GetCount() { int P_int_temp = 0; //初始化計數器 foreach (Control c in Controls)//遍歷控制元件在controls中 { if (!c.Enabled) P_int_temp++; // 計數器累加 } return P_int_temp.ToString();// 把整數變成字串返回 } void RemoveControl()//刪除控制元件方法 { for (int i = 0; i < 100; i++) //遍歷 100 個按鈕 { if (Controls.ContainsKey((i + 1).ToString())) //判斷中 是否 有此按鈕 { for (int j = 0; j < Controls.Count; j++) { if (Controls[j].Name == (i + 1).ToString()) { Controls.RemoveAt(j);//從指定索引位置的控價集合中刪除控制元件 break; } } } } } } }