How to Correctly Implement Winning Logic in a Simple Nim Game?

  • Thread starter iamjon.smith
  • Start date
  • Tags
    Game
In summary: I am not sure how to fix this issue. In summary, Design and implement a Nim class and a NimGame application to allow two human players to play the game of Nim. The game starts with four piles of stones, with varying numbers of stones in each pile. Players take turns removing stones from a single pile, but can only take up to half of the remaining stones in that pile. The player who takes the last stone loses. A Nim class has been created with methods for making moves, formatting the board, changing players, and determining the winner. A NimTest class has also been created to test the game and allow for user input. The current issues with the program include incorrect validation for number of rocks and piles, and displaying the
  • #1
iamjon.smith
117
3
Simple Nim Game Due Tonight. Please Help!

Design and implement a Nim class and a NimGame application to allow two human players to play the game of Nim. The game starts with four piles of stones. The first pile has 3 stones, the second pile has 5 stones, the third pile has 7 stones, and the last pile has 9 stones. The players take turns removing stones. On a single turn a player may only take stones from a single pile. A player may not take more than half the pile, except when it’s the last stone in the pile. The loser of the game is the player to take the very last stone.

OK, So I have created a Nim class, and a NimTest to work on the game. The class is as follows:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nimtest;

/**
 *
 * @author Jon and Jessica
 */
public class Nim {

    private int[] gameBoard = new int[4];
    private int player;

    public Nim(int... gameBoard){

        setGameBoard(gameBoard);
        changePlayer();
       
    }
    public Nim(){
        this (3, 5, 7, 9);
    }
    // player move method to check for valid move and execute move
    public boolean move (int pile, int rocks){
        boolean result = false;

        pile -= 1;
        double halfPile = (double)gameBoard[pile] / 2;  // determine what half of pile is equal to

        if( rocks <= halfPile || rocks == 1 && gameBoard[pile] != 0){  // if player move is less than half of pile...
            gameBoard[pile] -= rocks; // make move
        result = true;
        }

        if(result){
            changePlayer(); // if move is valid, change player
            
        }
        return result;
    }
    // method to format board output
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("%10s%10s%10s%10s", "Pile 1", "Pile 2", "Pile 3", "Pile 4"));
        sb.append("\n");
        sb.append(String.format("%40s", "-----------------------------------------"));
        sb.append("\n");
        for (int rocks : getGameBoard()){
            sb.append(String.format("%10s", rocks));
                       
        }
        sb.append("\n");
        sb.append(String.format("%40s", "-----------------------------------------"));
        sb.append("\n");
        sb.append(String.format("It is player %s's turn.\n",getPlayer()));
        return sb.toString();
    }
    // method to change between players
    private void changePlayer(){
        if (getPlayer() == 1){
            setPlayer(2);
        }
        else {
            setPlayer(1);
        }
    }

    /**
     * @return the gameBoard
     */
    public int[] getGameBoard() {
        return gameBoard;
    }

    /**
     * @param gameBoard the gameBoard to set
     */
    public void setGameBoard(int[] gameBoard) {
        this.gameBoard = gameBoard;
    }

    /**
     * @return the player
     */
    public int getPlayer() {
        return player;
    }

    /**
     * @param player the player to set
     */
    private void setPlayer(int player) {
        this.player = player;
    }
   // method to determine game winner
    public int gameWinner(){

        boolean isComplete = true;
        int winner = -1;

        if (gameBoard[0] == 0 && gameBoard[1] == 0 && gameBoard[2] == 0 && gameBoard[3]== 0)

                winner = player;
                isComplete = true;

        if(isComplete == true && winner == 1){

            System.out.print("Winner is Player 1");
            winner = 0;
        }

        if(isComplete == true && winner == 2){

            System.out.print("Winner is Player 2");
            winner = 0;
        }

                return winner;
    }

    public boolean gameOver(){

        boolean gameOver = true;

        if( gameBoard[0] != 0 && gameBoard[1] != 0 && gameBoard[2] != 0 && gameBoard[3] != 0){
         gameOver = false;
        }
        else {
            gameOver = true;
        }

        return gameOver;
    }
  }

my test class is as follows:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nimtest;
import java.util.Scanner;
/**
 *
 * @author Jon and Jessica
 */
