简单的打字母的游戏
1、先看图
2、思路很简单:
窗体上放一个Timer控件,在指定的时间间隔往窗体中添加一个Label控件,用Label控件显示随机生成的字母;
敲键时,遍历窗体中所有的Label控件,如果其Text值与键盘字母相同则移除该控件;
注意,一旦找到就要终止循环,否则会清楚所有的Text值和敲得字母相同的Label ;
这里,只适用了大写字母A-Z,其AscII码为65-90,便于生成随机字母
3、代码
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PrintLetter
{
public partial class Letter : Form
{
public Letter()
{
InitializeComponent();
}
private void Letter_Load(object sender, EventArgs e)
{
//A-Z 65-90
//a-z 97
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
//在窗体中新增一个Label控件
//并让把随机生成的字母赋值给Label的Text属性
Random rdLetter = new Random();
Label lbl = new Label();
lbl.Text = Convert.ToString((char)rdLetter.Next(65, 90));
lbl.Location = new Point(rdLetter.Next(10, this.ClientSize.Width-10), 0);
lbl.Size = new Size(20, 20);
lbl.Font = new Font("宋体", 15f); ;
this.Controls.Add(lbl);
foreach (Control c in this.Controls)
{
Label lblControl = (Label)c;
lblControl.Location = new Point(lblControl.Location.X,
lblControl.Location.Y + 5);
}
}
private void Letter_KeyUp(object sender, KeyEventArgs e)
{
//遍历当前窗体中的所有Label控件,
//如果Label控件的Text值和当前按下的键的值相等
//则移除该控件,并让总分数+5
foreach (Control c in this.Controls)
{
Label lblControl = (Label)c;
if (lblControl.Text == e.KeyCode.ToString())
{
this.Controls.Remove(c);
this.Text = Convert.ToString(int.Parse(this.Text) + 5);
break;
}
}
}
}
}
using System.Drawing;
using System.Windows.Forms;
namespace PrintLetter
{
public partial class Letter : Form
{
public Letter()
{
InitializeComponent();
}
private void Letter_Load(object sender, EventArgs e)
{
//A-Z 65-90
//a-z 97
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
//在窗体中新增一个Label控件
//并让把随机生成的字母赋值给Label的Text属性
Random rdLetter = new Random();
Label lbl = new Label();
lbl.Text = Convert.ToString((char)rdLetter.Next(65, 90));
lbl.Location = new Point(rdLetter.Next(10, this.ClientSize.Width-10), 0);
lbl.Size = new Size(20, 20);
lbl.Font = new Font("宋体", 15f); ;
this.Controls.Add(lbl);
foreach (Control c in this.Controls)
{
Label lblControl = (Label)c;
lblControl.Location = new Point(lblControl.Location.X,
lblControl.Location.Y + 5);
}
}
private void Letter_KeyUp(object sender, KeyEventArgs e)
{
//遍历当前窗体中的所有Label控件,
//如果Label控件的Text值和当前按下的键的值相等
//则移除该控件,并让总分数+5
foreach (Control c in this.Controls)
{
Label lblControl = (Label)c;
if (lblControl.Text == e.KeyCode.ToString())
{
this.Controls.Remove(c);
this.Text = Convert.ToString(int.Parse(this.Text) + 5);
break;
}
}
}
}
}