Question

In: Computer Science

Nim Game Java, PegClass One variation of the game of Nim, described in Chapter 5 Exercise...

Nim Game Java, PegClass

One variation of the game of Nim, described in Chapter 5 Exercise 12, is played with four
piles of stones. Initially, the piles contain 1, 2, 3, and 4 stones. On each turn, a player may
take 1, 2, or 3 stones from a single pile. The player who takes the last stone loses.
a) Write a program that allows two players to play Nim. Be sure to allow only legal
moves. The program should be written so that it can easily be modified for more
or less than four piles. The program output should look similar to:

Name for player #1: Petra
Name for player #2: Elaine
Board: 1 2 3 4
Petra
Which pile? 3
How many? 2
Board: 1 2 1 4
Elaine
Which pile? 4
How many? 3
Board: 1 2 1 1

You do not need to write the full program but figure out how to display the board as:

XXX|XXX

XXX|XXX XXX|XXX

XXX|XXX XXX|XXX XXX|XXX

XXX|XXX XXX|XXX XXX|XXX XXX|XXX

and as the numbers change

XXX|XXX - represents one stone

changes.

Solutions

Expert Solution

Code for your game program is provided below. Code is explained in code comments from top to to bottom. I have provided the output screenshot as welll.

As For the second Part, Why just figure out !!! Lets Make it happen!!! I have made the code for representing bricks too. and i have explained it in code comments. A brief explanation for that is, i have changed the code of printBoard() method, and used two loops for displaying bricks in each pile. You can view to code and understand it.

Enjoy the game!!!!! If you need any further clarification please ask in comments.

############################################################################

CODE WHERE BOARD IS REPRESENTED BY NUMBERS

import java.util.Scanner;   //to take input

public class PegClass {

        //function to return sum of the stones. we use it to find if there is only one stone left
        public static int boardSum(int[] arr)
        {
                int sum=0;
                for(int i=0;i<arr.length;i++)
                        sum+=arr[i];
                return sum;   //return sum
        }
        
        //method to print the board
        public static void printBoard(int[] board)
        {
                for(int i=0;i<board.length;i++)
                {
                        System.out.print(board[i]+" ");  //printing no of stones in each pile
                }

        }
        
        //sets all piles to zero stones
        public static void setBoardZero(int[]board)
        {
                for(int i=0;i<board.length;i++)
                        board[i]=0;
        }
        
