Skip to main content
deleted 61 characters in body
Source Link
user203258
user203258
import random
import string

words = [word for word in open('random_words.txt').read().split()]
attempts = 6
hangman_pics = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
========='''][::-1]


def get_current_figure():
    """Print current state of Hangman."""
    print(hangman_pics[attempts])


def play_game():
    """Play game."""
    global attempts
    available_letters = list(string.ascii_lowercase)
    letters_guessed = []
    secret_word = random.choice(words)
    slots = ['_' for _ in range(len(secret_word))]
    valid_responses = ['y', 'yes', 'n', 'no']
    print('Welcome to the hangman!')
    confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()
    while confirm_start not in valid_responses:
        print(f'Invalid response! {confirm_start}  Enter y/n')
        confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()
    if confirm_start == 'n' or confirm_start == 'no':
        print('Thank you for playing Hangman.')
        print(29 * '=')
        exit(0)
        print(f'The word to guess is {len(secret_word)} long.')
    while confirm_start == 'y' or confirm_start == 'yes':
        if not attempts:
            get_current_figure()
            print(f"You're dead, the word was {secret_word}")
            break
        check_win = 0
        for letter in secret_word:
            if letter in letters_guessed:
                check_win += 1
        if check_win == len(secret_word):
            print(f'Well done! you win.\nThe correct word is {secret_word}')
        print(45 * '=')
        get_current_figure()
        print(f"Available letters: {''.join(available_letters)}")
        print(f"Letters used: {''.join(sorted(letters_guessed))}")
        print(f'You have {attempts} attempts left.')
        print(slots, '\n')
        letter_guessed = input('Guess a letter:  ').lower()
        if letter_guessed in letters_guessed:
            print(f'You already tried that letter {letter_guessed}')
            attempts -= 1
        if letter_guessed.isalpha() and len(letter_guessed) == 1 and letter_guessed not in letters_guessed:
            available_letters.remove(letter_guessed)
            letters_guessed.append(letter_guessed)
            if letter_guessed in secret_word and len(letter_guessed) == 1:
                for index, letter in enumerate(secret_word):
                    if letter_guessed == letter:
                        slots[index] = letter
                print(f'Correct guess! {letter_guessed} is in the word.')
            if letter_guessed not in secret_word:
                attempts -= 1
                print(f'Wrong guess! {letter_guessed} not in the word.')
        if not letter_guessed.isalpha() or len(letter_guessed) > 1:
            print(f'Invalid entry {letter_guessed}')
            print('You have been penalized and lost 2 attempts!')
            attempts -= 2


def replay_game():
    """Return True for a game replay, False otherwise."""
    valid_responses = ['y', 'yes', 'n', 'no']
    replay = input('Would you like to play another game? y/n ').lower()
    while replay not in valid_responses:
        print(f'Invalid response {replay}')
        replay = input('Would you like to play another game? y/n ').lower()
    if replay == 'y' or replay == 'yes':
        return True
    if replay == 'n' or replay == 'no':
        print('Thank you for playing Hangman.')
        print(29 * '=')
        exit(0)
        return False


if __name__ == '__main__':
    while True:
        play_game()
        replay = replay_game()
        if replay:
            attempts = 6
            play_game()
        else:
            exit(0)
import random
import string

words = [word for word in open('random_words.txt').read().split()]
attempts = 6
hangman_pics = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
========='''][::-1]


def get_current_figure():
    """Print current state of Hangman."""
    print(hangman_pics[attempts])


def play_game():
    """Play game."""
    global attempts
    available_letters = list(string.ascii_lowercase)
    letters_guessed = []
    secret_word = random.choice(words)
    slots = ['_' for _ in range(len(secret_word))]
    valid_responses = ['y', 'yes', 'n', 'no']
    print('Welcome to the hangman!')
    confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()
    while confirm_start not in valid_responses:
        print(f'Invalid response! {confirm_start}  Enter y/n')
        confirm_start = input('Would you like to start a new game?' 'y/n: ')
    if confirm_start == 'n' or confirm_start == 'no':
        print('Thank you for playing Hangman.')
        print(29 * '=')
        exit(0)
        print(f'The word to guess is {len(secret_word)} long.')
    while confirm_start == 'y' or confirm_start == 'yes':
        if not attempts:
            get_current_figure()
            print(f"You're dead, the word was {secret_word}")
            break
        check_win = 0
        for letter in secret_word:
            if letter in letters_guessed:
                check_win += 1
        if check_win == len(secret_word):
            print(f'Well done! you win.\nThe correct word is {secret_word}')
        print(45 * '=')
        get_current_figure()
        print(f"Available letters: {''.join(available_letters)}")
        print(f"Letters used: {''.join(sorted(letters_guessed))}")
        print(f'You have {attempts} attempts left.')
        print(slots, '\n')
        letter_guessed = input('Guess a letter:  ').lower()
        if letter_guessed in letters_guessed:
            print(f'You already tried that letter {letter_guessed}')
            attempts -= 1
        if letter_guessed.isalpha() and len(letter_guessed) == 1 and letter_guessed not in letters_guessed:
            available_letters.remove(letter_guessed)
            letters_guessed.append(letter_guessed)
            if letter_guessed in secret_word and len(letter_guessed) == 1:
                for index, letter in enumerate(secret_word):
                    if letter_guessed == letter:
                        slots[index] = letter
                print(f'Correct guess! {letter_guessed} is in the word.')
            if letter_guessed not in secret_word:
                attempts -= 1
                print(f'Wrong guess! {letter_guessed} not in the word.')
        if not letter_guessed.isalpha() or len(letter_guessed) > 1:
            print(f'Invalid entry {letter_guessed}')
            print('You have been penalized and lost 2 attempts!')
            attempts -= 2


def replay_game():
    """Return True for a game replay, False otherwise."""
    valid_responses = ['y', 'yes', 'n', 'no']
    replay = input('Would you like to play another game? y/n ').lower()
    while replay not in valid_responses:
        print(f'Invalid response {replay}')
        replay = input('Would you like to play another game? y/n ').lower()
    if replay == 'y' or replay == 'yes':
        return True
    if replay == 'n' or replay == 'no':
        print('Thank you for playing Hangman.')
        print(29 * '=')
        exit(0)
        return False


if __name__ == '__main__':
    while True:
        play_game()
        replay = replay_game()
        if replay:
            attempts = 6
            play_game()
        else:
            exit(0)
import random
import string

