I am trying to create a Nim game in Java following tutorials from ProgrammingByDoing (https://programmingbydoing.com/a/baby-nim.html). In this first attempt, I'm not so worried about error checking or going past zero, but it seems that as long as two of the three groups/piles reach zero then the game ends. However, I want all three piles to reach or exceed zero before the game ends.
My code is:
import java.util.Scanner;
public class BabyNim
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int pile1 = 10;
int pile2 = 10;
int pile3 = 10;
String pileChoice = "";
int amount;
System.out.print("A: " + pile1 + "\t" + "B: " + pile2 + "\t" + "C: " + pile3 + "\n" );
System.out.print("Choose a pile: ");
pileChoice = keyboard.next();
System.out.print("How many to remove from pile " + pileChoice + ": ");
amount = keyboard.nextInt();
System.out.println("");
while ( pile1 > 0 && pile2 > 0 && pile3 > 0 )
{
if ( pileChoice.equals("A") ) {
pile1 -= amount;
} else if ( pileChoice.equals("B") ) {
pile2 -= amount;
} else {
pile3 -= amount;
}
System.out.print("A: " + pile1 + "\t" + "B: " + pile2 + "\t" + "C: " + pile3 + "\n" );
System.out.print("Choose a pile: ");
pileChoice = keyboard.next();
System.out.print("How many to remove from pile " + pileChoice + ": ");
amount = keyboard.nextInt();
System.out.println("");
}
System.out.println("");
System.out.println("All piles are empty. Good job!");
}
}
My problem is that I get results such as:
A: 10 B: 10 C: 10 Choose a pile: B How many to remove from pile B: 8 A: 10 B: 2 C: 10 Choose a pile: C How many to remove from pile C: 9 A: 10 B: 2 C: 1 Choose a pile: A How many to remove from pile A: 8 A: 2 B: 2 C: 1 Choose a pile: C How many to remove from pile C: 1 A: 2 B: 2 C: 0 Choose a pile: A How many to remove from pile A: 1 All piles are empty. Good job!
do {} while();loop in this case.