Skip to content

Instantly share code, notes, and snippets.

@ChekeGT
Created September 11, 2023 08:13
Show Gist options
  • Save ChekeGT/6304aa221f8188adfa566e17264d1342 to your computer and use it in GitHub Desktop.
Save ChekeGT/6304aa221f8188adfa566e17264d1342 to your computer and use it in GitHub Desktop.
A hangman game made in console, for windows
import json
import json
import random
from os import system
from time import sleep
import string
# This part of code gets the data_set that we will be working with.
def clear_and_pause():
system('cls')
sleep(1)
def get_valid_words(file_name, lenght=6):
f = open(f'{file_name}')
data = json.load(f)
words = [word.upper() for word_list in data.values() for word in word_list if len(word) == lenght]
return words
def string_to_dict(s: str) -> dict:
dict = {}
for x in range(0, len(s)):
dict[f'{x}'] = s[x]
return dict
class Player(object):
def __init__(self, name, difficulty=6) -> None:
self.name = name
self.lives = 6
self.difficulty = difficulty
self.winned_games = 0
self.lost_games = 0
def play(self):
"""The hangman game works as the following.
A player has to guess a random word, but he only has 6 lives.
He will know all the words that he has used.
And will be able to see the position of each correct word.
In case he reaches to 0 lives, the hagman dies.
"""
self.lives = 6
# This set the words that are going to be used.
word = random.choice(get_valid_words(file_name='words.json',lenght=self.difficulty))
# We use dictionaries to keep track of the position of each word, this makes the game more fun by allowing words that repeat characters.
characters_dict = string_to_dict(word)
guessed_characters = {}
# At the end the guessed_characters should be the same as the characters of the word, we transform them into list and sort them to compare correctly if they have the same characters.
while sorted(list(guessed_characters.keys())) != sorted(list(characters_dict.keys())) and self.lives > 0:
# We obtain the hint by analyzing each of the letters that the user has guessed and its position,
# on this way we do not give him two hints for the price of 1.
# So if we have ANA and the user has only guessed one A The hint will look like A-- or --A
hint = [characters_dict[f'{k}'] if (k in guessed_characters.keys()) else "-" for k in characters_dict.keys()]
print(f'These are the words you have guessed: {hint}')
# Here we ask the user for input, and validate it is correct. A.K.A it should be on the alphabet and have only one character
guess = input('Guess a word:').upper()
if guess not in string.ascii_uppercase or len(guess) >= 2:
print('You have not introduced a valid input, please do so again.')
# This is what happens if the character that user has gave us is in the word.
if guess in characters_dict.values() and list(guessed_characters.values()).count(guess) < word.count(guess):
# This variable works for two things, provide a sense of randomness to the position of the word
# F.E: The hint on this way will be for the word ANA A-- or --A
# And also this works only if the character repeats itself in the word
guess_indexes = [index for index in characters_dict.keys() if characters_dict[f'{index}'] == guess]
random.shuffle(guess_indexes)
# If in fact, the word repeats a character two or more times and all characters are not guessed
if len(guess_indexes) >= 2:
# We will review if it is already on our dictionary or otherwise
for index in guess_indexes:
if index in guessed_characters.keys():
continue
#We will place it on our dictionary
else:
guessed_characters[f'{index}'] = guess
break
# If the word only presents a certain character once, we will simply add it to the dictionary
else:
guessed_characters[f'{word.index(guess)}'] = guess
# If the player fails, we will make him lose 1 life.
else:
self.lives -= 1
print(f'You have not guessed right, you have {self.lives} lives now ):')
clear_and_pause()
if self.lives > 0:
print(f'You have won, and you did so with {self.lives} lives while guessing the word {word}')
print(f'Congrats, your score is: {self.games_winned}!!')
else:
print(f'You have lost, thats sad, with this one it is a total of: {self.lost_games} games lost.')
def create_player():
clear_and_pause()
name = input("What's your name:")
difficulty = int(input("How difficult would you like the game to be(How long will the word be, on characters):"))
return Player(name, difficulty=difficulty)
def menu():
print('Welcome to the hangman game. Have fun!!')
sleep(1)
player = create_player()
while True:
option = input('1)Play\n2)Exit\n')
if option == '1':
clear_and_pause()
player.play()
elif option == '2':
clear_and_pause()
print('Thanks for playing the game, have a nice day.')
break
else:
print('You have not used a correct option, please do so.')
menu()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment