From 4a9952d05a7e61390eac4b8a97cc24e739a6177d Mon Sep 17 00:00:00 2001 From: Naman Verma Date: Mon, 28 Oct 2024 23:33:09 +0530 Subject: [PATCH] Implemented Hangman game in Python. Working process/flow: - Word Selection: A random word is chosen from a list of words. - Game Loop: 1. The player is shown their remaining lives and used letters. 2. The current state of the word is displayed, with guessed letters shown and unguessed letters as underscores. 3. The player guesses a letter. 4. If the letter is correct, it's removed from the word's letter set. 5. If the letter is incorrect, the player loses a life. - Win/Lose Condition: 1. If all letters are guessed, the player wins. 2. If the player runs out of lives, they lose. --- hangman_game.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 hangman_game.py diff --git a/hangman_game.py b/hangman_game.py new file mode 100644 index 0000000..7dead02 --- /dev/null +++ b/hangman_game.py @@ -0,0 +1,41 @@ +import random + +def hangman(): + word_list = ["python", "java", "javascript", "c++", "ruby"] + chosen_word = random.choice(word_list) + word_letters = set(chosen_word) + alphabet = set('abcdefghijklmnopqrstuvwxyz') + used_letters = set() + + lives = 6 + + while len(word_letters) > 0 and lives > 0: + print('Lives remaining:', lives) + print('Used letters:', ' '.join(used_letters)) + + print('\nCurrent word:') + for letter in chosen_word: + if letter in used_letters: + print(letter, end=' ') + else: + print('_', end=' ') + print() + + user_letter = input('Guess a letter: ').lower() + if user_letter in alphabet - used_letters: + used_letters.add(user_letter) + if user_letter in word_letters: + word_letters.remove(user_letter) + else: + lives -= 1 + elif user_letter in used_letters: + print('You already used that letter. Guess again.') + else: + print('Invalid character. Please try again.') + + if lives == 0: + print('You died, sorry. The word was', chosen_word) + else: + print('You guessed the word', chosen_word, '!') + +hangman() \ No newline at end of file