words = [word for word in open('random_words.txt').read().split()]
attempts = 6
hangman_pics = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
========='''][::-1]


def get_current_figure():
    """Print current state of Hangman."""
    print(hangman_pics[attempts])


def play_game():
    """Play game."""
    global attempts
    available_letters = list(string.ascii_lowercase)
    letters_guessed = []
    secret_word = random.choice(words)
    slots = ['_' for _ in range(len(secret_word))]
    valid_responses = ['y', 'yes', 'n', 'no']
    print('Welcome to the hangman!')
    confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()
    while confirm_start not in valid_responses:
        print(f'Invalid response! {confirm_start}  Enter y/n')
        confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()
    if confirm_start == 'n' or confirm_start == 'no':
        print('Thank you for playing Hangman.')
        print(29 * '=')
        exit(0)
    while confirm_start == 'y' or confirm_start == 'yes':
        if not attempts:
            get_current_figure()
            print(f"You're dead, the word was {secret_word}")
            break
        check_win = 0
        for letter in secret_word:
            if letter in letters_guessed:
                check_win += 1
        if check_win == len(secret_word):
            print(f'Well done! you win.\nThe correct word is {secret_word}')
        print(45 * '=')
        get_current_figure()
        print(f"Available letters: {''.join(available_letters)}")
        print(f"Letters used: {''.join(sorted(letters_guessed))}")
        print(f'You have {attempts} attempts left.')
        print(slots, '\n')
        letter_guessed = input('Guess a letter:  ').lower()
        if letter_guessed in letters_guessed:
            print(f'You already tried that letter {letter_guessed}')
            attempts -= 1
        if letter_guessed.isalpha() and len(letter_guessed) == 1 and letter_guessed not in letters_guessed:
            available_letters.remove(letter_guessed)
            letters_guessed.append(letter_guessed)
            if letter_guessed in secret_word and len(letter_guessed) == 1:
                for index, letter in enumerate(secret_word):
                    if letter_guessed == letter:
                        slots[index] = letter
                print(f'Correct guess! {letter_guessed} is in the word.')
            if letter_guessed not in secret_word:
                attempts -= 1
                print(f'Wrong guess! {letter_guessed} not in the word.')
        if not letter_guessed.isalpha() or len(letter_guessed) > 1:
            print(f'Invalid entry {letter_guessed}')
            print('You have been penalized and lost 2 attempts!')
            attempts -= 2


def replay_game():
    """Return True for a game replay, False otherwise."""
    valid_responses = ['y', 'yes', 'n', 'no']
    replay = input('Would you like to play another game? y/n ').lower()
    while replay not in valid_responses:
        print(f'Invalid response {replay}')
        replay = input('Would you like to play another game? y/n ').lower()
    if replay == 'y' or replay == 'yes':
        return True
    if replay == 'n' or replay == 'no':
        print('Thank you for playing Hangman.')
        print(29 * '=')
        exit(0)
        return False


if __name__ == '__main__':
    while True:
        play_game()
        replay = replay_game()
        if replay:
            attempts = 6
            play_game()
        else:
            exit(0)
Spelling, grammar and markdown
Source Link
Toby Speight
  • 88.3k
  • 14
  • 104
  • 327
from random_words import RandomWords
from colorama import Fore, Back, Style 
from random_words import RandomWords
from colorama import Fore, Back, Style

Assuming that someone wants to run your program, how would he run it without having this random_wordsrandom_words thing? You should include it with the rest of your code unless it's an official Python module.

I suggest you check pep0008 https://www.python.org/dev/peps/pep-0008/PEP0008, the official Python style guide.

#define function to clear the screen
def clear_screen():
    return os.system('cls')
#define function to clear the screen
def clear_screen():
    return os.system('cls')
  • Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.

     def clear_screen():
         """Clear the screen."""
         return os.system('cls')
    
  • Comments: You might want to include comments on a need basis and ommitomit the unecessary explanationsunnecessary explanations; according to PEP0008 you should use comments sparingly. lots of things are self-explanatory. And a comment starts with # comment# comment not #comment#comment.

     # import packages
     # define function to clear the screen
     # opening statement
    
  • Blank lines: (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

  • Too long lines: PEP 8 suggests lines should be limited to 79 characters.

     
  •   while game_on is True:
    

    can be expressed:

      while game_on:
    
  • Missing white space around operators: 1 space on both sides of binary operators(+ - / * // & | ^ % = > < == !=) except for function default values.

     hidden_word = ('_')*length_of_word_to_guess
     print (f'You correctly guessed the word, which is ' + Fore.GREEN + 
     f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
    

Invalid input: no catching of problematic inputs such as numbers (7 in the case above, the program indicates that I already tried 7 before). sameThe same goes for invalid inputs in the first question (do you want to start the game? y/n) - suppose a user entered yes or no instead of n or y or N or Y, then the program should indicate the invalid input or have cases covering such possible occurrences (it's not very unlikely that someone enters yes or no).

Clear screen function os.system('cls')os.system('cls') clears only windows systemon Windows systems, os.system('clear')os.system('clear') for unixUnix (mac-linuxincluding Mac and Linux) systems otherwise are going to throw some error,error; you should indicate that in the docstring or implement another function to support unixUnix systems (I have a macbook, so I had to change it to run properly).

Would you like to start a new game? infinite loop if the answer is no (n) at the very start of the game, so the user is compelled to play,play; he has no actual choice!

os.system('cls')
print ('Welcome to the Hangman!\n')
os.system('cls')
print ('Welcome to the Hangman!\n')

whyWhy use os.system('cls')os.system('cls') and you already defined a function to do so? why not ...

#Functions Python Functions. AA function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. You can enclose your code into separate functions that perform differents tasks,different tasks; it's better for readability/modularity and easier to debug/ change (what if you want to change some value that keeps repeating through the code?).

Here's a refactored version of the code: You

You will need to download this text file containing lots of wordsword list for running the code (put the file in the same folder with the script) https://drive.google.com/file/d/1am_sdLI-NCs31G-O7b-7pJKx9t5QIGqs/view?usp=sharing.

from random_words import RandomWords
from colorama import Fore, Back, Style 

Assuming that someone wants to run your program, how would he run it without having this random_words thing? You should include it with the rest of your code unless it's an official Python module.

I suggest you check pep0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide.

#define function to clear the screen
def clear_screen():
    return os.system('cls')
  • Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.

     def clear_screen():
         """Clear the screen."""
         return os.system('cls')
    
  • Comments: You might want to include comments on a need basis and ommit the unecessary explanations according to PEP0008 you should use comments sparingly. lots of things are self-explanatory. And a comment starts with # comment not #comment.

     # import packages
     # define function to clear the screen
     # opening statement
    
  • Blank lines: (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

  • Too long lines: PEP 8 suggests lines should be limited to 79 characters.

     while game_on is True:
    

    can be expressed:

     while game_on:
    
  • Missing white space around operators: 1 space on both sides of binary operators(+ - / * // & | ^ % = > < == !=) except for function default values.

     hidden_word = ('_')*length_of_word_to_guess
     print (f'You correctly guessed the word, which is ' + Fore.GREEN + 
     f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
    

Invalid input: no catching of problematic inputs such as numbers (7 in the case above, the program indicates that I already tried 7 before). same goes for invalid inputs in the first question (do you want to start the game? y/n) suppose a user entered yes or no instead of n or y or N or Y, the program should indicate the invalid input or have cases covering such possible occurrences (it's not very unlikely that someone enters yes or no)

Clear screen function os.system('cls') clears only windows system, os.system('clear') for unix (mac-linux) systems otherwise are going to throw some error, you should indicate that in the docstring or implement another function to support unix systems (I have a macbook, so I had to change it to run properly)

Would you like to start a new game? infinite loop if the answer is no (n) at the very start of the game, so the user is compelled to play, he has no actual choice!

os.system('cls')
print ('Welcome to the Hangman!\n')

why use os.system('cls') and you already defined a function to do so? why not ...

#Functions Python Functions. A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. You can enclose your code into separate functions that perform differents tasks, it's better for readability/modularity and easier to debug/ change (what if you want to change some value that keeps repeating through the code)

Here's a refactored version of the code: You will need to download this text file containing lots of words for running the code (put the file in the same folder with the script) https://drive.google.com/file/d/1am_sdLI-NCs31G-O7b-7pJKx9t5QIGqs/view?usp=sharing

from random_words import RandomWords
from colorama import Fore, Back, Style

Assuming that someone wants to run your program, how would he run it without having this random_words thing? You should include it with the rest of your code unless it's an official Python module.

I suggest you check PEP0008, the official Python style guide.

#define function to clear the screen
def clear_screen():
    return os.system('cls')
  • Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.

     def clear_screen():
         """Clear the screen."""
         return os.system('cls')
    
  • Comments: You might want to include comments on a need basis and omit the unnecessary explanations; according to PEP0008 you should use comments sparingly. lots of things are self-explanatory. And a comment starts with # comment not #comment.

     # import packages
     # define function to clear the screen
     # opening statement
    
  • Blank lines: (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

  • Too long lines: PEP 8 suggests lines should be limited to 79 characters.

     
  •   while game_on is True:
    

    can be expressed:

      while game_on:
    
  • Missing white space around operators: 1 space on both sides of binary operators(+ - / * // & | ^ % = > < == !=) except for function default values.

     hidden_word = ('_')*length_of_word_to_guess
     print (f'You correctly guessed the word, which is ' + Fore.GREEN + 
     f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
    

Invalid input: no catching of problematic inputs such as numbers (7 in the case above, the program indicates that I already tried 7 before). The same goes for invalid inputs in the first question (do you want to start the game? y/n) - suppose a user entered yes or no instead of n or y or N or Y, then the program should indicate the invalid input or have cases covering such possible occurrences (it's not very unlikely that someone enters yes or no).

Clear screen function os.system('cls') clears only on Windows systems, os.system('clear') for Unix (including Mac and Linux) systems otherwise are going to throw some error; you should indicate that in the docstring or implement another function to support Unix systems (I have a macbook, so I had to change it to run properly).

Would you like to start a new game? infinite loop if the answer is no (n) at the very start of the game, so the user is compelled to play; he has no actual choice!

os.system('cls')
print ('Welcome to the Hangman!\n')

Why use os.system('cls') and you already defined a function to do so? why not ...

#Functions A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. You can enclose your code into separate functions that perform different tasks; it's better for readability/modularity and easier to debug/ change (what if you want to change some value that keeps repeating through the code?).

Here's a refactored version of the code:

You will need to download this word list for running the code (put the file in the same folder with the script).

added 16 characters in body
Source Link
user203258
user203258
  • Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.

     def clear_screen():
         """Clear the screen."""
         return os.system('cls')
    
  • Comments: You might want to include comments on a need basis and ommit the unecessary explanations according to PEP0008 you should use comments sparingly. lots of things are self-explanatory. And a comment starts with # comment not #comment.

     # import packages
     # define function to clear the screen
     # opening statement
    
  • Blank lines: (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

  • Too long lines: PEP 8 suggests lines should be limited to 79 characters.

     while game_on is True:
    

    can be expressed:

     while game_on:
    
  • Missing white space around operators: 1 space on both sides of binary operators(+ - / * // & | ^ % = > < == !=) except for function default values.

     hidden_word = ('_')*length_of_word_to_guess
     print (f'You correctly guessed the word, which is ' + Fore.GREEN + 
     f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
    
  • Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.

     def clear_screen():
         """Clear the screen."""
         return os.system('cls')
    
  • Comments: You might want to include comments on a need basis and ommit the unecessary explanations according to PEP0008 you should use comments sparingly. lots of things are self-explanatory. And a comment starts with # comment not #comment.

     # import packages
     # define function to clear the screen
     # opening statement
    
  • Blank lines: (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

  • Too long lines: PEP 8 suggests lines should be limited to 79 characters.

     while game_on is True:
    

    can be expressed:

     while game_on:
    
  • Missing white space around operators: 1 space on both sides of binary operators(+ - / * // & |) except for function default values.

     hidden_word = ('_')*length_of_word_to_guess
     print (f'You correctly guessed the word, which is ' + Fore.GREEN + 
     f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
    
  • Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.

     def clear_screen():
         """Clear the screen."""
         return os.system('cls')
    
  • Comments: You might want to include comments on a need basis and ommit the unecessary explanations according to PEP0008 you should use comments sparingly. lots of things are self-explanatory. And a comment starts with # comment not #comment.

     # import packages
     # define function to clear the screen
     # opening statement
    
  • Blank lines: (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

  • Too long lines: PEP 8 suggests lines should be limited to 79 characters.

     while game_on is True:
    

    can be expressed:

     while game_on:
    
  • Missing white space around operators: 1 space on both sides of binary operators(+ - / * // & | ^ % = > < == !=) except for function default values.

     hidden_word = ('_')*length_of_word_to_guess
     print (f'You correctly guessed the word, which is ' + Fore.GREEN + 
     f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
    
added 328 characters in body
Source Link
user203258
user203258
Loading
fixed some issues with the code
Source Link
user203258
user203258
Loading
deleted 58 characters in body
Source Link
user203258
user203258
Loading
added a file
Source Link
user203258
user203258
Loading
Source Link
user203258
user203258
Loading