Assignment # P2 and Nim
Code
/// Name: Tommy Oyuntseren
/// Period: 7
/// Program Name: Niim
/// File Name: Nim.java
/// Date: 3/3/2016
import java.util.Scanner;
public class Nim
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String p1, p2, player, pile;
int remove, turn, first, gameover, choice, a, b, c;
a= 3;
b= 4;
c= 5;
choice= 0;
gameover= 0;
turn= 1;
pile= "";
player= "";
System.out.print("Player 1, enter your name: ");
p1 = keyboard.next();
System.out.print("Player 2, enter your name: ");
p2 = keyboard.next();
while (gameover == 0)
{
if (turn%2 != 0)
player= p1;
else
player= p2;
System.out.println("\nA: " + a + "\tB: " + b + "\tC: " + c + "\n");
System.out.print(player + ", choose a pile: ");
pile= keyboard.next();
if (pile.equals("A"))
choice= a;
else if (pile.equals("B"))
choice= b;
else if (pile.equals("C"))
choice= c;
if (choice == 0)
{
System.out.print("\nNice try, " + player + ". That pile doesn't have any. Choose again: ");
pile= keyboard.next();
}
else
{
System.out.print("How many to remove from pile " + pile + ": ");
remove= keyboard.nextInt();
while (remove <= 0)
{
System.out.print("\nYou must choose at least 1. How many? ");
remove= keyboard.nextInt();
}
while ( remove > choice )
{
System.out.print("\nPile " + pile + " doesn't have that many. Try again: ");
remove= keyboard.nextInt();
}
choice= choice - remove;
if (pile.equals("A"))
a= choice;
else if (pile.equals("B"))
b= choice;
else if (pile.equals("C"))
c= choice;
if ((a == 0) && (b == 0) && (c == 0 ))
{
turn ++;
gameover = 1;
first = 1;
}
else
{
turn ++;
first = 1;
}
}
}
if (turn % 2 != 0)
System.out.println("\n" + p1 + ", there are no counters left, so you WIN!");
else
System.out.println("\n" + p2 + ", there are no counters left, so you WIN!");
}
}
Picture of the output