Skip to content

Instantly share code, notes, and snippets.

@CAD97
Created May 13, 2015 16:55
Show Gist options
  • Save CAD97/17ef91be6b17d7f1834d to your computer and use it in GitHub Desktop.
Save CAD97/17ef91be6b17d7f1834d to your computer and use it in GitHub Desktop.
My implementation of the NumberWizard game from the Udemy Unitycourse
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
int max;
int min;
int guess;
void Start () {
StartGame();
}
void StartGame() {
max = 1000;
min = 1;
print ("Welcome to NumberWizard!");
print (string.Format("Pick a number between {0} and {1}, but don't tell me.", min, max));
max += 1;
/* for the binsearch: min <= guess < max, and here we want
to include max, so add one so that 1000 can be guessed. */
print ("Press ↑ if your number is higher, ↓ if your number is lower, or ⏎ if I am correct.");
NaturalBinSearch(min, max);
}
void Update () {
if (Input.GetKeyDown(KeyCode.Return)) {
print ("I was right!");
print ("=========================");
Start();
} else {
if (Input.GetKeyDown(KeyCode.UpArrow)) {
min = guess + 1; // target >= min
NaturalBinSearch(min, max);
}
if (Input.GetKeyDown(KeyCode.DownArrow)) {
max = guess; // target < max
NaturalBinSearch(min, max);
}
}
}
/**
* Takes a min and a max. Guesses close to halfway to disguise the binsearch
* min <= guess < max
**/
void NaturalBinSearch(int min, int max) {
guess = (min + max) / 2;
guess += (int) Mathf.Floor((Random.value-0.5f) * ((max-min) / 4f));
if (guess < min) {
guess = min; // in small ranges the fudge can go below min because of flooring
}
print(string.Format("Is your number {0}?", guess));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment