Wednesday, January 13, 2021

Python - Project - Hangman (Day 7)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Hangman



What is hangman game? Reference.

First of all, we need to draw a flow chart to break down the requirements




Ex:
import random

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

# lives should match the stage (index)
lives = 6

# Define those words for this game
word_list = ["turtle", "giraffe", "mouse", "crocodile"]

# Show welcome message
print("Let's play HANGMAN!")

# Randomly pick a word from a defined list
chosen_word = random.choice(word_list)

# Deine a list to keep tracking the game result
display = []
for _ in range(0, len(chosen_word)):
    display.append("_")

# Show placeholder list
print(display)

# Show first stage
print(f"{stages[lives]}")

# Continue the game if users still have lives to play and
# have not guessed the word successfully
while "_" in display and lives > 0:

    guess = input("Guess a letter: ").lower()

    # Succeeded
    if guess in chosen_word:
        # Update placeholder list
        for index in range(0, len(chosen_word)):
            if chosen_word[index] == guess:
                display[index] = guess
    # Failed
    else:
        print(f"It is a wrong guess, and you lose a life")
        lives = lives - 1

    print(f"{ display }")
    print(f"{ stages[lives] }")

# Determine the result
if "_" in display:
    print("You Lose")
else:
    print("You Win")



Note



   
# Use random.randint to randomly access an element of list
chosed_word = word_list[random.randint(0, len(word_list)-1)]

# The better way
# Utilize random.choice function to randomly pick an element from a list
chosed_word = random.choice(word_list)


   
# loop for a string
for letter in chosed_word:
    print("Hi")

# Using range if the letter of a string was not used
for _ in range(len(chosed_word)):
    print("Hi")



No comments:

Post a Comment