简单编程游戏代码大全(python简单射击小游戏代码)
程序员文章站
2024-03-26 20:58:53
基于视频讲解《通过编程制作一款猜数字的小游戏》的完整源代码:设计界面using system;using system.collections.generic;using system.compone...
基于视频讲解《通过编程制作一款猜数字的小游戏》的完整源代码:
设计界面
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();
}
}
}