柳州职业技术学院物联网应用技术2班-20210320018-李俊运
设计如图6-8a所示的窗体。单击“开始游戏”按钮,随机给出一个[0,9]之间的整数。然后让你猜是什么数字。你可以随便猜一个数字,游戏会提示大小,从而缩小结果范围。经过几次猜测与提示后,最终猜中答案。
游戏设计思路:
(1)窗体打开时,文本框只读,即禁止在文本框标输入任何内容,且焦点在“开始游戏”按钮上。如图6-8a所示。
(2)点击“开始游戏”按钮,则①取消文本框只读;②但在文本框中只能输入0~9十种数字;③生成一个0~99的随机整数作为目标数,供游戏者猜。如图6-8b所示。
(3)游戏者在文本框标输入数字。若没猜中,给出大小提示,可以继续输入数字。如图6-8c所示。
(4)若猜中,也给出提示,清空文本框,且重新设置文本框为只读,如图6-8c所示。
(5)游戏者可以点击“结束”按钮结束程序,也可以点击“开始游戏”按钮开始新的一轮游戏,此时随机产生目标数字被重新生成。
代码实现:
窗体中只需添加控件即可
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace text6
{
public partial class Form8 : Form
{
int num;
string str;
int b = 0;
public Form8()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
}
private void Form8_Load(object sender, EventArgs e)
{
this.label1.Text = "输入0~99之间整数:";
this.Text = "猜数字游戏";
this.button1.Text = "开始游戏";
this.button2.Text = "结束";
this.textBox1.ReadOnly = true;
}
private void button1_Click(object sender, EventArgs e)
{
this.textBox1.ReadOnly = false;
Random random = new Random();
num = random.Next(0, 99);
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar)))
{
e.Handled = true;
}
if (e.KeyChar == (char)13)
{
str = textBox1.Text;
b = int.Parse(str);
if (b > num)
{
DialogResult d = MessageBox.Show("大啦!", "", MessageBoxButtons.OK);
}
else if (b < num)
{
DialogResult d = MessageBox.Show("小啦!", "", MessageBoxButtons.OK);
}
else
{
DialogResult d = MessageBox.Show("猜中啦!", "", MessageBoxButtons.OK);
this.textBox1.Text = null;
this.textBox1.ReadOnly = true;
}
}
}
}
}
就可以实现猜字小游戏了。