TransWikia.com

Hangman Game in Python-3

Code Review Asked by Phinn Galactica on December 7, 2020

answer = input("what's the word")
answer_list = list(answer) #list version of the original word
presentation = []
for i in range(len(answer_list)):
    presentation.append("_") #makes a list that shows the progress of the player during the game

incorrect = 0 #number of allowed guesses
completion = False # condition for end game
while completion == False:
    attempt = input('guess')
    ind = 0 #index of the guess that appears in answer_list
    count = 0 #number of occurences of the guess in answer_list
    for x in answer_list: #searches for all occurences of the guess in answer_list and change presentation accordingly
        if x == attempt:
            num = answer_list.index(attempt)
            presentation[num] = attempt
            answer_list[num] = 0 #if there is an occurence, replace that occurence with 0 in answer_list
            count += 1
    if count>0:
        print ("Your guess is correct, there was/were {} matches in the word".format(count))
        print(presentation)
    elif count == 0:
        incorrect += 1

    if incorrect == 5:
        print("You lost")
        break
    
    if any(answer_list) == False: #since all 0 have a negative truthy value, we can use any() to check if any element has a truthy value 
        print("Congrats, you got everything correct")
        completion = True
        break

I want to make clean up this hangman game and format it as 1 or 2 functions. How do I make it work? For example, initializing lists could be initialize() and from the declaration of incorrect to the end of the code can be play_hangman(). I am still very new to python.

One Answer

Welcome to Code Review!

PEP-8

Since you're still new to python, it's a good idea to keep a window/tab open with PEP-8 loaded into it. It is mostly suggestions for coding style. Few things that can be picked up from the same:

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.
  • Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:

Functions

As you've already raised this point, splitting the code into individual functions is always a good practice.

if __name__ block

Put the execution logic of your script inside the if __name__ == "__main__" block. Read more about the details on why on stack overflow.

f-string

Python 3.x also introduced literal string interpolation, or more commonly used term: f-string. Read more about it here (PEP-498).

Type hinting

When writing functions, you can also make use of type hinting to provide a more readable flow of your code to anyone. This helps removing the manual labour of having to backtrack variable types etc. More details can be found in PEP-484.

Game logic

The initialisation of presentation array can be simplified to:

presentation = ["_"] * len(answer)

For every guessed character from the user, you keep looping over the answer_list, irrespective of validating whether the guess is correct or not.

Before the loop over each character of the correct word, you have setup ind = 0 which is never really used.

Your global while loop relies on the condition completion == False (which should ideally be completion is False) but you break out before the loop/condition really has a chance to do so for you, making the variable useless.


Rewrite

from typing import List

MAX_ATTEMPTS: int = 5


def get_answer() -> str:
    return input("What's the word? ")


def correct_guess(char_count: int, guessed_word: List[str]):
    print(f"Your guess is correct, there was/were {char_count} matches in the word.")
    print(" ".join(guessed_word))


def game_win(guessed_word: List[str]) -> bool:
    return "_" in guessed_word


def game():
    answer = get_answer()
    correct_letters = set(answer)
    guessed_word = ["_"] * len(answer)
    incorrect = 0
    while True:
        if incorrect >= MAX_ATTEMPTS:
            print("You lost!")
            break
        attempt = input("Guess: ")
        if attempt not in correct_letters:
            incorrect += 1
            continue
        char_count = 0
        for index, char in enumerate(answer):
            if char == attempt:
                guessed_word[index] = char
                char_count += 1
        correct_guess(char_count, guessed_word)
        if game_win(guessed_word):
            print("Congrats, you got everything correct")
            break


if __name__ == "__main__":
    game()

Answered by hjpotter92 on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP