Refactor code for fancy printing, make instructions clearer

This commit is contained in:
Chris Proctor 2023-07-11 15:41:03 -04:00
parent c6f9f5cc41
commit 4e2abe1775
9 changed files with 165 additions and 121 deletions

View File

@ -1,48 +1,49 @@
# This is a Python program. You should run it by typing "chest.py"
import os
from pathlib import Path
from urllib.request import urlretrieve
import threading
import datetime
from threading import Timer
from datetime import datetime
import sys
sys.path.append('../../..')
from fancy_printing import print_fancy
def treasure():
print(" something shining brightly from within, so bright you can't")
print(" quite make out what it is.\n")
def monster1():
print(" *rumble* *rumble* *rumble* \n")
print(" Around the reef, nothing seems out of place.\n")
def monster2():
print(" *rumble* *rumble* *rumble* \n")
print(" A SEA MONSTER APPEARS FROM THE REEF! \n")
print(" The sea monster must have seen you open the chest!")
print(" There's no time to squander. You grab the treasure from the chest without taking a closer look!")
print(" Quick, use mkdir to make a \"bag\" directory and mv to")
print(" hide the treasure.jpg in the bag. ")
print(" Then get back to the surface ASAP! The monster is coming! \n")
print(" Don't forget to take your treasure bag with you up to the top directory!")
now = datetime.datetime.now()
with open(".timer", "w") as timerfile:
timerfile.write(str(now))
secret = "318"
print(" You approach the chest and see that the lock is surprisingly free of rust.")
print(" In fact, the code dials turn smoothly. Try entering a code.")
CHEST_TIMER_FILE = ".timer"
SECRET = "318"
APPROACH_CHEST = [
"You approach the chest and see that the lock is surprisingly free of rust. In fact, the code dials turn smoothly. Try entering a code."
]
CHEST_OPENS = [
"The chest snaps open, releasing several huge air bubbles. You look into the chest and see..."
]
TREASURE = [
"something shining brightly from within, so bright you can't quite make out what it is."
]
MONSTER1 = [
"*rumble* *rumble* *rumble*",
"Around the reef, nothing seems out of place."
]
MONSTER2 = [
"*rumble* *rumble* *rumble*",
"A SEA MONSTER APPEARS FROM THE REEF!",
"The sea monster must have seen you open the chest! There's no time to squander. You grab the treasure from the chest without taking a closer look! Quick, make a bag and store your treasure inside, using the following comamnds:",
"mkdir bag",
"mv treasure.jpg bag",
"Then get back to the surface ASAP! Don't forget to take your treasure bag with you. Remember, `..` means 'the parent directory,' so these commands will move the bag to the parent directory and then move yourself:",
"mv bag ../bag",
"cd .."
]
print_fancy(APPROACH_CHEST)
guess = input(" > ")
if guess == secret:
print(" The chest snaps open, releasing several huge air bubbles.")
print(" You look into the chest and see...\n")
if guess.strip() == SECRET:
Path(CHEST_TIMER_FILE).write_text(datetime.now().isoformat())
print_fancy(CHEST_OPENS)
os.system('cp ./../../../.assets/fork.jpg treasure.jpg')
timer1 = threading.Timer(1.0, treasure)
timer2 = threading.Timer(3.0, monster1)
timer3 = threading.Timer(5.0, monster2)
timer1.start()
timer2.start()
timer3.start()
Timer(1.0, print_fancy, [TREASURE]).start()
Timer(3.0, print_fancy, [MONSTER1]).start()
Timer(5.0, print_fancy, [MONSTER2]).start()
else:
print(" nothing happens. Maybe next time.")
print_fancy(["nothing happens. Maybe next time."])

View File

@ -3,5 +3,5 @@
to be at the edge of a plateau whose edges are encrusted with beautiful
corals.
Both sunken_ship and coral_reef are directories, so use the "cd" command
Both sunken_ship and coral_reef are directories, so use the `cd` command
to go into whichever one you want.

View File

