Hangman in C language

Can someone help me do this in C language? How do I put 7 chances for the player to guess?

DIRECTIONS:
Hangman Game

Hangman is a game that let’s its player determine a word or group of words by enumerating letters
possibly in the puzzle with a limited number of guesses. In every guess, the player is allowed a chance to
solve the puzzle and if it’s incorrect, it will reduce the number of guesses by 1.
Code conditions:
1. You are to create up to 5 one-word puzzles for this game.
2. Every game must select a random word from your predefined words.
3. The player has up to seven (7) guesses to win.

Last edited on
What are you having trouble with? We won't write the code for you, but if you post what you have we'll provide advice and guidance.
Will never win with puzzle 4 :+)
@seeplus

here is the code I made I can't run it tho. Also how do I limit the chances for the player to guess at maximum of 7 guesses only? the <7 tries doesn't work for me.

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include <stdio.h>
#include <string.h>
#define letters 5
int search(const char list[], int letternum, char letter);

int main(void);
{
    int day;
    printf("Please choose a number\n");
    printf("Input A to guess the word number 1\n");
    printf("Input B to guess the word number 2\n");
    printf("Input C to guess the word number 3\n");
    printf("Input D to guess the word number 4\n");
    printf("Input E to guess the word number 5\n");
    day = getchar();
    switch(day){
        case'A':
        printf("guess the word number 1\n");
        break;
        {
char word[letters] = {'p','e', 'a', 'c', 'h'};
char guess_word[letters];
char letter;
int location;
int tries = 0;
int i = 0;

for( i = 0; i < letters; i++ )
   guess_word[i] = '_';
   do
{
printf("choose a letter: ");
scanf("%1s", &letter);

location = search(word, letters, letter);

if ( location != -1 )
{
    printf("%c was found\n", letter);
    guess_word[location] = letter;
    for( i = 0; i < letters; i++ )
       printf(" %c",guess_word[i]);
    printf("\n");
}
    
else printf("%c was not found\n", letter);

++tries;

}while(tries < 7);

return 0;
}

int search(const char list[], int letternum, char letter)
{
int i = 0, found = 0;

while (i < letternum && !found)
{
if (list[i] == letter) found = 1;

else i++;
}

if( found == 1 )
  return i;
else
  return -1;
}
  case 'B':
  printf("guess the word number 2\n");
  break;
  {
      char word[letters] = {'k','i', 'n', 'g', 'd', 'o', 'm'};
char guess_word[letters];
char letter;
int location;
int tries = 0;
int i = 0;

for( i = 0; i < letters; i++ )
   guess_word[i] = '_';
   do
{
printf("choose a letter: ");
scanf("%1s", &letter);

location = search(word, letters, letter);

if ( location != -1 )
{
    printf("%c was found\n", letter);
    guess_word[location] = letter;
    for( i = 0; i < letters; i++ )
       printf(" %c",guess_word[i]);
    printf("\n");
}
    
else printf("%c was not found\n", letter);

++tries;

}while(tries < 7);

return 0;
}

int search(const char list[], int letternum, char letter)
{
int i = 0, found = 0;

while (i < letternum && !found)
{
if (list[i] == letter) found = 1;

else i++;
}

if( found == 1 )
  return i;
else
  return -1;
  }
  case 'B':
  printf("guess the word number 3\n");
  break;
  {
      char word[letters] = {'p','r', 'o', 'g', 'r', 'a', 'm'};
char guess_word[letters];
char letter;
int location;
int tries = 0;
int i = 0;

for( i = 0; i < letters; i++ )
   guess_word[i] = '_';
   do
{
printf("choose a letter: ");
scanf("%1s", &letter);

location = search(word, letters, letter);

if ( location != -1 )
{
    printf("%c was found\n", letter);
    guess_word[location] = letter;
    for( i = 0; i < letters; i++ )
       printf(" %c",guess_word[i]);
    printf("\n");
}
    
else printf("%c was not found\n", letter);

++tries;

}while(tries < 7);

return 0;
}

int search(const char list[], int letternum, char letter)
{
int i = 0, found = 0;

while (i < letternum && !found)
{
if (list[i] == letter) found = 1;

else i++;
}

if( found == 1 )
  return i;
else
  return -1;
  }
  case 'B':
  printf("guess the word number 4\n");
  break;
  {
      char word[letters] = {'t','o', 'f', 'u'};
char guess_word[letters];
char letter;
int location;
int tries = 0;
int i = 0;

for( i = 0; i < letters; i++ )
   guess_word[i] = '_';
   do
{
printf("choose a letter: ");
scanf("%1s", &letter);

location = search(word, letters, letter);

if ( location != -1 )
{
    printf("%c was found\n", letter);
    guess_word[location] = letter;
    for( i = 0; i < letters; i++ )
       printf(" %c",guess_word[i]);
    printf("\n");
}
    
else printf("%c was not found\n", letter);

++tries;

}while(tries < 7);

return 0;
}

int search(const char list[], int letternum, char letter)
{
int i = 0, found = 0;

while (i < letternum && !found)
{
if (list[i] == letter) found = 1;

else i++;
}

if( found == 1 )
  return i;
else
  return -1;
  }
  case 'B':
  printf("guess the word number 5\n");
  break;
  {
      char word[letters] = {'g','a', 'm', 'e'};
char guess_word[letters];
char letter;
int location;
int tries = 0;
int i = 0;

for( i = 0; i < letters; i++ )
   guess_word[i] = '_';
   do
{
printf("choose a letter: ");
scanf("%1s", &letter);

location = search(word, letters, letter);

if ( location != -1 )
{
    printf("%c was found\n", letter);
    guess_word[location] = letter;
    for( i = 0; i < letters; i++ )
       printf(" %c",guess_word[i]);
    printf("\n");
}
    
else printf("%c was not found\n", letter);

++tries;

}while(tries < 7);

return 0;
}

int search(const char list[], int letternum, char letter)
{
int i = 0, found = 0;

while (i < letternum && !found)
{
if (list[i] == letter) found = 1;

else i++;
}

if( found == 1 )
  return i;
else
  return -1;
  }

}
That's a lot of code for a hangman game! Any reason you're not using C++? You really should.

Your code is very messy and has A LOT of mistakes. I recommend you go through a C or C++ tutorial and look at switch examples.


Here's a quick breakdown:

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// ConsoleApplication36.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <stdio.h>
#include <string.h>
#define letters 5
int search(const char list[], int letternum, char letter);

int main(void)//; semicolon?
{
    int day;
    printf("Please choose a number\n");
    printf("Input A to guess the word number 1\n");
    printf("Input B to guess the word number 2\n");
    printf("Input C to guess the word number 3\n");
    printf("Input D to guess the word number 4\n");
    printf("Input E to guess the word number 5\n");
    day = getchar();
    switch (day) {
    case'A':
        printf("guess the word number 1\n");
        break; //break?
       /* {//A bracket?
            char word[letters] = { 'p','e', 'a', 'c', 'h' };
            char guess_word[letters];
            char letter;
            int location;
            int tries = 0;
            int i = 0;

            for (i = 0; i < letters; i++)
                guess_word[i] = '_';
            do
            {
                printf("choose a letter: ");
                scanf("%1s", &letter);

                location = search(word, letters, letter);

                if (location != -1)
                {
                    printf("%c was found\n", letter);
                    guess_word[location] = letter;
                    for (i = 0; i < letters; i++)
                        printf(" %c", guess_word[i]);
                    printf("\n");
                }

                else printf("%c was not found\n", letter);

                ++tries;

            } while (tries < 7);

            return 0;
        } //Nothing in your brackets will be executed because there's a BREAK right before it

        //Random function in here? Put it outside of int main()
        int search(const char list[], int letternum, char letter)
        {
            int i = 0, found = 0;

            while (i < letternum && !found)
            {
                if (list[i] == letter) found = 1;

                else i++;
            }

            if (found == 1)
                return i;
            else
                return -1;
        }*/
    case 'B':
        printf("guess the word number 2\n");
        break;
        /* {
            char word[letters] = { 'k','i', 'n', 'g', 'd', 'o', 'm' };
            char guess_word[letters];
            char letter;
            int location;
            int tries = 0;
            int i = 0;

            for (i = 0; i < letters; i++)
                guess_word[i] = '_';
            do
            {
                printf("choose a letter: ");
                scanf("%1s", &letter);

                location = search(word, letters, letter);

                if (location != -1)
                {
                    printf("%c was found\n", letter);
                    guess_word[location] = letter;
                    for (i = 0; i < letters; i++)
                        printf(" %c", guess_word[i]);
                    printf("\n");
                }

                else printf("%c was not found\n", letter);

                ++tries;

            } while (tries < 7);

            return 0;
        }

        int search(const char list[], int letternum, char letter)
        {
            int i = 0, found = 0;

            while (i < letternum && !found)
            {
                if (list[i] == letter) found = 1;

                else i++;
            }

            if (found == 1)
                return i;
            else
                return -1;
        }*/
    case 'B': //Another case for 'B'?
        printf("guess the word number 3\n");
        break;
       /* {
            char word[letters] = { 'p','r', 'o', 'g', 'r', 'a', 'm' };
            char guess_word[letters];
            char letter;
            int location;
            int tries = 0;
            int i = 0;

            for (i = 0; i < letters; i++)
                guess_word[i] = '_';
            do
            {
                printf("choose a letter: ");
                scanf("%1s", &letter);

                location = search(word, letters, letter);

                if (location != -1)
                {
                    printf("%c was found\n", letter);
                    guess_word[location] = letter;
                    for (i = 0; i < letters; i++)
                        printf(" %c", guess_word[i]);
                    printf("\n");
                }

                else printf("%c was not found\n", letter);

                ++tries;

            } while (tries < 7);

            return 0;
        }

        int search(const char list[], int letternum, char letter)
        {
            int i = 0, found = 0;

            while (i < letternum && !found)
            {
                if (list[i] == letter) found = 1;

                else i++;
            }

            if (found == 1)
                return i;
            else
                return -1;
        }*/
    case 'B':
        printf("guess the word number 4\n");
        break;
        /* {
            char word[letters] = { 't','o', 'f', 'u' };
            char guess_word[letters];
            char letter;
            int location;
            int tries = 0;
            int i = 0;

            for (i = 0; i < letters; i++)
                guess_word[i] = '_';
            do
            {
                printf("choose a letter: ");
                scanf("%1s", &letter);

                location = search(word, letters, letter);

                if (location != -1)
                {
                    printf("%c was found\n", letter);
                    guess_word[location] = letter;
                    for (i = 0; i < letters; i++)
                        printf(" %c", guess_word[i]);
                    printf("\n");
                }

                else printf("%c was not found\n", letter);

                ++tries;

            } while (tries < 7);

            return 0;
        }

        int search(const char list[], int letternum, char letter)
        {
            int i = 0, found = 0;

            while (i < letternum && !found)
            {
                if (list[i] == letter) found = 1;

                else i++;
            }

            if (found == 1)
                return i;
            else
                return -1;
        }*/


    }
} // You were missing this final bracket 



https://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm
Last edited on
That's a lot of code for a hangman game! Any reason you're not using C++? You really should.

Oh no :( I am asked to do it in C language
Your code's a mess. It probably doesn't compile, if you're lucky; really unlucky if it does.

Start by thinking about your algorithm, maybe pseudo-code will help. It might look something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
reference_word = "hello" // set this value accordingly
max_tries := length( reference_word ) + 5 // set this value accordingly
n_matches = 0;

n_tries := 0;
while ((n_matches < length(reference_word)) and (n_tries < max_tries))
    ch := read letter from player
    match := (ch == reference_word[ n_matches ])
    if (match)
        ++n_matches
    endif
endwhile

win := (n_matches < length(reference_word))
if (win)
    print "You won"
else
    print "You failed, the word was: ${reference_word}"
endif


Once you're happy with the algorithm, you can proceed to encode that in your language of choice.

C is a particularly low level language (even though it's described as a high level language) and things can become unmanageable quickly.

That pseudo-code may translate to something like this, but it's deliberately incomplete. Also, I haven't tried to compile it, so it may contain syntax errors:
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
#include <stdio.h>  /* I expect you'll need this */
#include <stdlib.h> /* srand(), rand() */
#include <string.h> /* strlen() */

#define MAX_WORD_LENGTH (32)

void generate_word(cnar* word, size_t len);
char read_letter(size_t n_tries);

int main(void) {
    srand(time(NULL)); // seed the PRNG

    char reference_word[MAX_WORD_LENGTH];
    generate_word(reference_word, MAX_WORD_LENGTH);
    const size_t max_tries = strlen(reference_word) + 5;

    size_t n_matches = 0;
    for (size_t n_tries = 0;
         (n_matches < strlen(reference_word)) && (n_tries < max_tries); ++n_tries) {
        char ch = read_letter(n_tries);

        if (ch == reference_word[n_tries])
            ++n_matches;
    }

    int win = n_matches == strlen(reference_word);
    // print the results
}

void generate_word(char* word, size_t len) {
    const char* words[] = {
        "hello",
        "world",
        "python",
        "nightmare",
        nullptr
    };
    int idx = rand() % 4;
    strncpy(word, words[idx], len);
}

char read_letter(size_t n_tries) {
    /* you need to implement this */
    return ' ';
}


EDIT: I've noticed it has C++ in places (for loop and nullptr), and we probably need time.h, so yeah, it won't compile as is.
Last edited on
Unfortunately I can't run the code Idk why I think I need to remake everything only in C language
Perhaps consider:

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_WORD_LENGTH (32)

void generate_word(char* word, size_t len);

int main(void) {
	srand(time(NULL));
	const size_t max_guess = 7;

	char reference_word[MAX_WORD_LENGTH] = {0};
	char guess_word[MAX_WORD_LENGTH] = {0};
	char used[MAX_WORD_LENGTH] = {0};

	generate_word(reference_word, MAX_WORD_LENGTH);

	const size_t wlen = strlen(reference_word);

	memset(guess_word, '_', wlen);

	printf("The word has %zu letters\n", wlen);
	printf("You have %zu guesses\n\n", max_guess);

	for (size_t n_tries = 1; n_tries <= max_guess && strcmp(reference_word, guess_word) != 0; ++n_tries) {
		char guess[MAX_WORD_LENGTH] = {0};

		printf("%s\n\nGuess %zu. Either enter a letter or a word guess: ", guess_word, n_tries);
		scanf("%s", guess);

		if (guess[1] == 0) {
			size_t cnt = 0;

			if (strchr(used, guess[0])) {
				printf("You have already guessed %c\n", guess[0]);
				--n_tries;
			} else {
				char g[2] = {guess[0], 0};

				strcat(used, g);

				for (char* st = reference_word, *fnd = 0; *st && ((fnd = strchr(st, guess[0])) != NULL); st = fnd + 1) {
					guess_word[fnd - reference_word] = guess[0];
					++cnt;
				}

				if (cnt)
					printf("You found %zu instances of %c\n", cnt, guess[0]);
				else
					printf("Sorry. %c isn't in the word\n", guess[0]);
			}
		} else
			if (strcmp(guess, reference_word) == 0) {
				strcpy(guess_word, guess);
				break;
			}
	}

	if (strcmp(reference_word, guess_word) == 0)
		puts("You guessed the word!");
	else
		printf("Sorry. You didn't guess %s\n", reference_word);
}

void generate_word(char* word, size_t len) {
	static const char* const words[] = {
		"hello",
		"world",
		"python",
		"nightmare",
	};

	snprintf(word, len, "%s", words[rand() % 4]);
}

Last edited on
Perhaps consider:

Thank you so much for this, I didn't know I can just generate the words I thought switching controls will be easy to make it. Now I have learned how to put all in one without using switches. Problem solved!
Topic archived. No new replies allowed.