Right now I'm trying to build a Number Wizard game in Unity 4.6.9. So far, everything works except for the first guess.
When the game guesses the number to be 500, you have to tell it whether your number is higher, lower, or equal to 500. Ideally, if you tell it that your number is higher or lower it should immediately guess a new number (either 750 for higher, or 250 for lower).
The problem is that it doesn't change the guess immediately.
When I tell the game that number is greater than the original guess, the console in Unity says this:
The problem is line 3. It should ask "Is it higher or lower than 750?", and then line 4 should ask "Is it higher or lower than 875?", and so on.
I'm really not sure what it is that I've done wrong in the code. If anyone would be willing to look through it and point out my mistake I'd be very grateful.
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
int max = 1000;
int min = 1;
int guess = 500;
// Use this for initialization
void Start () {
max += 1;
print ("Welcome to Number Wizard.");
print ("To begin, pick a number in your head, but don't tell me what it is.");
print ("The highest number you can pick is " +max +", and the lowest number you can pick is " +min +".");
print ("Is your number greater than " +guess +"?");
print ("Press Y if it is greater, N if it is lesser, or E if it is " +guess +".");
}
// Update is called once per frame
void Update () {
string NewGuess = "Is it higher or lower than " +guess +"?";
if (Input.GetKeyDown(KeyCode.Y)) {
min = guess;
guess = (max + min) / 2;
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.N)) {
max = guess;
guess = (max + min) / 2;
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.E)) {
print ("I won!");
}
}
}
Again, any help would be greatly appreciated.
The problem is you never update your NewGuess string that you are printing to actually include the newly calculated guess. Try this:
void Update () {
string NewGuess = "Is it higher or lower than " +guess +"?";
if (Input.GetKeyDown(KeyCode.Y)) {
min = guess;
guess = (max + min) / 2;
NewGuess = "Is it higher or lower than " +guess +"?";
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.N)) {
max = guess;
guess = (max + min) / 2;
NewGuess = "Is it higher or lower than " +guess +"?";
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.E)) {
print ("I won!");
}
}
Or, a cleaner solution would be to create a new method for printing to call from your Update method with the new guess passed as a parameter.
Example:
void PrintNewGuess(int newGuess)
{
String newGuessString = "Is it higher or lower than " +newGuess +"?";
print(newGuessString);
}