TIL: Python Basics Day 7 - Hangman Game

이다연·2020년 11월 28일
0

Udemy Python Course

목록 보기
7/64

Recap day
Project: Hangman
Flow chart Programming

Hangman step 2

range(len(word)) : if length was 5 , 0,1,2,3,4
range(1, 3) : 1,2 -> not including 3

TODO-2: I made an empty list 'display =[ ]' repeatedly to fill in the data using '+=' to add the new letters, however, angela simply exchanged word only when it meets the condition. She used 'display[position] = letter' to exchange the letter.

#Step 2

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#TODO-1: - Create an empty List called display.
#For each letter in the chosen_word, add a "_" to 'display'.
#So if the chosen_word was "apple", display should be ["_", "_", "_", "_", "_"] with 5 "_" representing each letter to guess.

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

display = []
for letter in chosen_word:
  display += "_"

print(display)

#TODO-2: - Loop through each position in the chosen_word;
#If the letter at that position matches 'guess' then reveal that letter in the display at that position.
#e.g. If the user guessed "p" and the chosen word was "apple", then display should be ["_", "p", "p", "_", "_"].

#<my code>
display = []
for i in range(len(chosen_word)):
  if chosen_word[i] == guess:
    display += chosen_word[i]
  else:
    display += "_"
    
#<Angela's code>  
word_length = len(chosen_word)
for position in range(word_length):
    letter = chosen_word[position]
    if letter == guess:
        display[position] = letter


#TODO-3: - Print 'display' and you should see the guessed letter in the correct position and every other letter replace with "_".
#Hint - Don't worry about getting the user to guess the next letter. We'll tackle that in step 3.
print(display)

Hangman step3

  • Logic was confusing. Angela's code used one more variable called "end_of_game" on top of 'not in' logic for readability.
  • Indentation was extra important. At first, print part was skipped in my code because I didn't indent it.
  • "while not False" means "While True" it goes into infinite loop, without the line (if "_" not in display:) underneath, it won't end.
#Step 3

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
    display += "_"

#TODO-1: - Use a while loop to let the user guess again. The loop should only stop once the user has guessed all the letters in the chosen_word and 'display' has no more blanks ("_"). Then you can tell the user they've won.

#<my code>
while '_' in display:

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

#Check guessed letter
  for position in range(word_length):
    letter = chosen_word[position]
    if letter == guess:
        display[position] = letter

    print(display)

  if not '_' in display:
    print("win")


#<angela's code>
end_of_game = False

while not end_of_game:

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

#Check guessed letter
  for position in range(word_length):
    letter = chosen_word[position]
   
    if letter == guess:
        display[position] = letter
    print(display)

  if "_" not in display:
    end_of_game = True
    print("you win.")

Hangman step 4

Multiple ifs, indentation was very confusing. I first wrote 'else:' under the for loop of #TODO2 and it didn't work. I had to try different code a few times.

#Step 4

import random

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

end_of_game = False
word_list = ["ardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
lives = 6

#TODO-1: - Create a variable called 'lives' to keep track of the number of lives left. 
#Set 'lives' to equal 6.

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
    display += "_"

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

    #Check guessed letter
    for position in range(word_length):
        letter = chosen_word[position]
        print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
        if letter == guess:
            display[position] = letter

    #TODO-2: - If guess is not a letter in the chosen_word,
    #Then reduce 'lives' by 1. 
    #If lives goes down to 0 then the game should stop and it should print "You lose."
    
    if guess not in chosen_word:
      lives -= 1
     
      if lives == 0:
        end_of_game = True
        print("You lose.")
        
    #Join all the elements in the list and turn it into a String.
    print(f"{' '.join(display)}")

    #Check if user has got all letters.
    
    if "_" not in display:
        end_of_game = True
        print("You win.")

    #TODO-3: - print the ASCII art from 'stages' that corresponds to the current number of 'lives' the user has remaining.
    
    print(stages[lives]) 

Hangman stage 5

It's important to add full functionality in the end after getting everything right. In this case, importing Ascii (design), word_list from different files and improving user experience by gently nudging them with hints.

  • Module:
    from hangman_art import logo, stages - > you can import multiple things in one line, at once.

Final Result:
https://repl.it/@daylee/Day-7-Hangman-5-Start#main.py

profile
Dayeon Lee | Django & Python Web Developer

3개의 댓글

comment-user-thumbnail
2023년 6월 22일

Thanks for the tutorial, I love these games! Basically, I like everything related to the gaming industry.

답글 달기
comment-user-thumbnail
2023년 6월 22일

I also like simple games and excitement. It is very difficult to find something interesting now, there is a lot of choice. Gambling is a great leisure option. And now I found this site https://crypto-gambling.tv/de/casino/ , where there are some of the best crypto casinos with cool bonuses, as well as pleasant conditions for players. Cryptocasino seems like an interesting idea to me.

답글 달기
comment-user-thumbnail
2023년 7월 19일

Thank you for the tutorial - top work. If you're interested in cryptocurrencies, check out the best Bitcoin sportsbooks and have a blast - https://www.doublethebitcoin.net/crypto-sportsbetting/

답글 달기