运行效果图如下:
按钮:开始、结束、退出。
菜单:设置(开始游戏、结束游戏、退出游戏),查看(正确率、所用时间)。
页面:
控件属性:
timer1:
enabled选择false,Interval设置为5.
timer2:
enabled选择false,Interval设置为1000.
代码:
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 WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int x = 200, y, num;
private DateTime dt1, dt2;
private int count_all = 0;
private int count_correct = 0;
private TimeSpan ts;
Random rd = new Random();
private void btnStart_Click(object sender, EventArgs e)
{
tsmiRate.Enabled = true;//启用控件
dt1 = DateTime.Now;
timer1.Start();
timer2.Start();
textBox1.Visible = true;
num = rd.Next(65, 90);
}
private void btnStop_Click(object sender, EventArgs e)
{
tsmiTime.Enabled = true;
dt2 = DateTime.Now;
timer1.Stop();
timer2.Stop();
textBox1.Visible = false;
MessageBox.Show("游戏结束。", "提示");
}
private void btnQuit_Click(object sender, EventArgs e)
{
timer1.Stop();
textBox1.Visible = false;
DialogResult dr = MessageBox.Show("确定要退出吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (dr == DialogResult.OK)
Application.Exit();
}
private void tsmiStart_Click(object sender, EventArgs e)
{
dt1 = DateTime.Now;
timer1.Start();
timer2.Start();
textBox1.Visible = true;
num = rd.Next(65, 90);
}
private void tsmiStop_Click(object sender, EventArgs e)
{
dt2 = DateTime.Now;
timer1.Stop();
timer2.Stop();
textBox1.Visible = false;
MessageBox.Show("游戏结束!", "提示");
}
private void tsmiQuit_Click(object sender, EventArgs e)
{
timer1.Stop();
textBox1.Visible = false;
DialogResult dr = MessageBox.Show("确定要退出吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (dr == DialogResult.OK)
Application.Exit();
}
private void tsmiRate_Click(object sender, EventArgs e)
{
double corr_rate = count_correct * 1.0 / count_all;
string s = string.Format("{0,5:P2}",corr_rate);
MessageBox.Show("正确率为:" + s, "正确率");
}
private void tsmiTime_Click(object sender, EventArgs e)
{
ts = dt2 - dt1;
MessageBox.Show("所用时间为:" + ts.Seconds + "(s)", "所用时间");
}
private void timer1_Tick(object sender, EventArgs e)//???
{
y++;
if (y > this.ClientSize.Height - 5)
y = 20;
textBox1.Text = ((char)num).ToString().ToUpper();
textBox1.Location = new Point(x, y);
textBox1.ForeColor = Color.FromArgb(rd.Next(0, 255), rd.Next(0, 255), rd.Next(0, 255));
}
private void timer2_Tick(object sender, Eve