Skip to content

Instantly share code, notes, and snippets.

@sinabigo
Created November 28, 2021 04:23
Show Gist options
  • Save sinabigo/002a27d81c26c9a7fc0e5107b15d7be0 to your computer and use it in GitHub Desktop.
Save sinabigo/002a27d81c26c9a7fc0e5107b15d7be0 to your computer and use it in GitHub Desktop.
another version of the hangman game in python ## بازی ساده حدس کلمه / پایتون ## بازی پایتون
import string
import random
from words_json import words
# randomly select word from words list
# don't allow words with spaces or dashes
def get_valid_word(words):
word = random.choice(words)
while ' ' in word or '-' in word:
word = random.choice(words)
return word.upper()
def hangman():
nguess = 0
guesses = set()
abcs = set(string.ascii_uppercase)
word = get_valid_word(words)
word_set = set(word) # will remove correct guesses from this set
limit = int(input('How many guesses allowed?: ')) # limit number of guesses
# While limit not reached and word set not empty, keep guessing
while limit-nguess > 0 and len(word_set) > 0:
# show the player the word with only the correct guesses so far, along with the guessed letters so far
show_word = [letter if letter in guesses else '-' for letter in word]
print(f'The word so far: {show_word}. Letters guessed so far: {guesses}')
# ask player to guess a letter
guess = input('Guess a new letter: ').upper()
# check if guess is valid: has it been guessed yet?
while guess in guesses:
guess = input('Already guessed that - try a new letter: ').upper()
guesses.add(guess)
if guess not in word_set:
nguess += 1
else:
word_set.remove(guess)
if limit-nguess == 0:
print(f'Sorry! The word was {word}.')
else:
print(f'Awesome! You guessed it - the word was {word}.')
if __name__ == "__main__":
hangman()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment