本文实例为大家分享了C#实现打字游戏的具体代码,供大家参考,具体内容如下
思路:
1、有一个游戏界面,我用panel作为游戏界面
2、开始生成字母
打字游戏的字母是不断生成的,所以用计时器timer来生成字母
所有生成的字母设置tag方便寻找
3、字母下落
字母下落是一个持续的动作,所以也在计时器里做
在计时器里通过foreach遍历panel中的所有控件,同时通过tag找到字母,让字母下降
4、生成子弹
通过获取键盘事件生成子弹
5、子弹与字母相碰
代码:
private void Form1_Load(object sender, EventArgs e)
{
this.panel1.BackColor = Color.White;
timer1.Start();
timer2.Start();
timer1.Interval = 1000;
timer2.Interval = 100;
fj.Tag = "feiji";
fj.Size = new Size(30, 40);
fj.BackColor = Color.Black;
fj.Text = "飞机";
fj.TextAlign = ContentAlignment.MiddleCenter;
fj.ForeColor = Color.White;
fj.Location = new Point(panel1.Width / 2 - fj.Width / 2, panel1.Height - fj.Height);
panel1.Controls.Add(fj);
}
Label fj = new Label();
Random r = new Random();
private void timer1_Tick(object sender, EventArgs e)
{
Label zm = new Label();
zm.Tag = "zimu";
zm.Text = ((char)r.Next(97, 123)).ToString();
zm.Font = new Font("", r.Next(20, 30));
zm.AutoSize = true;
zm.Location = new Point(r.Next(0, panel1.Width - zm.Width), 0);
zm.ForeColor = Color.FromArgb(r.Next(255), r.Next(255), r.Next(255));
panel1.Controls.Add(zm);
}
private void timer2_Tick(object sender, EventArgs e)
{
foreach (Control item in panel1.Controls)
{
if (item.Tag.ToString() == "zimu"||item.Tag.ToString()=="zzm")
{
item.Top += 5;
if (item.Top >= panel1.Height)
{
item.Dispose();
}
}else if (item.Tag.ToString() == "zidan")
{
item.Top -= 9;
foreach (Control con in panel1.Controls)
{
if (con.Tag.ToString() == "zzm")
{
if (con.Top + con.Height >= item.Top)
{
con.Dispose();
item.Dispose();
SoundPlayer ply = new SoundPlayer();
ply.SoundLocation = ".../.../Sound/MyBomb.wav";
ply.Play();
}
}
}
}
}
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
foreach (Control item in panel1.Controls)
{
if (item.Tag.ToString() == "zimu")
{
if (item.Text == e.KeyChar.ToString())
{
Label zd = new Label();
zd.Tag = "zidan";
zd.Size = new Size(20, 20);
item.Tag = "zzm";
zd.BackColor = Color.Red;
zd.Location = new Point(item.Left + item.Width / 2 - zd.Width / 2, fj.Top - fj.Height);
fj.Left = item.Left + item.Width / 2 - fj.Width / 2;
panel1.Controls.Add(zd);
return;
}
}
}
}
您可能感兴趣的文章:C#实现打字小游戏C#实现简单打字游戏C#实现简单打字小游戏