基于视频讲解《通过编程制作一款猜数字的小游戏》的完整源代码:
设计界面
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.Threading;using System.Windows.Forms;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } Thread th; Random rand = new Random(); int randnum; private void button1_Click(object sender, EventArgs e) { int x = 10; int y = 60; for (int i = 1; i <= 50; i++) { Button bt = new Button(); bt.Text = i.ToString(); bt.Name = i.ToString(); bt.Width = 40; bt.Height = 40; bt.Location = new Point(x, y); bt.Click += new EventHandler(bt_Click); x += 41; if (i % 10 == 0) { x = 10; y += 41; } Controls.Add(bt); } //新建一个线程 th = new Thread(delegate () { int i = 0; while (true) { i = ++i > 1000000 ? 0 : i; this.Invoke( (MethodInvoker)delegate { label1.Text = i.ToString(); }); Thread.Sleep(1000); } }); th.IsBackground = true; th.Start(); randnum = rand.Next(1, 50); button1.Enabled = false; } private void bt_Click(object sender, EventArgs e) { Control bc = sender as Control; if (int.Parse(bc.Name) > randnum) { bc.BackColor = Color.Pink; bc.Enabled = false; bc.Text = "大"; } if (int.Parse(bc.Name) < randnum) { bc.BackColor = Color.Green; bc.Enabled = false; bc.Text = "小"; } if (int.Parse(bc.Name) == randnum) { bc.BackColor = Color.Red; bc.Enabled = false; bc.Text = "中"; th.Abort(); // 线程终止 MessageBox.Show(string.Format("终于猜中了,用时{1}秒,猜了{0}次!", GetCount(), label1.Text), "恭喜"); } } string GetCount() { int pcount = -1; foreach (Control c in Controls) { if (!c.Enabled) { pcount++; } } return pcount.ToString(); } }}