In: Computer Science
Write an app that works in both vertical and horizontal orientations. The app is a variety of the game of nim. Two players take turns removing identical objects from a set of objects. A player can remove one, two, or three objects at a time. The player who takes the last object loses. You can store the current number of objects in a TextView and get user input via an EditText. Include a Model. Generate randomly the starting number of objects, an integer between 10 and 20. The GUI should look nice in both orientations.
import java.util.Scanner; /**Implements a game of nim, person vs. computer. * The game starts with a number of elements chosen * by the person. The computer takes 1 or 2 elements. * Then the person takes 1 or 2 elements. The game * continues until there are no elements left. The * play who takes the last turn wins. */ public class Nim { /**gets the computer's move, 1 or 2. Currently * this method gets a random number. Your job * is to make the computer choose such that it * wins every time it is possible. First, solve * with recursion. After successfully completing * this, run the program a few times to see if you * can recognize the pattern the computer is taking. * Then see if you can get the computer to choose * its move without looping or recursion. * @param left * @return */ public int getComputerMove(int left) { return (int)(Math.random()*2)+1; } /** * plays the game of nim, computer versus person */ public void play() { Scanner sc = new Scanner(System.in); System.out.println("Enter number of elements to start."); int left = sc.nextInt(); while(left>0) { int computer=getComputerMove(left); System.out.println("Computer takes "+computer); left-=computer; System.out.println("Now there are "+left+" left."); if(left<=0) { System.out.println("Computer wins!"); return; } System.out.println("What's your move? (1 or 2)"); int person=sc.nextInt(); while(person!=1 && person!=2) { System.out.println(person+" not allowed, choose 1 or 2."); person=sc.nextInt(); } left-=person; System.out.println("Now there are "+left+" left."); if(left<=0) { System.out.println("You win!"); return; } } } public static void main(String[] args) { Nim nim=new Nim(); nim.play(); } }