2️⃣

1.2 - Example

Example

As an example of a simple game, let’s start with guess the password! The directions for this assignment are to create a game where the user has to guess a certain password that you will set, and see how many tries it takes for the user to guess it correctly.
``````# Directions: The goal of this exercise is to create
# a game where the user has to guess a certain password that
# you set and see how many tries it takes for that user to guess correctly

# set an input so it will appear in the console and ask the user
guess = input("Enter the password: ")

# set a counter to count the number of guesses
counter = 1

# set a while loop to check if the user guess correctly and count the number of guesses
while guess != pas:
guess = input("Incorrect Password. Try Again:")
counter += 1

# print the results
print(f"Nice Job. Unlocked. It took you {counter} tries")``````
View code on GitHub

Code Breakdown

Here's how this simple game follows the simple game loop that we defined in the last section.
• Line 9 - Handles events by getting user input.
• Line 15 - Updates game state; if `guess` is equal to the password, then stop running; if `guess` isn't, then keep running.
• Line 16 - Updates the display by telling the user that they got the wrong message and handles events by getting a new user input/guess.

Hangman

For another easy game, let’s code the hangman game! Code the game so that the user will play with the console to figure the secret word. If the player runs out of lives, reveal the word.
Note: Make sure to implement the game loop concept from the previous section (
1️⃣
1.1 - The Game Loop
).
``````# Directions: Lets Play Hangman. In the code, create a function that
# takes as a paramater the word that the user has to guess.
# The user should have 15 'lives'.
# Similar to the original game of hangman, if the user guesses an incorrect
# letter, then their lives goes down. If they guess a correct letter, they
# don't lose a life.

score = 0

def hangman(endword: str):
global score
wordSet = set(endword)
print(
"Welcome to Hangman! You have 15 lives to "
+ "figure out the correct word. Good Luck!"
)

lives = 15
correctguesses = []

# mainloop
for i in range(15):
# take user input
guess = input(f"Guess a letter! You have {lives} lives left: ")

# win condition
if guess == endword:
print(f"Nice, the word is '{endword}'")
score += 1
break

if guess in endword:
correctguesses.append(guess)

# 'draw screen' phase
for i in range(len(endword)):
if endword[i] in correctguesses:
print(endword[i], end="")
else:
print("_ ", end="")
print()

if guess not in wordSet:
lives -= 1

# update game state
# game over condition
if lives == 0:
print(f"You ran out of lives. The correct word is '{endword}'")

# win condition
if set(correctguesses) == wordSet:
print(f"Nice, the word is '{endword}'")
score += 1
break

hangman("hangman")``````
View code on GitHub

Previous Section

1️⃣
1.1 - The Game Loop

3️⃣
1.3 - Practice

⚖️