Advertisement

game of nim

Started by May 03, 2021 08:27 PM
6 comments, last by pbivens67 3 years, 4 months ago

I am working on the game of nim. In my code it does not get to the winner output of my game.

#include <iostream>
#include <math.h>
#include <time.h>

using namespace std;

int main() 
{
	int init_size, first_turn, AI, play_turn, comp_turn,count;
	srand(time(NULL));
	init_size = rand() % 100 + 10;
	first_turn = rand() % 1 + 0;
	AI = rand() % 1 + 0;

	while (init_size != 0)
	{
		if (first_turn == 1)
		{
			play_turn = rand() % (init_size / 2) + 1;
			init_size = init_size - play_turn;
			first_turn = 0;
			count = 1;
		}
		if (first_turn == 0)
		{
			comp_turn = rand() % (init_size / 2) + 1;
			init_size = init_size - comp_turn;
			first_turn = 1;
			count = 0;
		}
	}

	if (count == 1)
	{
		cout << "Player Wins" << endl;
	}

	if (count == 0)
	{
		cout << "Computer Wins" << endl;
	}

	return 0;
}

pbivens67 said:
In my code it does not get to the winner output of my game.

Then likely the while loop is an infinite loop.

Put some cout into that loop or better use debugger to see why.

My guess is init_size goes below zero.

Advertisement

I made the changes as suggested. However it only outputs “computer wins” text.

#include <iostream>
#include <math.h>
#include <time.h>

using namespace std;

int main() 
{
	int init_size, first_turn, AI, play_turn, comp_turn,count;
	srand(time(NULL));
	init_size = rand() % 100 + 10;
	first_turn = rand() % 1 + 0;
	AI = rand() % 1 + 0;

	while (init_size >= 2)
	{
		if (first_turn == 1)
		{
			play_turn = rand() % (init_size / 2) + 1;
			init_size = init_size - play_turn;
			first_turn = 0;
			count = 1;
		}
		if (first_turn == 0)
		{
			comp_turn = rand() % (init_size / 2) + 1;
			init_size = init_size - comp_turn;
			first_turn = 1;
			count = 0;
		}
		cout << init_size << endl;
	}

	if (count == 1)
	{
		cout << "Player Wins" << endl;
	}

	if (count == 0)
	{
		cout << "Computer Wins" << endl;
	}

	return 0;
}

Maybe this:

if (first_turn == 1)
		{
			play_turn = rand() % (init_size / 2) + 1;
			init_size = init_size - play_turn;
			first_turn = 0;
			count = 1;
		}
		if (first_turn == 0)

should be this instead:

if (first_turn == 1)
		{
			play_turn = rand() % (init_size / 2) + 1;
			init_size = init_size - play_turn;
			first_turn = 0;
			count = 1;
		}
		else // if (first_turn == 0)

As it is now, computer does a turn in every round because player sets first_turn = 0;

well I put in the else statement and it worked, thanks!

Yay : )

Using the debugger, you would see both players code gets executed one after another, and instantly notice the reason. ; )

Advertisement

thanks for all the help

This topic is closed to new replies.

Advertisement