pyhang_game
This is an old revision of the document!
Pyhang Game
- Basic Hangman clone in Python
- List Example I
- Hangman
Hangman Game
The following game illustrates the use of lists.
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.
pyhang_game.1699232833.txt.gz · Last modified: 2023/11/06 01:07 by appledog
