我需要在Visual Studio中隨機數猜猜遊戲的一些幫助。我首先解決了代碼中的問題,但是我隨意使用隨機數字生成器並獲取隨機數字以移植到點擊事件中。和往常一樣,我並不真的需要代碼,而是一些關於我在做什麼錯誤的指導和/或解釋,以及是否有一種更有效的方法來在初學階段學習。以下是我的代碼,評論是我有麻煩的部分。感謝任何幫助,因爲我迄今收到的幫助是phenominal。Windows窗體應用程序 - C#隨機數猜猜遊戲
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 LAB6B
{
public partial class game : Form
{
public game()
{
InitializeComponent();
//Generate Random number between 1 and 100
//Not sure if there is a better way?
Random rand1 = new Random();
int num1 = rand1.Next(1,50);
int num2 = rand1.Next(1,50);
int answer = num1 + num2;
}
private void evaluate_Click(object sender, EventArgs e)
{
int count = 0;
int choice = Convert.ToInt32(guess);
if (guess.Text != string.Empty)
{
// set counter to keep track of how many tries
// should this be done by a loop or will it count without a loop?
count++;
//compare user input against random number
//Can’t import the random number for comparision
if (choice < answer)
{
Evaluate.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "Too Low!";
Clear.Visible = true;
BackColor = Color.LightSeaGreen;
}
else if (choice > answer)
{
Evaluate.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "Too High!";
Clear.Visible = true;
BackColor = Color.SlateBlue;
}
else
{
//Display correct message along with how many times it took to get it
MessageBox.Show(" Eso es CORRECTO! It took you {0} tries. ", count);
}
}
}
private void Clear_Click(object sender, EventArgs e)
{
guess.Text = "";
Evaluate.Visible = true;
lblMessage.Visible = false;
Clear.Visible = false;
BackColor = Color.PowderBlue;
}
}
}
感謝您的快速回復。這將幫助很大,隨機看起來更容易。我用過的一個例子是我找到的。我其實發現了其中三個,每個都有點不同。我認爲Random()是基於時鐘的,並且可以一次又一次地產生相同的結果,這就是爲什麼我在原始代碼中嘗試了這個結果的原因。 – user1174357 2012-02-16 15:34:22