        //main method
        public static void main(String[] args) 
        {
                int board[]=new int[4];  //board fo size 4
                String player1="",player2="";  //player names
                int pick=-1;   //no of stones to be picked
                int pile=-1;   //to choose pile
                Scanner scan=new Scanner(System.in);
                int turn=1;  //to be used to determine the turn, 1 for player 1 , 2 for player 2
                boolean valid=true;  //flag to be used to check if input is valid 
                
                for(int i=0;i<board.length;i++)
                {
                        board[i]=i+1;   //set the stones in piles
                }
                
                System.out.print("Name of player #1: ");
                player1=scan.nextLine();    //first player name
                System.out.print("Name of player #2: ");
                player2=scan.nextLine();        //second player name
                 
                while(boardSum(board)>1)   //loop until there is only one stone left in the board
                {
                        if(turn==1)    //player1 turn
                        {
                                do  //loop to take valid input
                                {
                                        valid=true;   //set flag true
                                        System.out.print("Board: ");
                                        printBoard(board);    //print board 
                                        System.out.println("\n"+player1);  //player1 name
                                        System.out.print("Which Pile? ");
                                        pile=scan.nextInt();    //select pile
                                        if(pile<1 || pile>board.length)    //if the pile no is invalid
                                        {
                                                System.out.println("INVALID PILE. CHOOSE AGAIN");
                                                valid=false;  //set flag false
                                                continue;  //continue to take input again
                                        }
                                        
                                        System.out.print("How Many? ");
                                        pick=scan.nextInt();     //select how many stones to pick
                                        if(pick<1 || pick>(board.length-1))    //if stones entered are invalid 
                                        {
                                                System.out.println("INVALID INPUT. YOU HAVE TO PICK ATLEAST 1 AND ATMOST "+(board.length-1)+" STONE. CHOOSE AGAIN");
                                                valid=false;
                                                continue;  //continue again
                                        }
                                        if(pick>board[pile-1])    //if there are less stones in the pile but user wants to pick more
                                        {
                                                System.out.println("THERE ARE NOT ENOUGH STONES IN THIS PIlE, PLEASE PICK VALID NO OF PILES");
                                                valid=false;
                                                continue;   //loop again take input again
                                        }
                                        
                                        board[pile-1]=board[pile-1]-pick;   //if input is valid then decrease the stones in pile as player has nimmed the stone
                                        turn=2;  //set turn for second player
                                        
                                }while(!valid);   //loop until there is invalid input
                        }
                        
                        else if(turn==2)    //turn for palyer2
                        {
                                do
                                {
                                        valid=true;
                                        System.out.print("Board: ");
                                        printBoard(board);   //print board
                                        System.out.println("\n"+player2);
                                        System.out.print("Which Pile? ");
                                        pile=scan.nextInt();   //scan pile number
                                        if(pile<1 || pile>board.length)   //invalid pile
                                        {
                                                System.out.println("INVALID PILE. CHOOSE AGAIN");
                                                valid=false;
                                                continue;   //continue again
                                        }
                                        System.out.print("How Many? ");
                                        pick=scan.nextInt();   // enter no of stones
                                        if(pick<1 || pick>(board.length-1))   //if invalid stones
                                        {
                                                System.out.println("INVALID INPUT. YOU HAVE TO PICK ATLEAST 1 AND ATMOST "+(board.length-1)+" STONE. CHOOSE AGAIN");
                                                valid=false; 
                                                continue;
                                        }
                                        if(pick>board[pile-1])   //if invalid stones 
                                        {
                                                System.out.println("THERE ARE NOT ENOUGH STONES IN THIS PIlE, PLEASE PICK VALID NO OF PILES");
                                                valid=false;
                                                continue;   //continue again
                                        }
                                        
                                        board[pile-1]=board[pile-1]-pick; //if input is valid then decrease the stones in pile as player has nimmed the stone
                                        turn=1;   //set turn for second player
                                        
                                }while(!valid);
                        
                        }  //else if closed
                }  //outer while loop closed
                
                System.out.print("Board: ");
                printBoard(board);     //print the board with only one stone left
                
                if(turn==1)  //if last turn is for player1
                {
                        System.out.println(player1+" picks the last stone.");
                        setBoardZero(board);   //set board with zero stones after player1 has picked it
                        System.out.print("Board: ");
                        printBoard(board);   //print board with zero stones
                        System.out.println("\nCongratulations!!! "+player2+", You Win.");   //player2 wins
                        
                }
                else    //if turn is for player2
                {
                        System.out.println(player2+" picks the last stone.");
                        setBoardZero(board);   //set board with zero stones after player2 has picked last stone
                        System.out.print("Board: ");
                        printBoard(board);    //print board with zero stones
                        System.out.println("\nCongratulations!!! "+player1+", You Win.");   //player1 wins
                }
                
                scan.close();   //close scanner
        }
}

OUTPUT

############################################################################

CODE WHERE BOARD IS REPRESENTED BY BRICKS

import java.util.Scanner;   //to take input

public class PegClass {

        //function to return sum of the stones. we use it to find if there is only one stone left
        public static int boardSum(int[] arr)
        {
                int sum=0;
                for(int i=0;i<arr.length;i++)
                        sum+=arr[i];
                return sum;   //return sum
        }
        
        //method to print the board
        public static void printBoard(int[] board)
        {
                for(int i=0;i<board.length;i++)  //loop for pile
                {
                        for(int j=1;j<=board[i];j++)   //loop for each stone
                        System.out.print("XXX|XXX  ");  //printing stone
                        
                        System.out.print("\n");  //new line for next pile
                }

        }
        
        //sets all piles to zero stones
        public static void setBoardZero(int[]board)
        {
                for(int i=0;i<board.length;i++)
                        board[i]=0;
        }
        