public class NimTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

       int pile = 0;
       int rocks = 0;
       
       Nim n = new Nim();

       n = new Nim(n.getGameBoard()); // Overloaded constructor to call game board
       Scanner input = new Scanner(System.in); // Scanner to accept user input

       do {
           
           System.out.print(n); // Start new game and print starting board
           System.out.println("Please choose a pile (1-4)"); // Ask user to pick a pile
           pile = input.nextInt(); // Assign user input to variable pile

           while (pile < 1 || pile > 4){        // check for valid pile
               System.out.println("Invalid Pile, Please Re-Enter Pile\n"); // user friendly error message
               pile = input.nextInt();      // get new value for variable pile
           }
           System.out.println("How many rocks would you like to take? You can't take more than half!"); // Ask user for number of rocks
                rocks = input.nextInt();    // assign next input to variable rocks

           
                     
            }   while (n.move(pile, rocks) || n.gameWinner() == 0);
       
            n.getGameBoard();

            while (!n.move(pile, rocks) || n.gameWinner() == 0){

                System.out.println("That is not a valid move!");
                System.out.println("Choose a pile?");
                pile = input.nextInt();

                System.out.println("How many rocks would you like?");
                rocks = input.nextInt();
                
            } 

    }

}

Problems I am having

1. if the user inputs an invalid number of rocks, such as more than half, or any number after the pile is = 0, the game prompts for entry of new pile and new number of rocks. Once the user enters the new numbers, the game exits instead of the game continuing.

2. it is not checking to see if there is a game winner. I am not sure what I am missing.

help me find the problem.
 
Physics news on Phys.org
  • #2


iamjon.smith said:
Problems I am having

1. if the user inputs an invalid number of rocks, such as more than half, or any number after the pile is = 0, the game prompts for entry of new pile and new number of rocks. Once the user enters the new numbers, the game exits instead of the game continuing.

2. it is not checking to see if there is a game winner. I am not sure what I am missing.

help me find the problem.

Ok, now it allows for correct validation, and the game runs through to the end. I am down to 2 small problems now:

1. Before the winner is declared, the winner is asked to enter a move on an empty Nims board:
Code:
    Pile 1    Pile 2    Pile 3    Pile 4
-----------------------------------------
         0         0         0         1
-----------------------------------------
It is player 1's turn.
Please choose a pile (1-4)
4
How many rocks would you like to take? You can't take more than half!
1
    Pile 1    Pile 2    Pile 3    Pile 4
-----------------------------------------
         0         0         0         0
-----------------------------------------
It is player 2's turn.
Please choose a pile (1-4)
4
How many rocks would you like to take? You can't take more than half!
1

I need it to show the winner once the final move is made.

Problem 2 is the winner statement. It displays as follows:

Output of winner is as follows:

Code:
Winner is Player 2Winner is Player 2Winner is Player 2Winner is Player 2That is not a valid move!
Choose a pile?

Since the board is empty, it always gives the invalid entry at the end and the game doesn't truly exit. It continues to run.
 
Last edited:

Related to How to Correctly Implement Winning Logic in a Simple Nim Game?

1. What is the Simple Nim Game?

The Simple Nim Game is a mathematical strategy game where two players take turns removing objects from a pile. The player who removes the last object wins the game.

2. How is the Simple Nim Game played?

The game starts with a pile of objects, such as stones or coins. Players take turns removing 1 or more objects from the pile. The player who removes the last object wins.

3. What is the objective of the Simple Nim Game?

The objective of the Simple Nim Game is to be the player who removes the last object from the pile. This can be achieved through strategic moves and anticipating your opponent's moves.

4. Is there a winning strategy for the Simple Nim Game?

Yes, there is a winning strategy for the Simple Nim Game. The strategy involves creating a "losing position" for your opponent, where they will always be forced to take the last object from the pile.

5. How does the Simple Nim Game relate to other mathematical concepts?

The Simple Nim Game can be used to teach and explore various mathematical concepts, such as game theory, combinatorics, and binary numbers. It is also commonly used as an example in computer science and programming courses.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
11
Views
9K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
2K
  • Programming and Computer Science
Replies
1
Views
1K
Back
Top