@ -1,17 +1,21 @@
# This is a Python file. You can run it by typing "python ghost.py"
import sys
from pathlib import Path
sys.path.append('../../../..')
from fancy_printing import print_fancy
GHOST_GIVES_KEY = [
"You enter the cramped galley and notice a sad, lonely ghost wandering around. You always wondered if you would be afraid of ghosts, but somehow this feels completely normal. The ghost begins to speak.",
"'It has been a long while since I have seen anybody down here,' she says. 'I would like to give you a gift. Here's a key.'"
]
GHOST_IS_BORED = [
"The ghost glances over at you. 'I hope you find some use for that key.'"
]
KEY = " Even in the faint light of your lamp, the key has a golden gleam.\n\n"
if Path("key.txt").exists():
print(" The ghost glances over at you. 'I hope you find some use for that key.'")
print_fancy(GHOST_IS_BORED)
else:
print(" You enter the cramped galley and notice a sad, lonely ghost wandering")
print(" around. You always wondered if you would be afraid of ghosts, but")
print(" somehow this feels completely normal. The ghost begins to speak.")
print("")
print(" 'It has been a long while since I have seen anybody down here,' she says")
print(" 'I would like to give you a gift. Here's a key.'")
with open("key.txt", "w") as keyfile:
keyfile.write(" Even in the faint light of your lamp, the key has a golden gleam.\n")
print_fancy(GHOST_GIVES_KEY)
Path("key.txt").write_text(KEY)

View File

@ -1,14 +1,22 @@
# This is a Python program. You can run it by typing "python desk.py"
import sys
from pathlib import Path
sys.path.append('../../../..')
from fancy_printing import print_fancy
print(" The stateroom contains the ruins of an elegant office. Scraps of wallpaper")
print(" are peeling from the wall; there is an eel living in the chandelier.")
print(" There is a huge desk at the center of the room.")
DESCRIPTION = [
"The stateroom contains the ruins of an elegant office. Scraps of wallpaper are peeling from the wall; there is an eel living in the chandelier. There is a huge desk at the center of the room."
]
OPEN_DESK = [
"You try your key in the desk drawer, and it clicks open. There are many decaying pieces of paper. One has the numbers 318 written in a fine script."
]
DESK_LOCKED = [
"You try to open the desk's drawer, but it is firmly locked."
]
print_fancy(DESCRIPTION)
if Path("../galley/key.txt").exists():
print(" You try your key in the desk drawer, and it clicks open. There are")
print(" many decaying pieces of paper. One has the numbers 318 written in")
print(" a fine script.")
print_fancy(OPEN_DESK)
else:
print(" You try to open the desk's drawer, but it is firmly locked.")
print_fancy(DESK_LOCKED)

10
fancy_printing.py Normal file
View File

@ -0,0 +1,10 @@
from click import secho
from textwrap import wrap
def print_fancy(paragraphs):
for paragraph in paragraphs:
wrapped_text = wrap(paragraph, initial_indent=' ', subsequent_indent=' ')
for line in wrapped_text:
secho(line, fg='cyan')
print('')

28
poetry.lock generated
View File

