🔓 Prison Escape
✍️ Coded line by line by Mr.Peak 💛 · See full profile and all works →
📖 What is this project?
Prison Escape คือเกมผจญภัยแบบเลือกทางเดิน (Text Adventure) ที่มีความยาวระดับเกมจริง — เนื้อเรื่องเริ่มจากตัวเราติดคุกเพราะขโมยนม 1 ขวด ต้องหาทางแหกคุกออกไปเอานมกลับบ้าน มีสถานที่มากกว่า 20 ฉาก ตั้งแต่ห้องขัง โรงอาหาร ลานกลางแจ้ง ไปจนถึงคูน้ำ ป่า กระท่อมลึกลับ ดินแดนซอมบี้ และพระราชวังโบราณ
จุดเด่นคือระบบไอเทมที่ต้องใช้ให้ถูกที่ (คลิปหนีบกระดาษงัดล็อกห้องขัง ตะไบตัดลูกกรงหน้าต่าง ดาบสู้ซอมบี้ นาฬิกาไขปริศนา) ระบบพูดคุยกับ NPC 3 คนที่แตกบทสนทนาได้หลายทาง และระบบเสี่ยงดวงตอนติดสินบนยาม — พลาดคือจบเกมทันที มีหลายตอนจบทั้งชนะ ถูกประหาร และโดนซอมบี้
ในแง่โค้ด นี่คือโปรเจ็คระดับแยกไฟล์เป็น 6 โมดูลพร้อม docstring อธิบายทุกฟังก์ชัน และมีคอมเมนต์วางแผนเวอร์ชันถัดไป (v0.5.6) เขียนไว้ในไฟล์ — เป็นวิธีทำงานแบบนักพัฒนามืออาชีพจริง ๆ
🕹️ Try the real thing!
This is the real program, converted to run on the web with every rule kept exactly the same — type your answer and press Enter, just like running it in Python.
👨💻 The original Python source code (with the comments they wrote themselves)
This project is split into 6 files — tap a heading to open each one.
main.py (135 lines)
from dialogue import dialogue, Colors, WON, LOSE
from locations import *
from items import (
itemLocations,
handle_item_usage,
ItemFails,
Items,
interact_with_item,
)
from utils import attempt_bribe
import time
# ============================================================================================
"""
FOR FUTURE UPDATES v0.5.6
>> Make the system of dialog better as some msgs are too long to print in one line ✅
> Maybe use a list or some sort of data structure and rework the way dialogues are displayed. ✅
>> Add more to the storyline and make it more engaging to the player.
>> Change the colors of the text based on the current state of the dialog.
{Current state of game is funcitonal and has an end. Item system is updated with a more eiffcent struture.})
"""
# ============================================================================================
def handle_new_event(new_location):
"""
Handles events based on the player's new location.
Args:
- new_location (str): The new location the player moves to.
Returns:
- str: The description of the event or location after handling.
"""
global current_location
if new_location in locations:
return locations[new_location] # Return location description
elif new_location in inmates:
inmate_interaction(new_location) # Handle interaction with inmates
current_location = "Cafeteria"
return locations[current_location] # Return cafeteria description
elif new_location in Items:
current_location = interact_with_item(new_location)
return locations[current_location] # Return new location description
def item_handler(current_locale):
global current_location
# Check if current location is applicable for using items and if it is not yet unlocked (status)
if current_locale in itemLocations and itemLocations[current_locale] != "Unlocked":
current_locale = handle_item_usage(current_locale)
# If there is Death or Freedom we return main loop.
if current_locale in ["Freedom", "Death"]:
return
elif current_locale in itemLocations:
dialogue(locations[current_locale])
item_handler(current_locale)
# Check if instance is tuple either (nullItem, location) or (location, "yes/no_items")
elif isinstance(current_locale, tuple):
# Incase it Death comes from not having an item like (Death, "yes/no_items")
if (
current_locale[0] in ["Freedom", "Death"]
or current_locale[-1] == "success"
):
current_location = current_locale[0]
# Case where item is not usable in current location or no items used get [0] from (locale, "yes/no_item") and return to main loop
elif current_locale[-1] in ("yes_items", "no_items"):
current_location = current_locale[0]
dialogue(locations[current_location])
# Case where no items display fail_msg and call return to main loop
elif current_locale[0] == "nullItem":
failDesc = ItemFails[current_locale[-1]]["Fail_Desc"]
dialogue(failDesc)
current_location = ItemFails[current_locale[-1]]["Prev_Location"]
else:
current_location = current_locale
return
def GateCases():
global current_location
if current_location == "Gate":
current_location = perform_action(current_location)
if current_location == "bribe":
current_location = attempt_bribe()
elif current_location == "Death":
dialogue("You really think that would work?", Colors.RED)
dialogue("Violence doesn't solve sh*t...", Colors.RED)
else:
dialogue(locations[current_location])
# Initial player location
current_location = "Cell"
# Game introduction and initial location
dialogue(
"You stole a bottle of milk. The cops then arrested you. You're in jail.",
Colors.CYAN,
)
dialogue(
"Your goal is to escape jail, to bring the milk back home to your long lost son 17 years ago...",
Colors.CYAN,
)
dialogue(locations[current_location], Colors.LIGHT_PURPLE)
# Main game loop
while True:
dialogue(f"[current_location]: {current_location}") # (Debugger 3/7/24)
time.sleep(0.2)
current_location = perform_action(current_location)
event_result = handle_new_event(current_location)
dialogue(event_result)
GateCases() # Handle Gate scenarios
item_handler(current_location) # Handle items
if current_location == "Freedom":
WON()
break
elif current_location == "Death":
LOSE()
break
dialogue("Game Over.", Colors.WHITE)
locations.py (181 lines)
from dialogue import dialogue, ask, Colors
from inmates import inmates, inmate_interaction
"""================================ Locations/Actions DATABASE ================================"""
# Define locations within jail
locations = {
"Cell": "You are in your prison cell. There's a bed, a small window, locked door, and a broken toilet.",
"Hallway": "You are in the hallway. There are guards patrolling the area.",
"Courtyard": "You are in the courtyard. There's a high fence surrounding the area. You also notice a file hidden in the grass.",
"Gate": "You are at the gate. It's heavily guarded with guards on duty 24/7...",
"Camp": "You find a camp within the clump of bushes. And seems like no one is around...",
"Cafeteria": "You are in the cafeteria. There are some inmates that are friendly. But beware, some of them might be hostile.",
"Dream": "You lay on the bed. It's not quite comfortable, but you manage to fall asleep. You then wake up in a weird place and see a glimmer of light in the distance",
"Toilet": "You are trying to do your business and notice that someone left a twisted paperclip on the floor.",
"Window": "You are at the window. It is boarded up with metal bars. You also caught a glimpse of a moat down below.",
"Moat": "You are submerged in water, and it's extremely smelly.",
"Forest": "You are surrounded by trees and it's very creepy. You see a faint light in the distance...",
"Cabin": "You see a small little cabin situated in the middle of nowhere...",
"Cabin-room": "You see a small little table, a tiny kitchen and a hallway leading to another room",
"Cabin-bathroom": "You are in a bathroom, there's a sink, bathtub at the back and a couple bottles of shampoo and soap.",
"Cabin-bedroom": "You are in a bedroom, fairly decorated with a bedside cabinet, some shelves on the wall, a nice little desk and a bed.",
"Freedom": "Congratulations! You've escaped from the prison!",
"Zombie": "You walk into the unknowing territory of the un-dead creatures, and they all are headed your way...",
"Sanctuary": "You are in a ancient place, here before time had a name... and a fellow person is walking in your direction... he asks you for the time...",
"Tent1": "You walk into the first tent and low and behold! A sword lying on the ground, also a bed on the right with a little torch on the left.",
"Tent2": "You walk into the second tent and see a bed with a little cupboard next to it, you also spot some stains on the floor... Ew",
"Jungle": "You stroll deep into the jungle and heard a disturbance not far away, but it is late.. Is it wise to be curious? Or do we leave it...",
"Cupboard": "In the cupboard you find an old watch, a smelly sock, and a crumpled up note.",
"Note": "To whoever is reading this, you must get out of here... the zombies are coming. THIS IS YOUR FINAL warning, millions and billions have died to this insane horde of the un-dead! If you hear any sounds, DO NOT go towards it! I repeat DON'T go towards it! It means zombies are headed your way! Good luck fellow stranger... May the best of luck be with you... Cheers, Some dude",
"Palace": "You are in a huge palace fitted with rooms of the most exquite artifacts. There are so much it is overwhelming....",
}
# Define the possible actions the player can take
actions = {
"Cell": {
"Explore": "Hallway",
"Sleep on bed": "Dream",
"Use Toilet": "Toilet",
"Go through window": "Window",
"Stay in cell": "Cell",
},
"Hallway": {
"Turn Left": "Courtyard",
"Turn right": "Cafeteria",
"Return to cell": "Cell",
},
"Courtyard": {
"Climb fence": "Gate",
"Return to hall": "Hallway",
"Pick up file": "file",
},
"Cafeteria": {
"Get food": "Cafeteria",
"Talk to inmate John": "John",
"Talk to inmate Jane": "Jane",
"Talk to inmate Jack": "Jack",
"Return to cell": "Cell",
},
"Gate": {
"Bribe guard": "bribe",
"Retreat": "Courtyard",
"Fight guard": "Death",
},
"Dream": {
"Wake up": "Cell",
"Walk to the source": "Camp",
},
"Sanctuary": {
"Talk to the person": "Sanctuary",
"Wake up": "Cell",
},
"Camp": {
"Go inside first tent": "Tent1",
"Go inside second tent": "Tent2",
"Wander on into the jungle": "Jungle",
},
"Tent1": {
"Steal sword": "sword",
"Take the torch": "torch",
"Sleep for the night": "Dream",
"Leave tent": "Camp",
},
"Tent2": {
"Search the cupboard": "Cupboard",
"Sleep for the night": "Dream",
"Leave tent": "Camp",
},
"Jungle": {
"Walk to the sound": "Zombie",
"Go back to camp": "Camp",
},
"Cupboard": {
"Take watch": "watch",
"Take sock": "sock",
"Read note": "Note",
},
"Note": {
"Stay in tent": "Tent2",
"Go outside": "Camp",
},
"Zombie": {
"Run away": "Sanctuary",
"Go back to camp": "Camp",
},
"Palace": {
"Explore": "Palace",
},
"Toilet": {
"Pick up paperclip": "paperclip",
"Forget about it": "Cell",
},
"Window": {
"Jump": "Moat",
"Don't jump": "Cell",
},
"Moat": {
"Swim right": "Courtyard",
"Swim left": "Forest",
},
"Forest": {
"Go to the source of light": "Cabin",
"Go back to moat": "Moat",
},
"Cabin": {
"Go in": "Cabin-room",
"Go back to moat": "Moat",
},
"Cabin-room": {
"Go out": "Cabin",
"Go to the right": "Cabin-bathroom",
"Go to the left": "Cabin-bedroom",
},
"Cabin-bathroom": {
"Go back to first room": "Cabin-room",
},
"Cabin-bedroom": {
"Go back to first room": "Cabin-room",
},
}
"""============================== ACTION HANDLING =================================="""
def perform_action(location):
"""
Displays possible actions for the given location and allows the player to choose an action.
Args:
- location (str): Current location within the game.
Returns:
- str: Next location based on the player's chosen action.
"""
action_dict = {} # Dictionary to map action numbers to actions
count = 1 # Initialize action number counter
try:
# Display each action available for the current location
for action in actions[location]:
dialogue(f"{count}. {action}", Colors.LIGHT_YELLOW)
action_dict[str(count)] = action # Map action number to action string
count += 1 # Increment action number
actionNum = input(ask("Action: ")).strip() # Prompt player to choose an action
print()
if actionNum in action_dict:
selectedAction = action_dict[actionNum] # Get selected action string
return actions[location][
selectedAction
] # Return next location based on selected action
else:
dialogue("Invalid action. Please try again.")
return perform_action(location)
except KeyError:
dialogue("Invalid location. Please try again.")
return perform_action(location)
except Exception as e:
print(f"An error occurred: {e}") # Print any unexpected error
return perform_action(location)
items.py (216 lines)
from dialogue import dialogue, ask, Colors
"""=============================== ITEM DATABASE ================================="""
# Define items
# Define possible item locations
itemLocations = {
"Courtyard": "Null",
"Window": "Locked",
"Zombie": "Null",
"Sanctuary": "Null",
}
"""
Key Arguments:
"desc": "Description of the item",
(
"Location for using item",
"Item to use in the location",
): "Message when the item is used",
new_location: "Where you will be if item is used successfully"
old_location: "Where you will be if item is used unsuccesfully (i.e. cannot be used, or )"
"""
Items = {
"paperclip": {
"desc": "You keep it hidden in your pocket",
(
"Courtyard",
"paperclip",
): "You used the paperclip to pick the lock and escaped!",
"new_location": "Freedom",
"old_location": "Cell",
"Status": "Null",
},
"file": {
"desc": "You keep it hidden in your pocket...",
(
"Window",
"file",
): "You used the file to cut the bars and go through the window!",
"new_location": "Window",
"old_location": "Courtyard",
"Status": "Unlocked",
},
"sword": {
"desc": "You strap it on your back",
(
"Zombie",
"sword",
): "You fight for your life and barely escaped death, swishing and slashing at the ever growing hoard of un-dead creatures and ran until you reached an ancient place...",
"new_location": "Sanctuary",
"old_location": "Tent1",
"Status": "Null",
},
"torch": {
"desc": "You carry it in your hand",
(
"Jungle",
"sword",
): "You fight for your life and barely escaped death, swishing and slashing at the ever growing hoard of un-dead creatures and ran until you reached an ancient place...",
"new_location": "Sanctuary",
"old_location": "Tent2",
"Status": "Null",
},
"watch": {
"desc": "You wear it on your hand",
(
"Sanctuary",
"watch",
): "You look at it and did some quick calculations and came up with a solution",
"new_location": "Palace",
"old_location": "Tent2",
"Status": "Null",
},
"sock": {
"desc": "You stuff it in your backpocket",
(
"Zombie",
"sock",
): "You realize that zombies love the smell of absolute disgusting stuff so you throw the sock away and baited them away from you. Phew...",
"new_location": "Zombie",
"old_location": "Tent2",
"Status": "Null",
},
}
# Define failure messages for using items in specific locations without the correct items
"""
Key Arguments:
"Fail locations": {
"Fail_Desc": "Msg shown if you don't have items to use",
"Prev_Location": "Go to the location previous to this (i.e. if no item for window go back to cell, or in certain cases if no items for courtyard stay at the same spot)",
},
"""
ItemFails = {
"Window": {
"Fail_Desc": "Unforunately, you don't have the tools for the job... So you jump back down",
"Prev_Location": "Cell",
},
"Courtyard": {
"Fail_Desc": "Unforunately, you can't break out yet... But you still got some options",
"Prev_Location": "Courtyard",
},
"Zombie": {
"Fail_Desc": "Without weapons, defending is impossible and you are deadmeat...",
"Prev_Location": "Death",
},
"Sanctuary": {
"Fail_Desc": "Even though you made it here, you don't have the right tme and they refuse to let you in... but you still can do something...",
"Prev_Location": "Sanctuary",
},
}
# Player's inventory
inventory = []
"""=============================== ITEM HANDLING ================================="""
# Function to handle item interactions
def interact_with_item(item):
"""
Handles interactions with items, such as picking them up and adding them to the inventory.
Args:
- item (str): The name of the item to interact with.
Returns:
- str: The new current location after interacting with the item.
"""
if item not in inventory:
item_desc = Items[item]["desc"]
dialogue(item_desc)
inventory.append(item)
dialogue(f"{item.title()} added to inventory", Colors.GREEN)
else:
dialogue(f"{item.title()} is already in your inventory", Colors.LIGHT_GRAY)
item_ogLocation = Items[item]["old_location"]
return item_ogLocation # Return the original location of the item's whereabouts
# Function to use item in the inventory
def use_item(location, item):
"""
Uses an item at a specified location and handles the consequences.
Args:
- location (str): The current location where the item is being used.
- item (str): The name of the item to use.
Returns:
- str: The new current location after using the item.
"""
location_item = (location, item)
if item in inventory:
if item in Items and location_item in Items[item]:
# Define msg / New locale / New Status
item_msg = Items[item][location_item]
item_new_location = Items[item]["new_location"]
item_new_status = Items[item]["Status"]
# Update item status if applicable
itemLocations[location] = item_new_status
dialogue(item_msg, Colors.LIME) # Display item usage dialogue
# Return new location after using the item
return (item_new_location, "success")
else:
# Inform player of invalid item usage
dialogue(f"You can't use {item} here.", Colors.LIGHT_RED)
else:
# Inform player item is not in inventory
dialogue(f"You don't have {item} in your inventory.", Colors.LIGHT_GRAY)
item_ogLocation = ItemFails[location]["Prev_Location"]
return (item_ogLocation, "yes_items")
# Function to handle item usage based on player input
def handle_item_usage(location):
"""
Handles the process of prompting the player to use an item and executes the action.
Args:
- location (str): The current location where item usage is being handled.
Returns:
- str: The new current location after handling item usage.
"""
if inventory:
use_item_option = (
input(ask("Would you like to use an item? (yes/no): ")).strip().lower()
)
print()
if use_item_option == "yes":
# Display current inventory
dialogue(f"Inventory: {' | '.join(inventory)}", Colors.CYAN)
item_choice = input(
ask("Which item would you like to use? ", Colors.YELLOW)
).strip()
print()
use_result = use_item(location, item_choice) # Use the selected item
return use_result # Returns either success or "yes_items"
else:
# Inform player no items were used
dialogue("No items used...", Colors.LIGHT_GRAY)
else:
return ("nullItem", location)
item_ogLocation = ItemFails[location]["Prev_Location"]
return (item_ogLocation, "no_items")
inmates.py (134 lines)
from dialogue import dialogue, ask, Colors
# Define inmate interactions
inmates = {
"John": {
"intro": "Wassup kid, you new round here?",
"responses": [
{
"text": "Me: Yea kinda... I guess",
"response": "John: Nice to meet ya. Just a tip of advice. Don't talk to Jack, he's kinda not friendly.",
},
{
"text": "Me: None of your business.",
"response": "John: Alright, fine be like that. You ain't gonna survive in here if ya not gonna make friends. Get out of here kid...",
},
],
},
"Jane": {
"intro": "Jane: Hi, I'm Jane. Whatcha doin'?",
"responses": [
{
"text": "Me: Just hanging around. What about you?",
"response": "Jane: Same old, same old. Trying to survive in this place.",
},
{
"text": "Me: None of your business.",
"response": "Jane: Fine, be that way.",
},
{
"text": "Me: Can you help me with something?",
"response": "Jane: Depends on what you need. What's up?",
"follow_up": {
"options": [
{
"text": "Me: How do I sneak out of here",
"response": "Jane: Beats me kid. IDK",
},
{
"text": "Me: Nevermind",
"response": "Jane: Alright see you around kid.",
},
]
},
},
{
"text": "I need to know about the guards' schedule. Can you help?",
"response": "Jane: Guards' schedule, huh? Well, that's valuable info.",
"follow_up": {
"response": "Jane: Alright, here's the deal. I'll tell you what I know, but I'll need a favor in return. There's a guard who owes me a favor. If you can get him to look the other way tonight, I'll spill the beans about the schedule.",
"options": [
{
"text": "I'm up for it. Tell me what I need to do.",
"response": "Jane: Good choice. Here's the guard's name and the details of the favor. Get it done, and I'll give you the info you need.",
},
{
"text": "No thanks, I'll find another way.",
"response": "Jane: Suit yourself. Let me know if you change your mind.",
},
{
"text": "I'll think about it. Can you give me more details?",
"response": "Jane: Of course. Here's what you need to know...",
"follow_up": {
"response": "Jane: So, now that you have all the details, what's your decision?",
"options": [
{
"text": "I'm up for it. Tell me what I need to do.",
"response": "Jane: Good choice. Here's the guard's name and the details of the favor. Get it done, and I'll give you the info you need.",
},
{
"text": "No thanks, I'll find another way.",
"response": "Jane: Suit yourself. Let me know if you change your mind.",
},
],
},
},
],
},
},
],
},
}
"""============================= INMATE INTERACTION ==================================="""
# Function to handle inmate interactions
def inmate_interaction(inmate_name):
"""Handles the dialogue interactions with inmates."""
conversation = inmates[inmate_name]
dialogue(conversation["intro"])
while True:
for index, response in enumerate(conversation["responses"], start=1):
dialogue(f"{index}. {response['text']}")
choice = input(ask("Your response: "))
if choice.isdigit() and 1 <= int(choice) <= len(conversation["responses"]):
selected_response = conversation["responses"][int(choice) - 1]
dialogue(selected_response["response"])
# Check if there's a follow-up question
if "follow_up" in selected_response:
follow_up = selected_response["follow_up"]
dialogue(follow_up["response"])
while True:
for index, option in enumerate(follow_up["options"], start=1):
dialogue(f"{index}. {option['text']}")
follow_up_choice = input(ask("Your response: "))
if follow_up_choice.isdigit() and 1 <= int(follow_up_choice) <= len(
follow_up["options"]
):
selected_option = follow_up["options"][
int(follow_up_choice) - 1
]
dialogue(selected_option["response"])
# Check if there's a further follow-up
if "follow_up" in selected_option:
follow_up = selected_option["follow_up"]
dialogue(follow_up["response"])
continue # Continue the loop for further follow-up
else:
break # Exit the loop if no further follow-up
else:
dialogue("Invalid choice. Please choose again.")
break # Exit the conversation loop
else:
break # Exit the conversation loop if no follow-up
else:
dialogue("Invalid choice. Please choose again.")
dialogue.py (126 lines)
import time
import sys
# Define ANSI escape codes for colors
class Colors:
"""Defines colors for aesthetics"""
# Standard colors
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
RESET = "\033[0m" # Resets the color to default
# Additional colors
LIGHT_RED = "\033[38;5;203m" # Light Red
ORANGE = "\033[38;5;214m" # Orange
LIGHT_YELLOW = "\033[38;5;227m" # Light Yellow
YELLOW_GREEN = "\033[38;5;155m" # Yellow-Green
LIGHT_GREEN = "\033[38;5;120m" # Light Green
GREEN_BLUE = "\033[38;5;38m" # Green-Blue
LIGHT_BLUE = "\033[38;5;39m" # Light Blue
BLUE_PURPLE = "\033[38;5;99m" # Blue-Purple
PURPLE = "\033[38;5;129m" # Purple
LIGHT_PURPLE = "\033[38;5;177m" # Light Purple
PINK = "\033[38;5;198m" # Pink
LIGHT_PINK = "\033[38;5;207m" # Light Pink
LIME = "\033[38;5;154m" # Lime
DARK_GRAY = "\033[90m" # Dark Gray
LIGHT_GRAY = "\033[37m" # Light Gray
DARK_BLUE = "\033[34m" # Dark Blue
BROWN = "\033[38;5;130m" # Brown
def split_message(message, max_length):
"""
Splits a long message into multiple lines, each of a specified maximum length,
without breaking words. If a word cannot fit within the maximum length, it is split
at the maximum length.
Args:
- message (str): The message to be split into multiple lines.
- max_length (int): The maximum allowed length of each line.
Returns:
- list: A list of strings, where each string is a line of the original message
that does not exceed the specified maximum length.
Example:
>>> split_message("This is an example of a long message that needs to be split into smaller lines.", 20)
['This is an example', 'of a long message', 'that needs to be', 'split into smaller', 'lines.']
"""
lines = []
while len(message) > max_length:
# Find the last space within the max_length
split_point = message.rfind(" ", 0, max_length)
if split_point == -1: # No spaces found within max_length
split_point = max_length
lines.append(message[:split_point])
message = message[split_point:].lstrip()
lines.append(message)
return lines
def dialogue(message, color=Colors.BLUE, max_length=80):
"""
Prints the prompt text and waits for user input.
Args:
- prompt (str): The prompt text to be displayed.
- color (str): The color code for the text.
Returns:
- str: The user's input.
"""
lines = split_message(message, max_length)
for line in lines:
for char in line:
sys.stdout.write(color + char + Colors.RESET)
sys.stdout.flush()
time.sleep(0.015)
print("\n") # New line after each chunk of text
def ask(message, color=Colors.LIGHT_BLUE, max_length=80):
"""
Prints the prompt text and waits for user input.
Args:
- prompt (str): The prompt text to be displayed.
- color (str): The color code for the text.
Returns:
- str: The user's input.
"""
lines = split_message(message, max_length)
for line in lines:
for char in line:
sys.stdout.write(color + char + Colors.RESET)
sys.stdout.flush()
time.sleep(0.02) # Adjust the sleep time to control the typing speed
return ""
def WON():
"""
Prints the winning message.
"""
dialogue(
"=========================YOU WON!!!!=========================",
Colors.GREEN,
)
def LOSE():
"""
Prints the losing message.
"""
dialogue(
"=========================YOU LOST!!!!=========================", Colors.RED
)
utils.py (29 lines)
from dialogue import dialogue, ask, Colors
from locations import actions
import random
def attempt_bribe():
"""
Attempts to bribe the guard at the gate with a randomized chance of success.
Returns:
- str: The new location or outcome after attempting to bribe the guard.
"""
success = random.choice([True, False, False]) # 33.34% chance of success
if success:
dialogue("You successfully bribed the guard and are free!", Colors.LIME)
# Update actions dictionary for successful bribe
actions["Gate"]["Bribe guard"] = "Freedom"
return "Freedom" # Return the new location after successful bribe
else:
dialogue(
"The guard didn't accept your bribe. You've been sentenced to death penalty...",
Colors.RED,
)
# Update actions dictionary for unsuccessful bribe
actions["Gate"]["Bribe guard"] = "Death"
return "Death" # Return the outcome of being caught after unsuccessful bribe
Our Python course is taught live, one-on-one, and every child builds a real project of their own just like these.