Implementation of simple hangman game

126 views Asked by At

I need to implement my own version of the classic hangman game with greek letters.

I have tried to alter my code several times, however it seems that I have a problem managing all the ''if'' and ''else'' statements together. My main problem is that I cannot properly set the new word for the user to see every time his guess is correct(get_word function). Here is my code:

import random

words=['''list of greek words''']

greek_alphabet=['''list of all greek letters''']

def shape(left=5):
    if left==5:
        print('|----------|')
        print('|          O')
        print('|')
        print('|')
        print('|')
        print('|')
        print('|')
    elif left==4:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|')
        print('|')
        print('|')
        print('|') 
    elif left==3:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|')
        print('|')
        print('|')
    elif left==2:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|        _/ \\_')
        print('|')
        print('|')
    elif left==1:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|        _/ \\_')
        print('|        ## ##')
        print('|')
    else:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|        _/ \\_')
        print('|        ## ##')
        print('|         fire')

def get_word(random_word,letter):
    for i in random_word:
        if i==letter:
            new_word.replace('_ ',letter)
    return new_word  

def hangman():
    found=False
    random_word=random.choice(words)
    words.remove(random_word)
    used_letters=[]
    max_guesses=0
    incorrect_guesses=0
    new_word=len(random_word)*'_ '
    print('You can make up to 5 mistakes')
    print('The 6th mistake is going to get you out of the game')
    print('The word you must guess is: ',new_word)
    while not found and incorrect_guesses<max_guesses:
        letter=input('Give letter: ')
        if found_word(random_word,new_word):
            print('Congrats! You found the word!')
            found=True
        elif letter in random_word and letter not in used_letters:
            used_letters.append(letter)
            print('The word you must guess is',get_word(random_word,letter))
        elif letter not in greek_alphabet:
            print('You did not give a letter. Try again.')
        elif letter in used_letters:
            print('This letter has already been used')
        else:
            incorrect_guesses+=1
            left=max_guesses-incorrect_guesses
            shape(left)
            print('You still have ',max_guesses-incorrect_guesses,'lives')
            print('The word you must choose is ',get_word(random_word,letter))

    if not found:
        shape()
        print('You did not find the word')
        print('The word we were looking for was ',random_word)
        return False
    else:
        return True

def found_hidden_word(random_word,new_word):
    if new_word==random_word:
        return True

hangman()

I have tried really hard to even get to that point, because I am an absolute beginner to this, however I believe that with some changes, my code is going to work properly.

2

There are 2 answers

0
Noctis Skytower On BEST ANSWER

May I suggest the following as a starting point? Please note that you will need to supply your own words.txt file with one Greek word per line. Once that file is in the same directory, this program should work fine:

#! /usr/bin/env python3
import random
import sys
import turtle


def main():
    words = load_words()
    my_word = random.choice(words)
    print('Welcome to the game of hangman!')
    print('I have chosen a word for you to guess,')
    print(f'and it contains {len(my_word)} letters.')
    print('Here is the gallows for your hangman.')
    hangman = draw_hangman()
    next(hangman)
    guess = [None] * len(my_word)
    wrong = []
    while True:
        print('This is what you have so far.')
        print(' '.join('_' if char is None else char for char in guess))
        char = get_character()
        if char in guess or char in wrong:
            print(f'You have already guessed {char!r} previously.')
        elif char in my_word:
            for index, my_char in enumerate(my_word):
                if my_char == char:
                    guess[index] = my_char
            if None not in guess:
                print('You have won!')
                print(f'You have guessed {my_word!r} correctly!')
                draw_finish()
        else:
            wrong.append(char)
            print('Wrong!')
            next(hangman)


def get_character():
    while True:
        try:
            char = input('What character would you like to guess? ')
        except EOFError:
            sys.exit()
        except KeyboardInterrupt:
            print('Please try again.')
        else:
            if len(char) != 1:
                print('Only a single character can be accepted.')
            elif not char.isalpha():
                print('Please only use letters from the alphabet.')
            else:
                return char.casefold()


def load_words():
    with open('words.txt') as file:
        return [word.casefold()
                for word in map(str.strip, file)
                if word.isalpha() and len(word) >= 5 and len(set(word)) > 1]