        //main method
        public static void main(String[] args) 
        {
                int board[]=new int[4];  //board fo size 4
                String player1="",player2="";  //player names
                int pick=-1;   //no of stones to be picked
                int pile=-1;   //to choose pile
                Scanner scan=new Scanner(System.in);
                int turn=1;  //to be used to determine the turn, 1 for player 1 , 2 for player 2
                boolean valid=true;  //flag to be used to check if input is valid 
                
                for(int i=0;i<board.length;i++)
                {
                        board[i]=i+1;   //set the stones in piles
                }
                
                System.out.print("Name of player #1: ");
                player1=scan.nextLine();    //first player name
                System.out.print("Name of player #2: ");
                player2=scan.nextLine();        //second player name
                 
                while(boardSum(board)>1)   //loop until there is only one stone left in the board
                {
                        if(turn==1)    //player1 turn
                        {
                                do  //loop to take valid input
                                {
                                        valid=true;   //set flag true
                                        System.out.print("Board: \n");
                                        printBoard(board);    //print board 
                                        System.out.println("\n"+player1);  //player1 name
                                        System.out.print("Which Pile? ");
                                        pile=scan.nextInt();    //select pile
                                        if(pile<1 || pile>board.length)    //if the pile no is invalid
                                        {
                                                System.out.println("INVALID PILE. CHOOSE AGAIN");
                                                valid=false;  //set flag false
                                                continue;  //continue to take input again
                                        }
                                        
                                        System.out.print("How Many? ");
                                        pick=scan.nextInt();     //select how many stones to pick
                                        if(pick<1 || pick>(board.length-1))    //if stones entered are invalid 
                                        {
                                                System.out.println("INVALID INPUT. YOU HAVE TO PICK ATLEAST 1 AND ATMOST "+(board.length-1)+" STONE. CHOOSE AGAIN");
                                                valid=false;
                                                continue;  //continue again
                                        }
                                        if(pick>board[pile-1])    //if there are less stones in the pile but user wants to pick more
                                        {
                                                System.out.println("THERE ARE NOT ENOUGH STONES IN THIS PIlE, PLEASE PICK VALID NO OF PILES");
                                                valid=false;
                                                continue;   //loop again take input again
                                        }
                                        
                                        board[pile-1]=board[pile-1]-pick;   //if input is valid then decrease the stones in pile as player has nimmed the stone
                                        turn=2;  //set turn for second player
                                        
                                }while(!valid);   //loop until there is invalid input
                        }
                        
                        else if(turn==2)    //turn for palyer2
                        {
                                do
                                {
                                        valid=true;
                                        System.out.print("Board: \n");
                                        printBoard(board);   //print board
                                        System.out.println("\n"+player2);
                                        System.out.print("Which Pile? ");
                                        pile=scan.nextInt();   //scan pile number
                                        if(pile<1 || pile>board.length)   //invalid pile
                                        {
                                                System.out.println("INVALID PILE. CHOOSE AGAIN");
                                                valid=false;
                                                continue;   //continue again
                                        }
                                        System.out.print("How Many? ");
                                        pick=scan.nextInt();   // enter no of stones
                                        if(pick<1 || pick>(board.length-1))   //if invalid stones
                                        {
                                                System.out.println("INVALID INPUT. YOU HAVE TO PICK ATLEAST 1 AND ATMOST "+(board.length-1)+" STONE. CHOOSE AGAIN");
                                                valid=false; 
                                                continue;
                                        }
                                        if(pick>board[pile-1])   //if invalid stones 
                                        {
                                                System.out.println("THERE ARE NOT ENOUGH STONES IN THIS PIlE, PLEASE PICK VALID NO OF PILES");
                                                valid=false;
                                                continue;   //continue again
                                        }
                                        
                                        board[pile-1]=board[pile-1]-pick; //if input is valid then decrease the stones in pile as player has nimmed the stone
                                        turn=1;   //set turn for second player
                                        
                                }while(!valid);
                        
                        }  //else if closed
                }  //outer while loop closed
                
                System.out.print("Board: \n");
                printBoard(board);     //print the board with only one stone left
                
                if(turn==1)  //if last turn is for player1
                {
                        System.out.println(player1+" picks the last stone.");
                        setBoardZero(board);   //set board with zero stones after player1 has picked it
                        System.out.print("Board: ");
                        printBoard(board);   //print board with zero stones
                        System.out.println("\nCongratulations!!! "+player2+", You Win.");   //player2 wins
                        
                }
                else    //if turn is for player2
                {
                        System.out.println(player2+" picks the last stone.");
                        setBoardZero(board);   //set board with zero stones after player2 has picked last stone
                        System.out.print("Board: ");
                        printBoard(board);    //print board with zero stones
                        System.out.println("\nCongratulations!!! "+player1+", You Win.");   //player1 wins
                }
                
                scan.close();   //close scanner
        }
}

