/ Published in: Java
The player selects a range from 0 to n, remembers a number in this range and then the script asks the player a question trying to guess the number. The PC will always guess the correct number.\r\n\r\nI could have added more varied questions, but the task did not state it had to be interesting, and being a lazy creature I took the path of least résistance.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import java.util.ArrayList; import java.util.Scanner; public class GuessNumber { public static short range; public static ArrayList<Integer> collection = new ArrayList<Integer>(); { // We need a range // Get and populate the range range = input.nextShort(); range = (range == 0) ? 1 : range; for (int i=0; i<=range; i++) collection.add(i); // A few ground rules // Keep asking as long as found is false boolean found = false; while ( ! found) { // Get the size of the collection int size = collection.size(); // As long as there are two or more numbers left if (size > 2) { // The centre index int centre = size / 2; int theNumber = collection.get(centre); // Default question // Evaluate input if (answer.equals("yes") || answer.equals("1")) delete(theNumber, true); else if (answer.equals("no") || answer.equals("0")) delete(theNumber, false); else { error(answer); found = true; } // If only one number is left then we are done. if (collection.size() == 1) { int num = collection.get(0); answer(num); found = true; } } // Otherwise there are now 2 values in the array. else { // Get the two values int num1 = collection.get(0); int num2 = collection.get(1); // Ask question and get answer // Resolve answer if (answer.equals("yes") || answer.equals("1")) { answer(num2); found = true; } else if (answer.equals("no") || answer.equals("0")) { answer(num1); found = true; } else { error(answer); found = true; } } } } // Deletes numbers less or greater than n public static void delete(int n, boolean lt) { // Create a temporary collection ArrayList<Integer> newCollection = new ArrayList<Integer>(); // Add numbers lesser than n if (lt) { for (int i:collection) if(i<n) newCollection.add(i); } // Add numbers greater than n else { n=n-1; for (int i:collection) if(i>n) newCollection.add(i); } // Replace the collection with the new one collection = newCollection; } // The answer public static void answer(int num) { } // An error { } }