import
java.util.*;
class
move {
public
int
pile_index;
public
int
stones_removed;
};
class
GFG {
static
int
COMPUTER =
1
;
static
int
HUMAN =
2
;
static
move moves =
new
move();
static
void
showPiles(
int
[] piles,
int
n)
{
int
i;
System.out.print(
"Current Game Status -> "
);
for
(i =
0
; i < n; i++)
System.out.print(
" "
+ piles[i]);
System.out.println();
return
;
}
static
boolean
gameOver(
int
[] piles,
int
n)
{
int
i;
for
(i =
0
; i < n; i++)
if
(piles[i] !=
0
)
return
false
;
return
true
;
}
static
void
declareWinner(
int
whoseTurn)
{
if
(whoseTurn == COMPUTER)
System.out.print(
"\nHUMAN won\n\n"
);
else
System.out.print(
"\nCOMPUTER won\n\n"
);
return
;
}
static
int
calculateNimSum(
int
[] piles,
int
n)
{
int
i, nimsum = piles[
0
];
for
(i =
1
; i < n; i++)
nimsum = nimsum ^ piles[i];
return
(nimsum);
}
static
void
makeMove(
int
[] piles,
int
n, move moves)
{
Random rand =
new
Random();
int
i, nim_sum = calculateNimSum(piles, n);
if
(nim_sum !=
0
) {
for
(i =
0
; i < n; i++) {
if
((piles[i] ^ nim_sum) < piles[i]) {
(moves).pile_index = i;
(moves).stones_removed
= piles[i] - (piles[i] ^ nim_sum);
piles[i] = (piles[i] ^ nim_sum);
break
;
}
}
}
else
{
int
[] non_zero_indices =
new
int
[n];
int
count =
0
;
for
(i =
0
; i < n; i++) {
if
(piles[i] >
0
) {
non_zero_indices[count] = i;
count +=
1
;
}
}
(moves).pile_index = (rand.nextInt(count));
(moves).stones_removed
=
1
+ (rand.nextInt(
1
+ piles[(moves).pile_index]));
piles[(moves).pile_index]
= piles[(moves).pile_index]
- (moves).stones_removed;
if
(piles[(moves).pile_index] <
0
)
piles[(moves).pile_index] =
0
;
}
return
;
}
static
void
playGame(
int
[] piles,
int
n,
int
whoseTurn)
{
System.out.print(
"\nGAME STARTS\n\n"
);
while
(gameOver(piles, n) ==
false
) {
showPiles(piles, n);
makeMove(piles, n, moves);
if
(whoseTurn == COMPUTER) {
System.out.println(
"COMPUTER removes "
+ moves.stones_removed
+
"stones from pile at index "
+ moves.pile_index);
whoseTurn = HUMAN;
}
else
{
System.out.println(
"HUMAN removes"
+ moves.stones_removed
+
"stones from pile at index "
+ moves.pile_index);
whoseTurn = COMPUTER;
}
}
showPiles(piles, n);
declareWinner(whoseTurn);
return
;
}
static
void
knowWinnerBeforePlaying(
int
[] piles,
int
n,
int
whoseTurn)
{
System.out.println(
"Prediction before playing the game -> "
);
if
(calculateNimSum(piles, n) !=
0
) {
if
(whoseTurn == COMPUTER)
System.out.println(
"COMPUTER will win\n"
);
else
System.out.println(
"HUMAN will win\n"
);
}
else
{
if
(whoseTurn == COMPUTER)
System.out.print(
"HUMAN will win\n"
);
else
System.out.print(
"COMPUTER will win\n"
);
}
return
;
}
public
static
void
main(String[] arg)
{
int
[] piles = {
3
,
4
,
5
};
int
n = piles.length;
knowWinnerBeforePlaying(piles, n, COMPUTER);
playGame(piles, n, COMPUTER);
}
}