-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguessing_game.c
87 lines (76 loc) · 1.91 KB
/
guessing_game.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main()
{
int secret;
int guess;
int countdown;
int c;
char buf[20];
char input[20];
time_t t;
printf("Welcome, would you like to play a guessing game?\n");
if (fgets(buf, 20, stdin) == NULL)
return -1;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
else
while ((c = getchar()) != EOF && c != '\n')
;
if (sscanf(buf, "%s", input) == EOF)
return -1;
countdown = 3;
/* Initializes pseudo-random number generator using the current time. */
srand((unsigned)time(&t));
secret = (rand() % 10) + 1;
/* DeMorgan's Law */
while (!(strcmp(input, "YES") && strcmp(input, "Yes") && strcmp(input, "yes") && strcmp(input, "Y") && strcmp(input, "y")))
{
printf("Please enter your guess from 1 - 10, you have %d tries remaining: ", countdown);
if (fgets(buf, 20, stdin) == NULL)
return -1;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
else
while ((c = getchar()) != EOF && c != '\n')
;
if (sscanf(buf, "%d", &guess) == EOF)
return -1;
if (guess < 1 || guess > 10)
{
printf("Error, please enter a number from the correct range.\n");
continue;
}
--countdown;
if (guess == secret)
{
printf("You got it! The secret was %d\n", secret);
/* If user guessed correctly, randomize the new secret value. */
secret = (rand() % 10) + 1;
countdown = 3;
}
else
{
printf("Aww you missed.\n");
if (countdown <= 0)
{
printf("The correct value was %d.\n", secret);
printf("Thank you very much for playing! Please try again some other time.\n");
break;
}
}
printf("Would you like to try again?\n");
if (fgets(buf, 20, stdin) == NULL)
return -1;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
else
while ((c = getchar()) != EOF && c != '\n')
;
if (sscanf(buf, "%s", input) == EOF)
return -1;
}
return 0;
}