Read Also: Rock Paper Scissors Source Code in Java
Nim Game Program Pseudo Code
1. Person chooses the number of elements at the start of the game.2. We use the Math.random() method to generate a random number for Computer. It can either be 1(one) or 2(two).
3. Person can choose either 1 or 2 elements.
4. The player with the last turn in the game when there are no elements left in it wins.
Java Program Source Code
import java.util.Scanner;
public class NimGame {
public int fetchComputerMove(int left)
{
int computerTurn = (int) (Math.random()*2)+1;
return computerTurn;
}
public static void main(String args[]) {
NimGame ng = new NimGame();
ng.play();
}
public void play() {
Scanner scan = new Scanner(System.in);
System.out.println("You are playing Nim Game");
System.out.println("Enter the number of elements to start the game");
int elementsLeft = scan.nextInt();
while (elementsLeft > 0) {
int computerMove = fetchComputerMove(elementsLeft);
System.out.println("Computer moves " + computerMove);
elementsLeft = elementsLeft - computerMove;
System.out.println("Now only " + elementsLeft + " elementsLeft");
System.out.println("");
if (elementsLeft <= 0) {
System.out.println("***********************");
System.out.println("Computer wins the game!");
System.out.println("***********************");
return ;
}
System.out.println("It's your turn now: Enter (1 or 2) ");
int personMove = scan.nextInt();
while (personMove != 1 && personMove != 2) {
System.out.println("Please choose 1 or 2 only");
personMove = scan.nextInt();
}
elementsLeft = elementsLeft - personMove;
System.out.println("After your move!! the number of elements left: "+elementsLeft);
System.out.println("");
if (elementsLeft <= 0) {
System.out.println("*****************");
System.out.println("You win the game!");
System.out.println("*****************");
return ;
}
}
}
}
Output:You are playing Nim Game
Enter the number of elements to start the game
10
Computer moves 1
Now only 9 elementsLeft
It's your turn now: Enter (1 or 2)
2
After your move!! the number of elements left: 7
Computer moves 2
Now only 5 elementsLeft
It's your turn now: Enter (1 or 2)
3
Please choose 1 or 2 only
1
After your move!! the number of elements left: 4
Computer moves 2
Now only 2 elementsLeft
It's your turn now: Enter (1 or 2)
2
After your move!! the number of elements left: 0
*****************
You win the game!
*****************
That's all for today. Please mention in the comments in case you have any questions related to the nim game in java.
Reference: Duke