#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define inf (1<<30)-1
#define SIZE 10001
#define forn(i,n) for (i=0;i<n;i++)
#define forr(i,n) for (i=n-1;i>=0;i--)
#define forab(i,p,k) for (i=p; i<=k;i++)
string players[3] = { "HUMAN", "COMPUTER" };
int gameBoard[100001],n;
int Score,currentPlayer,Round;
void printGameBoard(int gameBoard[])
{
int i;
printf("\nGame State: ");
forn(i,n) printf("\t%d",gameBoard[i]);
}
int maxIndex(int arr[])
{
int index = 0,i;
int Max = arr[0];
forn(i,n)
if(Max < arr[i])
{
Max = arr[i];
index = i;
}
return index;
}
void humanPlays(int gameBoard[])
{
int Stack,Piles;
invalid :
printf("\nFrom Which Stack ... : ");
scanf("%d",&Stack);
printf("\nNumber of Piles to remove : ");
scanf("%d",&Piles);
if(gameBoard[Stack - 1] == 0)
{
printf("\nInvalid move !!!!");
goto invalid;
}
else if(Piles > gameBoard[Stack - 1]) goto invalid;
else gameBoard[Stack - 1] -= Piles;
}
void computerPlays(int game[],int n)
{
int Stack, len = n, XOR = 0,i,afterandGame[n+1];
forn(i,len) XOR ^= game[i];
if (XOR == 0)
{
// min move to make game last longer and push user to mistake
while(gameBoard[Stack = (int)(rand() % len)] == 0);
gameBoard[Stack]--;
}
else
{
forn(i,len) afterandGame[i] = gameBoard[i] & XOR;
Stack = maxIndex(afterandGame);
gameBoard[Stack] -= (gameBoard[Stack] - (XOR ^ gameBoard[Stack]));
}
}
int main()
{
int i;
while(true)
{
Score = -1;
currentPlayer = Round = 0;
printf("Start Nim Game : \n\nPlease Enter the no of Stack : ");
scanf("%d",&n);
forn(i,n) gameBoard[i] = rand() % 20 + 1;
while(Score != 0)
{
printGameBoard(gameBoard);
currentPlayer = Round % 2;
cout << endl << endl;
cout << players[currentPlayer] << " Plays. " << endl;
cout << endl << endl;
if (currentPlayer == 0) humanPlays(gameBoard);
else computerPlays(gameBoard,n);
Score = 0;
forn(i,n) Score += gameBoard[i];
Round++;
}
cout << players[currentPlayer] << " wins.\n" << endl;
}
return 0;
}
No comments:
Post a Comment