用c#写了一个简单的打游戏,实现飞机打出子弹碰到字母时消失,但是出现了一个bug,子弹可以无限发出,当字母下落时按下对应的按键时可以发出无限的子弹,然后就使程序卡死了。
以下是代码:
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 打字游戏练习
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//创建加载事件
private void Form1_Load(object sender, EventArgs e)
{
}
//创建开始按钮事件
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
timer2.Start();
}
/// <summary>
/// 计时器1 产生字母
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//添加一个随机变量
Random r = new Random();
private void timer1_Tick(object sender, EventArgs e)
{
//创建字母
//实例化一个类
Label la = new Label();
//类的属性
//大小 颜色 位置 文本 字母
la.Tag = "zimu";
la.ForeColor =Color.FromArgb(r.Next(256),r.Next(256),r.Next(256));
la.Font = new Font("楷体",r.Next(30,50));
la.Location = new Point(r.Next(0,panel1.Width-la.Width),0);
la.Text=((char)r.Next(97,123)).ToString();
//设置字母的拉伸
la.AutoSize = true;
//将实例化的类添加到工作区
panel1.Controls.Add(la);
}
/// <summary>
/// 计时器2 使字母下落
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer2_Tick(object sender, EventArgs e)
{
//从容器的集合里面取字母
foreach(Control la in panel1.Controls)
{
//判断容器集合里的是字母还是图片
if (la.GetType().Name == "Label")
{
//判断类型是不是字母
if (la.Tag.ToString() == "zimu")
{
la.Top += 5;
}
else
{
la.Top -= 5;
//当子弹上升碰到字母时两个同时消失
foreach(Control lb in panel1.Controls)
{
if(lb.GetType().Name=="Label")
{
if (lb.Tag.ToString() == "zimu")
{
if (la.Text == lb.Text)
{
if (la.Top <= lb.Top + lb.Height)
{
la.Dispose();
lb.Dispose();
}
}
}
}
}
}
}
}
}
//添加按键触发事件
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
foreach(Control la in panel1.Controls)
{
if(la.Text==((char)e.KeyValue).ToString().ToLower())
{
if(la.GetType().Name=="Label")
{
pictureBox1.Left = la.Left + la.Width / 2 - pictureBox1.Width / 2;
//造子弹
Label zidan = new Label();
//子弹的属性
//子弹的位置 大小 颜色 标记
zidan.Tag = "zidan";
zidan.Width = 20;
zidan.Height = 30;
zidan.Text = la.Text;
zidan.Location = new Point(pictureBox1.Left + pictureBox1.Width / 2 - zidan.Width / 2, pictureBox1.Top);
zidan.BackColor = Color.Black;
//将实例化的类添加到工作区
panel1.Controls.Add(zidan);
}
}
}
}
}
}
程序截图: