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
Petra
...
When writing this JAVA program only use arrays, keyboardreader functions and no other function. You can only use Arrays.toString but you cannot use any other. Please put down below if you have any other functions that you want to use and I will look at it.
hey there ! i update the code .. Please give me a like to appreciate my work and efforts...
here is the code -
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author Aditya kumar
*/
public class BoardGame {
public static void main(String args[])
{
//declaring varibales
int pile,howmany;
String playername="";
//for taking user input
Scanner sc=new Scanner(System.in);
//create array
int board[]={1,2,3,4};
//showing output
System.out.println("Player #1 : ");
playername=sc.next();
System.out.println(Arrays.toString(board));
System.out.println(playername+" : ");
boolean va=true;
while(va)
{
if(board[0]==1 && board[1]==1 && board[2]==1
&& board[3]==1)
{
va=false;
}
else
{
System.out.println("Which Pile ? ");
//take input as pile number and as array start from zero
//so we need to -1 value from the pile
//for example - if user enter 4 , so the position will be 3 in the
array
pile=sc.nextInt()-1;
System.out.println("How Many ? ");
//take how many wants to remove by user
howmany=sc.nextInt();
//taking the value from the pile's position
int v=board[pile];
//substract v from the howmay
howmany=v-howmany;
//set the new value
board[pile]=howmany;
//print the array
System.out.println(Arrays.toString(board));
}
}
}
}
and the snapshot of the output is -
Thank You ! Dont Forget to like !
Get Answers For Free
Most questions answered within 1 hours.