簡單編程小游戲代碼 小游戲編程代碼大全



文章插圖
簡單編程小游戲代碼 小游戲編程代碼大全

文章插圖
基于視頻講解《通過編程制作一款猜數字的小游戲》的完整源代碼:
設計界面
【簡單編程小游戲代碼 小游戲編程代碼大全】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();}}}