Create a simple text-based adventure game. The user should be able to navigate between different rooms and collect points based on their choices.
This is the final code. Documentation of the code is written below.
import math
# Create a variable for the number of lives
score_count = 1
# Create a variable for current room.
current_room = "Start_room"
#Create intoduction and instruction text
print("Welcome to the Maze Room. You are stuck in rooms filled with Zombies.")
print("There's only one way out. Can you figure out that pattern?")
print("Valid moves. Type: 'left', 'right', 'down', 'up'")
print("You only have 3 moves. Cannot go back to the former room.")
print("Find the pattern. Goodluck!")
# Define the maze layout using dictionary
maze = {
"Start_room": {"left" : "Medicine Room 1", "right" : "Zombie Room 1", "up" : "Zombie Room", "down" : "Zombie Room"},
"Medicine Room 1": {"left" : "Zombie Room", "right" : "Zombie Room", "up" : "Zombie Room", "down" : "Medicine Room 2"},
"Medicine Room 2": {"left" : "Zombie Room", "right" : "Zombie Room", "up" : "Zombie Room", "down" : "Goal"},
"Goal": None
}
# Create a function with the variable to count points.
def add_point():
global score_count
score_count += 1
print(f'+1 point, score:{score_count}')
def minus_point():
global score_count
score_count -= 1
print(f'-1 point, score:{score_count}')
# Create while loop to play the game
while True:
# Display current room
print(f'Current room: {current_room}')
# Get user input for direction
direction = input("Type your move: 'left', 'right', 'up', 'down'>>>")
# Validate input
if direction not in ["left", "right", "up", "down"]:
print("Invalid move. Try again")
continue
# Check if the player has run out of lives
if score_count <= 0:
print("Game over!")
break
# Update current room based on user input
if direction in maze[current_room]:
current_room = maze[current_room][direction]
else:
print("Invalid move. Try again")
continue
# Check conditions for different rooms
if current_room == "Zombie Room" or current_room == "Zombie Room 1":
minus_point()
print("Minus 1 life")
elif current_room == "Medicine Room 1" or current_room == "Medicine Room 2":
add_point()
print("You're still alive!")
elif current_room is None:
print("Take another direction.")
elif current_room == "Goal":
print("You won!")
break
Plan the logic of the game.
This is a pattern maze game with a score counter per room, where every time a player enters a room, 1 life point can be added or deducted depending on the room. The game is won when the maze goal is reached. The player has 3 movements. If the life point = 0, the player loses. The player must reach the goal. There is only 1 pattern to win: left - down - down.
I looked for sources and tips online on how to create the idea of the game. The diagram is the logic. The idea is the player must be able to navigate through the rooms with “left, right, up and down” directions. I decided to create rooms using dictionaries because I understand it the most.
Source: Python - creating a building map with a dictionary - Stack Overflow
Step 1: Create variables to keep track of the player's score and current room.
The choice of module is math because the game will perform mathematical calculations for adding and subtracting scores using increments of +=1 and -=1.
To begin, create a variable for the score. The value (game point) starts with 1. because it is the number of life points of the player. It is important to note that score_count is a global variable because it is declared outside any def function code block. This is why it’s important to create global variables in the beginning of the code as well.
Also, this is necessary because when the score_count variable is being referenced later in the def functions, it will tell Python to update the overall score of the game and increment of +=1 or -=1 to the score_count variable. Thus, it results in addition or subtraction of points.
Create a variable for the current room and name it as “current_room.” The starting position is the “Start_room” where the player's starting position is. Later, current_room will be used to update the player’s position.
Step 2: Create an introduction and instruction text.
Step 3: Define the maze layout
Using dictionaries, the maze layout is made by using key-pair values. In the past, I have studied the relationship between dictionaries and key-pair values before. So, when I saw this code, I understood how it could work. This will be very useful in the if-elif statements inside the while-loop.
Dictionaries are a collection that allows storing data in key-value pairs. Create by placing key: value pairs inside curly brackets {} separated by commas.
Create the maze dictionary to represent the layout of the rooms in the zombie game. Each room is a key. The values are the possible directions the player can use.
Step 4: Create def functions to tell Python either to add or subtract points in a specific room.
Make two defined functions for adding and subtracting points into the score_count variable. Putting these specific actions assigned to a def function might also be easier to modify later for errors.
First, create a function called add_point(): Under this function, make a code block by intention of 4 spaces. Remember to assign which variable to increment +=1.
It means score_count = score_count +1. Print “+1 point, score” and use an f-string to modify the score_count variable for every update.
Second, create a function called minus_point() in the same context as add_point. The only difference is that it subtracts -1 to the point.
Step 5: Use a while loop that runs until the player has reached the goal or chosen to quit.
Create the while-loop statement.
While-loop repeats a block of code in an infinite number of occurrences until a certain condition is met. The condition could be True or False. In this game, use the while True: condition.
My Old Code Before Debugging:
direction = input and current_room variable -these two variables have a problem. INSIDE the while-loop, the direction variable is there but not the current_room variable.
Change to: Put the dictionary maze inside the while-loop. Current room will be updated based on the value of the maze and directions (user input is here).
The current_room is still not updating. I need help from ChatGpt.
According to ChatGpt, since the code is using the dictionary, the fix was to use maze as the value and current_room as the key.
maze[current_room] takes the value from the dictionary. It represents other rooms.
Change to: Let’s try that modification in the current_room.
Output:
“UnboundLocalError: cannot access local variable ‘score_count’ where it is NOT associated with a value.”
It is weird because I placed ‘score_count’ OUTSIDE the def function so it becomes a global variable. But here, the error still says that it is a LOCAL VARIABLE.
So the ‘score_count’ needs to be converted to a global variable somewhere in the def function.
Ask Google how to fix UnboundLocalError. How to change local to global variables.
Source: https://www.w3schools.com/python/python_variables_global.asp
Back to the def functions, declare ‘score_count’ as a global variable.
Final Changes to the code:
current_room
The current_room will be updated every time a move is typed. This is the first sentence that is printed in the while-loop. It is the display of the current room.
direction
Within the while True: code block, create a value called direction as the storage for the user input. This prompts the user to enter a move. Use the direction variable to determine the player’s move and proceed with the game logic from that input.
Output
Step 6: Use if statements inside the while loop to let the user make choices depending on which room they are in.
Before debugging, these are the old codes #1:
Use the if statement to create a condition.
If the score_count <= 0:, it means the player has run out of lives. “Game Over” is printed and the game will break. The break statement will exit the loop immediately.
Else statement
When other strings are typed other than “left, right, up and down”, the else statement will be executed.
After debugging code #1:
Change from Else statement to if, not in[list].
The code before debugging did not work. So, it is changed to 2 if statements and placed in the beginning of the while -loop. Use the if direction not in [“left”, “right”, “up”, “down”]: if statement. A statement is printed instead of using the else statement for invalid inputs. Then, it tells the program to continue looping. If the score_count becomes equal to or less than 0, the game breaks.
I can’t fix the code to update the current_room. Help from ChatGPT.
This code is not originally mine. I could not figure out how to update the variable current_room. The program crashes after the player’s second answer.
To explain how this code works:
if direction in maze[current_room]:
checks the user’s input from the maze dictionary. It checks if the move in the [current_room] is valid. Closed in square brackets because it’s a dictionary.
current_room = maze[current_room][direction]
If the if direction in maze[current_room]: is valid, it updates the current_room variable.
else:
\= if the statement is False, print(“Invalid”).
continue
Skips the code and starts the loop again. If the user enters an invalid input, the code will not break or print an error. It will prompt the user for a new valid input.
Old Code #2
Condition: Use the elif statement to create the other conditions of losing.
Using the current_room variable as the player’s place.
If current room == “Zombie Room”: the function minus_point will be executed.
“Minus 1 life” will be printed to tell the player.
New code #2
Make the code shorter and simpler by using the logical operator "or".
Old Code #3
Condition: Use the elif statement to create the other conditions of winning.
Using the current_room variable as the player’s place.
If current room == “Medicine Room”: the function add_point will be executed.
“You’re still alive!” will be printed to tell the player.
The loop will continue executing.
New Code #3
Make the code shorter and simpler by using the logical operator or.
Old Code #4
Condition: Use elif statement for None.
The player may decide to go back to the same Medicine Room which can give extra points. So, the “None” is made to not give extra points from the same Medicine Room.
New code #4
I learned that == None: and is None: gives the code completely different results. This change helps stop the errors.
\== is a comparison operator used for equality comparison.
is None is a keyword used to object identity. It is also recommended to use None to check if the variable is the same identity.
Condition: Use an elif statement to create the “Goal” of the game.
The game will print “You won!” once the player’s current room position is equivalent to the “Goal”. Then, the game will break and jump out of the loop.