我正在创建一个随机数猜测游戏,但我遇到了生成相同数字的生成器的问题,除非我关闭它并重新打开它。 我有“你的号码太小/太大”。这样可行。但是我希望一旦点击按钮检查猜测就改变数字。什么是错的?
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 Guess_the_number_1
{
public partial class Form1 : Form
{
int randomNumber;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random random = new Random();
randomNumber = random.Next(0, 10);
}
private void buttonCheckGuess_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(textboxGuess.Text) == randomNumber)
{
MessageBox.Show("Your Guessed Correctly! The Number Is: " + textboxGuess.Text);
}
else if (Convert.ToInt32(textboxGuess.Text) < randomNumber)
{
MessageBox.Show("The Number Is Larger Than: " + textboxGuess.Text);
}
else if (Convert.ToInt32(textboxGuess.Text) > randomNumber)
{
MessageBox.Show("The Number Is Smaller Than: " + textboxGuess.Text);
}
else
{
MessageBox.Show("Your Guessed Incorrectly. The Random Number Is Not: " + textboxGuess.Text);
}
}
}
}
答案 0 :(得分:4)
在加载时生成第一个随机数,然后在用户猜到正确的数字时再次生成。
将您的Random
对象作为字段(类成员)并在方法中使用它:
private void MakeNewRandomNumber()
{
randomNumber = random.Next(0, 10);
}
在表单加载(当前正在生成数字的位置)调用此方法,并在验证猜测后再次在单击处理程序中调用此方法:
private void buttonCheckGuess_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(textboxGuess.Text) == randomNumber)
{
MessageBox.Show("Your Guessed Correctly! The Number Is: " + textboxGuess.Text);
MakeNewRandomNumber();
}
答案 1 :(得分:0)
每次单击此按钮时,您需要创建一个随机数。
int randomNumber;
Random random;
public Form1()
{
InitializeComponent();
random = new Random();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonCheckGuess_Click(object sender, EventArgs e)
{
randomNumber = random.Next(0, 10);
if (Convert.ToInt32(textboxGuess.Text) == randomNumber)
{
MessageBox.Show("Your Guessed Correctly! The Number Is: " + textboxGuess.Text);
}
else if (Convert.ToInt32(textboxGuess.Text) < randomNumber)
{
MessageBox.Show("The Number Is Larger Than: " + textboxGuess.Text);
}
else if (Convert.ToInt32(textboxGuess.Text) > randomNumber)
{
MessageBox.Show("The Number Is Smaller Than: " + textboxGuess.Text);
}
else
{
MessageBox.Show("Your Guessed Incorrectly. The Random Number Is Not: " + textboxGuess.Text);
}
}
}