Java Program Write a java program that plays the game Nim wi
Java Program:
Write a java program that plays the game Nim with the user of the program. The program and the user alternate turns, picking up one, two, or three straws on each turn. The program goes first. The player to pick up the last straw loses. Create four \"cups\" numbered 0, 1, 2, 3, each containing the moves 1, 2 and 3. When it is the program\'s turn, it should select its next move randomly from the cup whose number is given by (number of straws left) % 4. If the selected cup is empty, your program should pick up one straw. When a move in a cup is selected, it should not be removed from the cup except in the following two situations:
a) if the move results in an immediate loss (i.e., if it is greater than or equal to the number of straws).
b) If the selected cup is cup number 1, and in the previous move made by the program, the selected cup was not empty. In this case, the previous move should be removed from the cup from which it was selected
Solution
import java.util.Scanner;
public class NimGame
{
public static int player = 1;//THIS IS A FIX
public static boolean flag = true;
public static void main(String[] args)
{
//Declare variables
//TOOK player AWAY HERE AND MADE IT GLOBAL STATIC
int pile = 0;//which pile to pick from
int stones = 0;//how many stones to pick
int counter = 0;//if the game is over or not -> 0 not over
int move;
//Scanner
Scanner input = new Scanner(System.in);
NimClass myAssistant = new NimClass();
myAssistant.displayBoard();//board gets set up
//Begin loop
while(counter == 0)
{
//Choose pile you want to remove stones from.
System.out.print(\"Player \" + player + \" Please enter the pile you wish\" +
\" to remove from. (1, 2, 3 or 4)\ \");
pile = input.nextInt();//get a pile number
//Enter # of stones you want to remove.
System.out.print(\"Player \" + player + \" Please enter the amount of\" +
\" stones you wish to remove\ \");
stones = input.nextInt();
myAssistant.playerMove(pile, stones);
//Determine what player is entering the values.
if (player == 1 && flag == true)
{
player = 2;
}
else if(player == 1 && flag == false)
{
player = 1;
flag = true;//set the flag back to true
}
else if(player == 2 && flag == true)
{
player = 1;
}
else
{
player = 2;
flag = true;
}
//Display board / determine the winner of the game.
myAssistant.displayBoard();
myAssistant.determineWinner();
if (myAssistant.determineWinner() != -1)
counter = 1;
}
}
}


