-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoingrab.c
More file actions
93 lines (78 loc) · 2.62 KB
/
Copy pathcoingrab.c
File metadata and controls
93 lines (78 loc) · 2.62 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /* for time() */
int gen_random_num(int coins);
void print_welcome();
void print_coins(int coins, int i);
int main(){
// Seed the RNG for computer randomized selections
srand(time(NULL));
// Initialization Block
int coins = 30; /* Total coins used in the game */
int psel = 0;
int csel = 0;
int i = 0;
print_welcome();
while(coins > 0){
//print the amount of coins
print_coins(coins, i);
//get player input
printf("Please choose 1, 2, or 3: ");
scanf("\n%d", &psel);
//check that player input is within the bounds
do{
if(psel < 1){
printf("You have to take at least one coin. ");
scanf("\n%d", &psel);
} else if(psel > 3 || psel > coins){
printf("Dont take that many coins, greedy! ");
scanf("\n%d", &psel);
}
}while(psel < 1 || psel > 3 || psel > coins);
coins -= psel;
if(coins == 0){
printf("You took the last coin! You Win!\n");
break;
} else{
printf("You take %d coins, there are %d coins left.\n", psel, coins);
}
csel = gen_random_num(coins);
coins -= csel;
if(coins == 0){
printf("The computer took the last coin. You lose.\n");
break;
} else{
printf("The computer takes %d coins, there are %d coins left.\n", csel, coins);
}
}
return 0;
}
// Prints the welcoming message for the game.
void print_welcome(){
printf("Welcome to Coin Grabber.\n");
printf("To play, take either 1, 2, or 3 coins from the stack,\n");
printf("and the computer will make its selection. The one who takes\n");
printf("the last coin from the stack wins. To start, press enter");
getchar();
}
//Selects the computer's Choice between 1, 2, or 3
int gen_random_num(int coins){
int r = (rand() % 3) + 1; //r will be either 1, 2, or 3
// prevent the computer from taking more coins than there are left
// or makes the CPU take the remaining coins if the remaining is
// less than or equal to 3, to simulate a human decision.
if(r > coins){
r = coins;
} else if(coins <= 3){
r = coins;
}
return r;
}
//Prints the remaining coins in a decimal, and ascii format
void print_coins(int coins, int i){
printf("\nRemaining coins (%d): ", coins);
for(i = 0; i < coins; i++){
printf("o");
}
printf("\n");
}