Programming NIM with 2 players

Hey! This is my code so far and it works fine but Player 2 cannot win only Player 1. Anyone know how to fix this!








#include <iostream>
#include <string>
using namespace std;
int main()
{
const int total = 13;
int n, mtotal;
bool winner = false;

mtotal = total;

while (!winner)
{
if (mtotal >= 0)
cout << "There are " << mtotal << " sticks" << endl;
cout << "Player 1, pick a number between 1 and 4" << endl;
cin >> n;
if (n >= 1 && n <= 4)
{
cout << "You have removed " << n << " stick(s)" << endl;
mtotal -= n;
}
else
{
cout << " Invalid number" << endl;
}
{
if (mtotal >= 0)
cout << "There are " << mtotal << "sticks" << endl;
cout << "Player 2, pick a number between 1 and 4" << endl;
cin >> n;
if (n >= 1 && n <= 4)
{
cout << "You have removed " << n << " stick(s)" << endl;
mtotal -= n;
}
else
{
cout << " Invalid number " << endl;
}
}

if (mtotal <= 0)
{
winner = true;
cout << " Player 1 wins" << endl;
}

}

system("pause");
}
@vgdd

You don't have any coding done that checks if player 2 wins. Also, you should ONLY check if there are 1 or more sticks to pick, NOT 0. Zero sticks and the game ends.

Here is the game where either player can win, if the opponent takes the last stick.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <string>
using namespace std;
int main()
{
	const int total = 13;
	int n, mtotal;
	bool winner = false;

	mtotal = total;

	do
	{
		if (mtotal > 0)
		{
			cout << "There are " << mtotal << " sticks" << endl;
			cout << "Player 1, pick a number between 1 and 4" << endl;
			cin >> n;
			if (n >= 1 && n <= 4)
			{
				cout << "You have removed " << n << " stick(s)" << endl;
				mtotal -= n;
			}
			else
			{
				cout << " Invalid number" << endl;
			}
			if (mtotal < 1 )
			{
				winner = true;
				cout << " Player 2 wins" << endl;
			}
		}
		if (mtotal > 0)
		{
			cout << "There are " << mtotal << " sticks" << endl;
			cout << "Player 2, pick a number between 1 and 4" << endl;
			cin >> n;
			if (n >= 1 && n <= 4)
			{
				cout << "You have removed " << n << " stick(s)" << endl;
				mtotal -= n;
			}
			else
			{
				cout << " Invalid number " << endl;
			}
			if (mtotal < 1 )
			{
				winner = true;
				cout << " Player 1 wins" << endl;
			}
		}

	}while(!winner);

	system("pause");
}


Also, you should check if the player tries to take more than the amount of sticks left.
Topic archived. No new replies allowed.