Project #2: Nim
Code
/// Name: Cassie
/// Period: 6
/// Program Name: Nim
/// File Name: nim.java
/// Date Finished: 1/29/2016
import java.util.Scanner;
import java.util.Random;
class nim {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
String choice;
int many, times = 2;
System.out.println();
System.out.print( "Player 1, enter your name: " );
String player1 = keyboard.next();
System.out.print( "Player 2, enter your name: " );
String player2 = keyboard.next();
System.out.println();
int a = 1 + r.nextInt(5);
int b = 1 + r.nextInt(5);
int c = 1 + r.nextInt(5);
String name = player1;
while ( a != 0 || b != 0 || c != 0 ) {
System.out.println( "A: " + a + "\tB: " + b + "\tC: " + c );
System.out.println();
if ( times % 2 == 0 ) {
name = player1;
} else {
name = player2;
}
System.out.print( name + ", choose a pile: " );
choice = keyboard.next();
System.out.print( "How many to remove from from pile " + choice + ": " );
many = keyboard.nextInt();
System.out.println();
if ( choice.equals("a") || choice.equals("A") ) {
while ( many > a || many < 1 ) {
System.out.print( "Nice try, " + name + ". That's a no-go. Choose again: " );
many = keyboard.nextInt();
System.out.println();
}
a -= many;
} else if ( choice.equals("b") || choice.equals("B") ) {
while ( many > b || many < 1 ) {
System.out.print( "Nice try, " + name + ". That's a no-go. Choose again: " );
many = keyboard.nextInt();
System.out.println();
}
b -= many;
} else if ( choice.equals("c") || choice.equals("C") ) {
while ( many > c || many < 1 ) {
System.out.print( "Nice try, " + name + ". That's a no-go. Choose again: " );
many = keyboard.nextInt();
System.out.println();
}
c -= many;
} else {
System.out.println( "You did it wrong, so you forfeit your turn." );
}
times += 1;
}
if ( name == player1 ) {
name = player2;
} else {
name = player1;
}
System.out.println();
System.out.println( "A: " + a + "\tB: " + b + "\tC: " + c );
System.out.println();
System.out.println( name + ", there are no counters left, so you WIN!" );
System.out.println();
}
}
Picture of the output