-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNimGame.c
122 lines (98 loc) · 2.82 KB
/
NimGame.c
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//
// Created by rooty on 7/25/15.
//
#include <stdio.h>
//constants
#define MAX_BALLZ_2_TAKE 3
#define LINE_DELIMITER "---------------\n"
/**
* macro that prints the balls in a certain box.
*/
#define PRINT_BALLZ(X)({for (int i =0; i < (X); i++){printf("o");} printf("\n");})
/**
* macro that switches the player from 1 to 2 or 2 to 1.
*/
#define SWITCH_PLAYER()( (player==1) ? (player = 2) : (player = 1))
// global vars.
int player = 1; // player defaults to player 1.
int box1Balls = 0; // boxes default to 0.
int box2Balls = 0;
/**
* helper method to print the board.
*/
void printBoard() {
printf(LINE_DELIMITER);
printf("Box 1: ");
PRINT_BALLZ(box1Balls);
printf("Box 2: ");
PRINT_BALLZ(box2Balls);
printf(LINE_DELIMITER);
}
/**
* method that gets the move, validates box choice and processes the move.
*/
void getMove() {
int boxChoice = (int)0;
// get user input.
printf("Player %d, i'ts your turn.\nPlayer %d, choose a box (1 or 2):\n", player, player);
scanf("%1d", &boxChoice);
// check if box choice is OK, then reference the box pointer to the actual box.
if (boxChoice != 1 & boxChoice != 2) {
int *temp = 0;
scanf("%1d", temp);
getMove();
} else {
// pointer to a box.
int *currentBox = 0;
switch (boxChoice) {
case 1:
currentBox = &box1Balls;
break;
case 2:
currentBox = &box2Balls;
break;
}
int numOfBallz;
int inValidMove = 1;
while (inValidMove){
printf("Player %d, how many balls do you want to take from box %d?\n", player, boxChoice);
scanf("%10d", &numOfBallz);
// check if pick is valid
if (numOfBallz < 0) {
printf("Number of balls to take must be positive.\n");
} else if (numOfBallz > MAX_BALLZ_2_TAKE) {
printf("Cannot take more than 3 balls at a time.\n");
} else if (numOfBallz > *currentBox) {
printf("Cannot take more balls than what's in the box.\n");
}
else {
*currentBox -= numOfBallz;
inValidMove = 0;
}
}
}
}
void startGame() {
while (box1Balls != 0 && box2Balls != 0) {
printBoard();
getMove();
SWITCH_PLAYER();
}
}
void getBalls(int *pBox, int boxNum) {
do {
printf("How many balls in box %d?\n", boxNum);
scanf("%2d", pBox);
getchar();
if (*pBox < 0) {
printf("Number of balls in box must be positive.\n");
}
} while (*pBox < 0);
}
int main() {
getBalls(&box1Balls, 1);
getBalls(&box2Balls, 2);
startGame();
printf("Player %d wins the game.\n", player);
return 0;
}