Python Hangman Program Error

Hello this is Gulshan Negi
Well, I am writing a program for making Hangman Game in Python but it shows some error at the time of execution, I don’t know what wrong I am doing here.

Here is my source code:

import random
import time
import os

def play_again():
question = ‘Do You want to play again? y = yes, n = no \n’
play_game = input(question)
while play_game.lower() not in [‘y’, ‘n’]:
play_game = input(question)

if play_game.lower() == ‘y’:
return True
else:
return False

def hangman(word):
display = ‘_’ * len(word)
count = 0
limit = 5
letters = list(word)
guessed =
while count < limit:
guess = input(f’Hangman Word: {display} Enter your guess: \n’).strip()
while len(guess) == 0 or len(guess) > 1:
print(‘Invalid input. Enter a single letter\n’)
guess = input(
f’Hangman Word: {display} Enter your guess: \n’).strip()

  if guess in guessed:
      print('Oops! You already tried that guess, try again!\n')
      continue

  if guess in letters:
      letters.remove(guess)
      index = word.find(guess)
      display = display[:index] + guess + display[index + 1:]

  else:
      guessed.append(guess)
      count += 1
      if count == 1:
          time.sleep(1)
          print('   _____ \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '__|__\n')
          print(f'Wrong guess: {limit - count} guesses remaining\n')

      elif count == 2:
          time.sleep(1)
          print('   _____ \n'
                '  |     | \n'
                '  |     | \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '__|__\n')
          print(f'Wrong guess: {limit - count} guesses remaining\n')

      elif count == 3:
          time.sleep(1)
          print('   _____ \n'
                '  |     | \n'
                '  |     | \n'
                '  |     | \n'
                '  |      \n'
                '  |      \n'
                '  |      \n'
                '__|__\n')
          print(f'Wrong guess: {limit - count} guesses remaining\n')

      elif count == 4:
          time.sleep(1)
          print('   _____ \n'
                '  |     | \n'
                '  |     | \n'
                '  |     | \n'
                '  |     O \n'
                '  |      \n'
                '  |      \n'
                '__|__\n')
          print(f'Wrong guess: {limit - count} guesses remaining\n')

      elif count == 5:
          time.sleep(1)
          print('   _____ \n'
                '  |     | \n'
                '  |     | \n'
                '  |     | \n'
                '  |     O \n'
                '  |    /|\ \n'
                '  |    / \ \n'
                '__|__\n')
          print('Wrong guess. You\'ve been hanged!!!\n')
          print(f'The word was: {word}')

  if display == word:
      print(f'Congrats! You have guessed the word \'{word}\' correctly!')
      break

def play_hangman():
print(‘\nWelcome to Hangman\n’)
name = input('Enter your name: ‘)
print(f’Hello {name}! Best of Luck!’)
time.sleep(1)
print(‘The game is about to start!\nLet's play Hangman!’)
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)

words_to_guess = [
‘january’, ‘border’, ‘image’, ‘film’, ‘promise’, ‘kids’,
‘lungs’, ‘doll’, ‘rhyme’, ‘damage’, ‘plants’, ‘hello’, ‘world’
]
play = True:
while play:
word = random.choice(words_to_guess)
hangman(word)
play = play_again()

print(‘Thanks For Playing! We expect you back again!’)
exit()

if name == ‘main’:
play_hangman()

Well, I also checked and took a reference from [here] (30 Cool, Easy & Fun Python Projects with Source Code [2023]), but I don’t know what I am missing in coding. Can anyone give their suggestions on this?
Thanks

Could you show the errors you are getting please?

1 Like

Thanks a lot for your kind response. Well, there is a syntax error as it is showing below error.

SyntaxError: invalid character in identifier

Thanks

SyntaxError: invalid character ‘‘’ (U+2018)

You are mixing many different types of quotes in your code. ’ and ’
I would make them all uniform, just ’

Screenshot 2023-05-07 075026
Screenshot 2023-05-07 075003

In these screenshots you can also see that the line:
print(f’Congrats! You have guessed the word '{word}' correctly!')
is breaking the syntax highlighting in Replit.

1 Like

Screenshot 2023-05-07 075521
Screenshot 2023-05-07 075455
Screenshot 2023-05-07 075333

1 Like

Thanks for your kind support and response.

I don’t know your skill level in python but, I would recommend learning to use classes. It will make your programming a little easier. I took the opportunity too start a hangman game with classes. It is by no means complete but should give you a start.

# Do the imports
from random import choice
import os
import requests

# Function for clearing the terminal
def clear():
    os.system('cls' if os.name == 'nt' else 'clear')


class Model:
    '''
        The Model class will handle all the words, word list and searches
        We compile a word list from the url below
    '''
    url = 'https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt'
    response = requests.get(url)
    words = response.text.split('\r\n')

    def __init__(self):
        ''' Intialize the word list '''
        self.wordlist = Model.words        

    def random_word(self):
        ''' Get a random word from the list '''
        word = choice(self.wordlist)
        self.wordlist.remove(word)
        return word
    
    def find(self, letter, word, letters):
        ''' 
            Search the word for entered letter. If one is found insert into our letters symbol (-)
            and return the list
            If one is not found return False    
        '''
        match = [i for i, x in enumerate(word) if x == letter]
        letters = [letter for letter in letters]
        if match:
            for i in match:
                letters[i] = letter
                Stats.remaining -= 1
            return ''.join(letters)
        return False
       

class View:
    ''' The only thing out View class does is return the data for displaying'''
    def __init__(self):
        pass

    def display(self, data):
        return data
    

class Stats:
    '''
        The Stats class keeps track of player stats
    '''
    player = ''
    wins = 0
    loss = 0
    tries = 5
    remaining = 0

    def __str__(self):
        return f'Player: {Stats.player.title()} / Wins: {Stats.wins} / Loss: {Stats.loss} / Tries Left: {Stats.tries} / Letters Left: {Stats.remaining}'
    

class Controller:
    '''
        The Controller class handles all the communication between classes
    '''
    def __init__(self, model, view):
        self.model = model
        self.view = view
        self.word = self.model.random_word()
        self.letters = '-'*len(self.word)
        Stats.remaining = len(self.word)

    def new_game(self):
        ''' Reset everything for a new game '''
        self.word = self.model.random_word()
        self.letters = '-'*len(self.word)
        Stats.wins = 0
        Stats.loss = 0
        Stats.tries = 5
        Stats.remaining = len(self.word)


if __name__ == '__main__':
    controller = Controller(Model(), View())
    Stats.player = input('Enter your name (Leave empty for default): ') or 'Player'

    while True:
        print(f'{controller.view.display(Stats())}\n')
        print(f'{controller.view.display(controller.letters)}\n')
        ask = input('Enter a letter:\n>> ').lower()

        if ask.strip() == '' or ask.isdigit() or len(ask) > 1:
            print('Please enter a single letter only...')
            continue

        if ask:
            letters = controller.model.find(ask, controller.word, controller.letters)

            if letters:
                controller.letters = letters
            else:
                Stats.tries -= 1          
        
        if Stats.remaining == 0 or Stats.tries == 0:
            print(f'{controller.view.display(Stats())}\n')
            play_again = input('Play Again? (y/n)\n>> ').lower()

            if play_again[0] == 'y':
                controller.new_game()
            else:
                print('Goodbye!')
                break

Ok, and thanks a lot for being always there for kind support.
Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.