@ -1,7 +1,31 @@
# This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand.
package = []
[[package]]
name = "click"
version = "8.1.4"
description = "Composable command line interface toolkit"
optional = false
python-versions = ">=3.7"
files = [
{file = "click-8.1.4-py3-none-any.whl", hash = "sha256:2739815aaa5d2c986a88f1e9230c55e17f0caad3d958a5e13ad0797c166db9e3"},
{file = "click-8.1.4.tar.gz", hash = "sha256:b97d0c74955da062a7d4ef92fadb583806a585b2ea81958a81bd72726cbb8e37"},
]
[package.dependencies]
colorama = {version = "*", markers = "platform_system == \"Windows\""}
[[package]]
name = "colorama"
version = "0.4.6"
description = "Cross-platform colored terminal text."
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
files = [
{file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
[metadata]
lock-version = "2.0"
python-versions = "^3.10"
content-hash = "17ca553b0bb9298a6ed528dd21e544ca433179192dba32a9920168e1c199d74f"
content-hash = "6cfb3d71df95e3e0d9fbd3bd3803dcaea2cd2db898299bb891ccda039aede2bb"

View File

@ -7,6 +7,8 @@ license = "MIT"
[tool.poetry.dependencies]
python = "^3.10"
click = "^8.1.4"
colorama = "^0.4.6"
[tool.poetry.dev-dependencies]

View File

@ -1,62 +0,0 @@
from pathlib import Path
import shutil
from datetime import datetime
from datetime import timedelta
import subprocess
def reset():
shutil.rmtree('bag')
Path('adventure/seafloor/coral_reef/.timer').unlink()
print(" You are swimming as fast as you can towards the boat but you can")
print(" feel the water begin to pull you back as the sea monster opens its")
print(" giant mouth.")
print(" You kick with all your might, sure that you are about to breath your")
print(" last breath.")
print(" ")
print(" ")
print(" Suddenly... The treasure bag slips out of your hand!")
print(" It swirls down through the water and into the mouth of the sea monster.")
print(" The beast's mouth snaps closed and it jets away into the depth of the")
print(" ocean, taking with it the treasure.")
print(" You are safe... but will you attempt the dive again?")
def win():
print(" You are swimming as fast as you can towards the boat but you can")
print(" feel the water begin to pull you back as the sea monster opens its")
print(" giant mouth.")
print(" You kick with all your might, sure that you are about to breathe your")
print(" last breath.")
print(" ")
print(" ")
print(" Suddenly... A hand appears!")
print(" You've made it to the boat! The crew pulls you into the boat, just in")
print(" time to avoid the sea monster's vicious maw.")
print(" You're safe at last!")
print(" Now you can finally show off the treasure you risked your life for...")
print(" Use open treasure.jpg to take a peek.")
now = datetime.now()
if not Path("adventure/seafloor/coral_reef/.timer").exists():
print(" Your adventure has only just begun. You are not yet ready to return")
print(" to the ship. More secrets await you in the ocean's depths.")
else:
if not Path("./bag/treasure.jpg").exists():
print(" You forgot your treasure bag! Hurry back to get it before the sea monster")
print(" hides it away forever!")
else:
with open ("adventure/seafloor/coral_reef/.timer", "r") as timerFile:
timeChestOpenedAsList=timerFile.readlines()
timeChestOpened = datetime.strptime(('').join(timeChestOpenedAsList), '%Y-%m-%d %H:%M:%S.%f')
if timeChestOpened + timedelta(seconds=60) < now:
reset()
else:
win()

57
return_to_ship.py Normal file
View File

@ -0,0 +1,57 @@
from shutil import rmtree
from pathlib import Path
from datetime import datetime
from datetime import timedelta
from fancy_printing import print_fancy
CHEST_TIMER_FILE = "adventure/seafloor/coral_reef/.timer"
BEGINNING = [
"Your adventure has only just begun. You are not yet ready to return to the ship. More secrets await you in the ocean's depths. Use `ls` to look around, and use `cd adventure` to start the adventure..."
]
FORGOT_BAG = [
"You forgot your treasure bag! Hurry back to get it before the sea monster hides it away forever!"
]
LOST_TREASURE = [
"You are swimming as fast as you can towards the boat but you can feel the water begin to pull you back as the sea monster opens its giant mouth. You kick with all your might, sure that you are about to breath your last breath.",
"",
"Suddenly... The treasure bag slips out of your hand!",
"It swirls down through the water and into the mouth of the sea monster. The beast's mouth snaps closed and it jets away into the depth of the ocean, taking with it the treasure. You are safe... but will you attempt the dive again?"
]
VICTORY = [
"You are swimming as fast as you can towards the boat but you can feel the water begin to pull you back as the sea monster opens its giant mouth. You kick with all your might, sure that you are about to breathe your last breath."
"",
"Suddenly... A hand appears! You've made it to the boat! The crew pulls you into the boat, just in time to avoid the sea monster's vicious maw. You're safe at last! Now you can finally show off the treasure you risked your life for... Use `open treasure.jpg` to take a peek."
]
def reset():
rmtree('bag')
Path('adventure/seafloor/coral_reef/.timer').unlink()
print_fancy(LOST_TREASURE)
def win():
print_fancy(VICTORY)
def chest_was_opened():
return Path(CHEST_TIMER_FILE).exists()
def treasure_is_present():
return Path("bag/treasure.jpg").exists()
def time_since_chest_was_opened():
if chest_was_opened():
treasure_opened_time = datetime.fromisoformat(Path(CHEST_TIMER_FILE).read())
elapsed_time = datetime.now() - treasure_opened_time
return elapsed_time
else:
return 0
if chest_was_opened():
if treasure_is_present():
if time_since_chest_was_opened() < 60:
win()
else:
reset()
else:
print_fancy(FORGOT_BAG)
else:
print_fancy(BEGINNING)