如何使统一不选择相同的数字两次

本文关键字:数字 两次 何使统 选择 | 更新日期: 2023-09-27 17:54:23

该程序是一个简单的数字猜游戏然而,当我随机猜测统一倾向于选择相同的数字多次有没有办法让它知道它已经选择了什么数字?还有,如果它不能选择另一个数字,是否有办法让它自动进入失去的场景?任何帮助都很感激^_^

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

如何使统一不选择相同的数字两次

试试这个:

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;
}

它记录已经猜到的内容,并继续猜测,直到之前没有猜到。

把它添加到你的代码中

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

你可能想用too

添加这个
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");
    }
}