-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.c
97 lines (88 loc) · 2.53 KB
/
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
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "dictio.h"
#include "game.h"
//gameMode 0 = text only gameMode 1 = text & drawing
void run(int gameMode){
int lives = 10;
char secWord[T_MAX_WORD] = "";
pickWord(secWord);
//printf("secWord = %s\n", secWord);
int *trueLetters = NULL; //bool tab contain discovred lettes
int sizeWord = len(secWord)-1; //the last char of the word is '\n' due to the extraction of the file.
trueLetters = malloc(sizeof(int)*sizeWord);
if(trueLetters == NULL){
fprintf(stderr, "[!] Not enough space\n\n");
printf("Press a key to exit.\n");
scanf("%c");
exit(0);
}
initTab(trueLetters, sizeWord);
//Adding the first letter of the word
suggestLetter(secWord, trueLetters, sizeWord, secWord[0]);
printf("Welcome to the hanged man\n\n");
while (lives > 0 && !win(trueLetters, sizeWord)){
printf("you have %d chances left.\n", lives);
for(int i=0;i<sizeWord;i++){
if(trueLetters[i] == 1){
printf("%c", secWord[i]);
}else{
printf("*");
}
}
printf("\n");
int propalTrue = suggestLetter(secWord, trueLetters, sizeWord, readChar());
if(!propalTrue){
lives--;
}
}
if(win(trueLetters, sizeWord)){
printf("You found the word %s", secWord);
}else{
printf("You lost the word was %s", secWord);
}
free(trueLetters);
}
char readChar(){
printf(":\\>");
char character = 0;
character = getchar();
character = toupper(character);
while (getchar() != '\n');
return character;
}
int win(const int* boolTab, const int size){
int i=0;
int remainUndiscoveredCars = 0;
while (i<size && !remainUndiscoveredCars){
remainUndiscoveredCars = (boolTab[i]==0);
i++;
}
return !remainUndiscoveredCars;
}
//return 1 if the word contain the letter, else return 0
int suggestLetter(const char *hiddenWord, int *charOk, const int sizeOfWord, const char proposal){
int trueProposal = 0;
for(int i=0;i<sizeOfWord;i++){
if(hiddenWord[i] == proposal && charOk[i] != 1){
charOk[i] = 1;
trueProposal = 1;
}
}
return trueProposal;
}
void initTab(int *tab,const int size){
for(int i=0;i<size;i++){
tab[i] = 0;
}
}
int len(const char* string){
int size=0;
char letter = 0;
do{
letter = string[size];
size++;
}while (letter != '\0');
return (size-1);
}