def draw_hangman():
    # Draw the gallows.
    turtle.mode('logo')
    turtle.speed(0)
    turtle.reset()
    turtle.penup()
    turtle.hideturtle()
    turtle.goto(300, -300)
    turtle.pendown()
    turtle.goto(-300, -300)
    turtle.goto(-300, 200)
    turtle.goto(-200, 300)
    turtle.goto(0, 300)
    turtle.color('brown')
    turtle.goto(0, 200)
    yield
    # Draw the head.
    turtle.color('green')
    turtle.left(90)
    turtle.circle(50)
    yield
    # Draw the body.
    turtle.penup()
    turtle.left(90)
    turtle.forward(100)
    turtle.pendown()
    turtle.forward(200)
    yield
    # Draw left arm.
    turtle.penup()
    turtle.backward(150)
    turtle.right(45)
    turtle.pendown()
    turtle.forward(100)
    yield
    # Draw right arm.
    turtle.penup()
    turtle.backward(100)
    turtle.left(90)
    turtle.pendown()
    turtle.forward(100)
    yield
    # Draw left leg.
    turtle.penup()
    turtle.backward(100)
    turtle.right(45)
    turtle.forward(150)
    turtle.right(22.5)
    turtle.pendown()
    turtle.forward(150)
    yield
    # Draw right leg.
    turtle.penup()
    turtle.backward(150)
    turtle.left(45)
    turtle.pendown()
    turtle.forward(150)
    turtle.done()


def draw_finish():
    turtle.penup()
    turtle.goto(0, 0)
    turtle.write('You won!')
    turtle.done()


if __name__ == '__main__':
    main()
2
Miguel On

You have to pass new_word to the function get_word to use it there. When you are replacing you are just creating a new variable new_word.

Either do :

def get_word(random_word, new_word, letter)

(Don't forget to attribute the return of this to new_word again in the hangman method)

OR
declare it as a global (not so good): at the top:

new_word = ""

Inside the functions you use it:

global new_word

Full code as requested:

import random

words=['''list of greek words''']

greek_alphabet=['''list of all greek letters''']

def shape(left=5):
    if left==5:
        print('|----------|')
        print('|          O')
        print('|')
        print('|')
        print('|')
        print('|')
        print('|')
    elif left==4:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|')
        print('|')
        print('|')
        print('|') 
    elif left==3:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|')
        print('|')
        print('|')
    elif left==2:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|        _/ \\_')
        print('|')
        print('|')
    elif left==1:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|        _/ \\_')
        print('|        ## ##')
        print('|')
    else:
        print('|----------|')
        print('|          O')
        print('|         /|\\')
        print('|          |')
        print('|        _/ \\_')
        print('|        ## ##')
        print('|         fire')

def get_word(random_word, new_word, letter):
    for i in random_word:
        if i==letter:
            new_word.replace('_ ',letter)
    return new_word  

def hangman():
    found=False
    random_word=random.choice(words)
    words.remove(random_word)
    used_letters=[]
    max_guesses=0
    incorrect_guesses=0
    new_word=len(random_word)*'_ '
    print('You can make up to 5 mistakes')
    print('The 6th mistake is going to get you out of the game')
    print('The word you must guess is: ',new_word)
    while not found and incorrect_guesses<max_guesses:
        letter=input('Give letter: ')
        if found_hidden_word(random_word,new_word):
            print('Congrats! You found the word!')
            found=True
        elif letter in random_word and letter not in used_letters:
            used_letters.append(letter)
            new_word = get_word(random_word, new_word, letter)
            print('The word you must guess is', new_word)
        elif letter not in greek_alphabet:
            print('You did not give a letter. Try again.')
        elif letter in used_letters:
            print('This letter has already been used')
        else:
            incorrect_guesses+=1
            left=max_guesses-incorrect_guesses
            shape(left)
            print('You still have ',max_guesses-incorrect_guesses,'lives')
            new_word = get_word(random_word,letter)
            print('The word you must choose is ',new_word)

    if not found:
        shape()
        print('You did not find the word')
        print('The word we were looking for was ',random_word)
        return False
    else:
        return True

def found_hidden_word(random_word,new_word):
    if new_word==random_word:
        return True

hangman()