pyhang_game
Table of Contents
Pyhang Game
- Basic Hangman clone in Python
- List Example I
- Hangman
Hangman Game v1
The following game illustrates the use of lists. It is one way to do the game.
import random def play(self): # List of words to choose from words = [ 'apple', 'banana', 'pig', 'going' ] guesses = [] chances = 7 tries = 0 # Pick a random word word = random.choice(common_nouns) gameword = [ '_' ] * len(word) # This is our game loop. while tries < chances: print("") print("=====") print(" ".join(gameword)) print("") # Ask the player to guess a letter. print("Guesses: " + "".join(guesses)) print("Tries left: ", chances-tries) guess = input("Please guess a letter: ") # Did we already guess this letter? if guess not in guesses: guesses.append(guess) guesses.sort() if guess in word: for i in range(len(word)): if word[i] == guess: gameword[i] = guess else: tries = tries + 1 # Check if the word has been completely guessed if '_' not in gameword: print("Congratulations! You've guessed the word: " + word) break if tries >= chances: print("You've run out of attempts. The word was: " + word)
Initially, you can just use print(gameword) instead of a more complex way of printing the game word. Later you can introduce .join() and explain what it does. Also, after the testing stage you can add more words.
Version 2
I taught another course to older kids and came up with a more straightforward way:
import random wordlist = [ "Dog", "Cat", "Bird", "Fish", "Elephant", "Tiger", "Lion", "Monkey", "Bear", "Horse", "Cow", "Chicken", "Pig", "Sheep", "Goat", "Duck", "Apple", "Banana", "Orange", "Grape", "Strawberry", "Bread", "Cheese", "Butter", "Milk", "Egg", "Rice", "Pasta", "Meat", "Chicken", "Beef", "Pork", "Fish", "Shrimp", "Salad", "Soup", "Sandwich", "Jacket", "Shirt", "Pants", "Dress", "Skirt", "Shorts", "Hat", "Shoes", "Socks", "Gloves", "Scarf", "Belt", "Coat" ] gameword = random.choice(wordlist) gameword = gameword.lower() guessed = "" badguess = "" playing = True check = "" chances = 7 round = 1 while playing: print("") print(f"Bad guesses: {badguess}") print(f"Guesses remaining: {chances}!") for letter in gameword: if letter in guessed: print(letter, end = ' ') else: print('_', end = ' ') print("") # skip one line guess = input("Choose a letter: ") guess = guess.lower() if guess in gameword: print("Good guess!") guessed = guessed + guess else: print("Bad guess!") badguess = badguess + guess chances = chances - 1 # Check to see if we need to keep guessing playing = False for letter in gameword: if letter not in guessed: playing = True # End the game if we run out of chances if chances <= 0: playing = False
This version began with a wordlist and random.choice. Then we made a guess-check algorithm. Then we replaced the print statement with the one that prints _'s. Then we made the game loop. Then we added checks for chances and completion.
pyhang_game.txt · Last modified: 2024/07/29 00:06 by appledog