c_winter_2019/hangman.c
2020-01-31 14:49:37 +01:00

103 lines
2 KiB
C

#include <stdio.h>
#include <string.h>
char *gallows[] = {
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"=============\n",
"\n"
"\n"
"\n"
"\n"
"\n"
" -----\n"
" / \\\n"
" / \\\n"
"=============\n",
"\n"
" |\n"
" |\n"
" |\n"
" |\n"
" -----\n"
" / \\\n"
" / \\\n"
"=============\n",
" -----\n"
" |/\n"
" |\n"
" |\n"
" |\n"
" -----\n"
" / \\\n"
" / \\\n"
"=============\n",
" -----\n"
" |/ o\n"
" | ^W^\n"
" | / \\\n"
" |\n"
" -----\n"
" / \\\n"
" / \\\n"
"=============\n",
};
void print_state(int state, char *placeholder, char *wrong_guesses);
int check_input(char *word, char *placeholder, char input);
int main(void) {
int state = 0;
char word[] = "gameover";
char placeholder[] = "________";
char wrong_guesses[6] = {0};
while (state < 5) {
print_state(state, placeholder, wrong_guesses);
char input;
do {
input = getchar();
} while (input == '\n');
if (check_input(word, placeholder, input)) {
if (strcmp(word, placeholder) == 0) {
printf("You won!");
return 0;
}
} else {
wrong_guesses[state] = input;
state++;
if (state == 5) {
printf("You lost!");
return 1;
}
}
}
return 0;
}
void print_state(int state, char *placeholder, char *wrong_guesses) {
printf(gallows[state]);
printf("word: %s\n", placeholder);
printf("wrong: %s\n", wrong_guesses);
}
int check_input(char *word, char *placeholder, char input) {
int occurences = 0;
while (*word != '\0') {
if (*word == input) {
*placeholder = input;
occurences++;
}
word++;
placeholder++;
}
return occurences;
}