Nim

September 2nd, 2007 by Daniel Høyer Iversen

Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object. The player who take the last object loses.

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
using namespace std;
 
int computer(int max, int numMatches);
int human(int max, int numMatches);
 
int main ()
{
int numbMatches(0), maxMatches(0), temp(0);
 
cout << "Number of matches:";
cin  >> numbMatches;
 
cout << "Maximum matches to take:";
cin  >> maxMatches;
 
if( 2 == (rand() % 2 + 1) ){
cout << "Your turn to start. ";
temp = human(maxMatches, numbMatches);
numbMatches -= temp;
 
cout << "Matches left: " << numbMatches <<"n";
if(numbMatches == 0 ){
cout << " You lose, I win  :)  ";
}
}else{
cout << "My turn to start. ";
}
 
while(numbMatches > 0 ){
temp = computer(maxMatches, numbMatches);
 
cout << "I take " <<  temp << " matches.";
numbMatches -= temp;
cout << " Matches left: " << numbMatches <<"n";
if(numbMatches == 0 ){
cout << "I lose, you win"<<"n";
break;
}
 
temp = human(maxMatches, numbMatches);
numbMatches -= temp;
 
cout << "Matches left: " << numbMatches <<"n";
if(numbMatches == 0 ){
cout << "You lose, I win  :)  " <<"n";
}
}
return 0;
}
 
int computer(int max, int numMatches){
int temp = numMatches;
if(numMatches - max > 1){
while( temp % (max +1) != 0){
temp--;
}
 
temp = numMatches - temp-1;
}else{
temp= numMatches -1;
}
if(temp < 1){
return 1;
}
return temp;
}
 
int human(int max, int numMatches){
int temp(0);
 
cout << "Your turn: ";
cin >> temp;
 
while( temp > max || numMatches -temp < 0 || temp <= 0){
cout << "The number has to be less then " << max << "." "n";
cout << "Your turn: ";
cin >> temp;
}
return temp;
}
Do you want to use this code?

0 Responses to “Nim”

  1. No Comments

Leave a Response