简单的打字母的游戏
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;
}
}
}
}
}
分类:
Windows应用程序
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述