-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnum_dos.c
91 lines (75 loc) · 2.21 KB
/
num_dos.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <conio.h>
int main()
{
int i, num = 0, guess = 0, tries = 0, limit = 0, max_tries = 0;
char name[100], buffer[100], *end;
randomize();
printf("Welcome to NumGuess C version!\n\n");
printf("Enter your name: ");
fgets(name, sizeof(name) - 1, stdin);
// Make sure we have a nice zero terminated string
name[99] = '\0';
for(i = 0; i < sizeof(name); i++) {
if(name[i] == '\n') {
name[i] = '\0';
break;
}
}
if(name[0] == '\0') strcpy(name, "Player");
printf("\nWelcome %s, enter upper limit: ", name);
fgets(buffer, sizeof(buffer), stdin);
limit = atoi(buffer);
if(limit < 10) limit = 10;
max_tries = (int)floor(log2(limit)) + 1;
while(1) {
num = random(limit) + 1;
guess = 0;
tries = 0;
printf("\nGuess my number between 1 and %d!\n", limit);
while(num != guess) {
printf("\nGuess: ");
fgets(buffer, sizeof(buffer), stdin);
guess = strtol(buffer, &end, 10);
if(end == buffer || (*end != '\0' && *end != '\n')) {
// Conversion failed with either invalid character at start
// or non-terminating character at the end.
printf("That's just plain wrong.");
// Clear guess to avoid triggering win condition when there
// are trailing junk characters (ignored by strtol).
guess = 0;
} else if((guess < 1) || (guess > limit)) {
printf("Out of range.");
} else {
tries++;
if(num < guess) {
printf("Too high!");
} else if(num > guess) {
printf("Too low!");
}
}
}
printf("\nWell done %s, you guessed my number from %d %s!\n", name, tries, tries == 1 ? "try" : "tries");
if(tries == 1) {
printf("You're one lucky bastard!");
} else if(tries < max_tries) {
printf("You are the master of this game!");
} else if(tries == max_tries) {
printf("You are a machine!");
} else if(tries <= max_tries * 1.1) {
printf("Very good result!");
} else if(tries <= limit) {
printf("Try harder, you can do better!");
} else {
printf("I find your lack of skill disturbing!");
}
printf("\nPlay again [y/N]? ");
fgets(buffer, sizeof(buffer), stdin);
if((buffer[0] != 'y') && (buffer[0] != 'Y')) break;
}
printf("\nOkay, bye.\n");
return 0;
}