如何统一不要两次选择相同的号码?

时间:2015-06-08 11:14:17

标签: c# unity3d

该程序是一个简单的数字猜谜游戏,但是当我随机猜测统一倾向于多次选择相同的数字时,有没有办法让它知道它已经选择了什么数字?还有一种方法可以让它自动进入失败的场景,如果它不能选择另一个号码?任何帮助表示赞赏^ _ ^

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class NumberGuesser : MonoBehaviour {

int min;
int max;
int guess;
int maxGuessesAllowed = 15;
public Text text;
//guess = (max + min) / 2;

// Use this for initialization
void Start () {
    min = 1;
    max = 1000;
    NextGuess();
    max = max + 1;
}

// Update is called once per frame
public void guessHigher () {
    min = guess;
    NextGuess ();
}
public void guessLower() {
        max = guess;
        NextGuess();
    }
void NextGuess(){
    guess = (max + min) / 2;
    //guess = Random.Range (min,max);//Randomizes Guesses
    //print (guess);
    text.text = guess.ToString ();
    maxGuessesAllowed = maxGuessesAllowed - 1;
    if (maxGuessesAllowed <= 0) {
        Application.LoadLevel ("Win");
    }
}
}//main

2 个答案:

答案 0 :(得分:2)

试试这个:

List<int> alreadyGuessed = new List<int>();
...

int NextGuess()
{
    int theGuess = Random.Range(min, max);
    while(alreadyGuessed.Contains(theGuess))
        theGuess = Random.Range(min, max);

    alreadyGuessed.Add(theGuess);
    return theGuess;
}

它会记录所猜到的内容并继续猜测,直到之前没有猜到猜测为止。

答案 1 :(得分:1)

只需在代码顶部添加

即可
List<int> used = new List<int>();  

您可能也想使用

添加此内容
using System.Collections.Generic;  

然后将NextGuess功能更改为此

void NextGuess()
{
    guess = Random.Range (min,max);
    while(used.Contains(guess))
        guess = Random.Range (min,max);
    used.Add (guess);
    text.text = guess.ToString ();
    maxGuessesAllowed = maxGuessesAllowed - 1;
    if (maxGuessesAllowed <= 0) {
        Application.LoadLevel ("Win");
    }
}