OUTPUT


Related Solutions

The game of Nim. This is a well-known game with a number of variants. The following...
The game of Nim. This is a well-known game with a number of variants. The following variant has an interesting winning strategy. Two players alternately take marbles from a pile. In each move, a player chooses how many marbles to take. The player must take at least one but at most half of the marbles. Then the other player takes a turn. The player who takes the last marble loses. Write a program in which the computer plays against a...
Write a program in Basic to play the game of Nim with acom­puter.
Write a program in Basic to play the game of Nim with acom­puter.
Develop a Java application that plays a "guess the number" game as described below. a) The...
Develop a Java application that plays a "guess the number" game as described below. a) The user interface is displayed and the user clicks the “Start Game” button to begin the game. b) Your application then gets a random number in the range 1-1000 inclusive (you might want to use Math.random or the Random class). c) The application then displays the following prompt (probably via a JLabel): I have a number between 1 and 1000 can you guess my number?...
JAVA - Programming Exercise 10-5. The developers of a free online game named Sugar Smash have...
JAVA - Programming Exercise 10-5. The developers of a free online game named Sugar Smash have asked you to develop a class named SugarSmashPlayer that holds data about a single player. The class contains the following fields: idNumber - the player’s ID number (of type int) name - the player's screen name (of type String) scores - an array of integers that stores the highest score achieved in each of 10 game levels Include get and set methods for each...
One file java program that will simulate a game of Rock, Paper, Scissors. One of the...
One file java program that will simulate a game of Rock, Paper, Scissors. One of the two players will be the computer. The program will start by asking how many winning rounds are needed to win the game. Each round will consist of you asking the user to pick between rock, paper, and scissors. Internally you will get the computers choice by using a random number generator. Rock beats Scissors, Paper beats Rock, and Scissors beats Paper. You will report...
How to prove that player I can always win a Nim game in which hte number...
How to prove that player I can always win a Nim game in which hte number of heaps with an odd number of coins is odd. I understand the objective, having trouble formuating a more formula argument for the problem.
Using induction: Show that player 1 can always win a Nim game in which the number...
Using induction: Show that player 1 can always win a Nim game in which the number of heaps with an odd number of coins is odd.
Using one quantitative and one qualitative health policy research method described in this chapter, design a...
Using one quantitative and one qualitative health policy research method described in this chapter, design a study to examine health centers are able to reduce or eliminate health disparities (i.e., differences in access, quality, and health outcomes) across racial or ethnic and socioeconomic sub-populations.
Modified from Chapter 07 Programming Exercise 5 Original Exercise: Rock, Paper, Scissors Modification Programming Exercise 11...
Modified from Chapter 07 Programming Exercise 5 Original Exercise: Rock, Paper, Scissors Modification Programming Exercise 11 in Chapter 6 asked you to design a program that plays the Rock, Paper, Scissors game. In the program, the user enters one of the three strings—"rock", "paper", or "scissors"—at the keyboard. Add input validation (with a case-insensitive comparison) to make sure the user enters one of those strings only. Modifications: Allow the user to input "r", "p", "s" or the full strings "Rock",...
Java programming One of the most popular games of chance is a dice game known as...
Java programming One of the most popular games of chance is a dice game known as “craps,” which is played in casinos and back alleys throughout the world. The rules of the game are straightforward: A player rolls two dice. Each die has six faces. These faces contain 1, 2,3,4,5, and 6 spots. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT