Your goal is to accumulate as much wealth as possible within a set number of turns.
Explore a variety of goods, manage your cargo capacity, and navigate the dynamic market.
Choose Difficulty Level:
Easy
Medium
Hard
Enter the number corresponding to your choice (1-3):
async def slow_input(prompt):
await fast_print(prompt)
# Input is already disabled; wait for user to input via JS and send 'input-received' event
await asyncio.sleep(0) # Yield control to allow user interaction
code
promise = asyncio.Future()
# Define a proxy to resolve the promise when input is received
def on_user_input(event):
if user_input.value.strip() != '':
promise.set_result(user_input.value.strip())
# Input is already disabled by JS's handleSend()
input_handler = create_proxy(on_user_input)
document.addEventListener('input-received', input_handler)
result = await promise
document.removeEventListener('input-received', input_handler)
return result.lower()
async def safe_int_input(prompt, min_val, max_val):
while True:
try:
input_str = await slow_input(prompt)
selected = int(input_str)
if min_val <= selected <= max_val:
return selected
else:
await fast_print(f"Please enter a number between {min_val} and {max_val}.")
except ValueError:
await fast_print("Invalid input. Please enter a valid number.")
GLOBAL_EVENTS = [
"Economic boom affecting all markets.",
"Global trade embargo reducing supply worldwide.",
"Pandemic affecting demand for certain goods globally.",
"Technological advancements altering trade dynamics.",
"Global inflation increasing prices across the board.",
"Global recession decreasing purchasing power.",
]
LOCAL_EVENTS = [
"Thieves attacked your caravan and stole some goods!",
"A storm ruined your goods during travel.",
"A festival in town increased demand for certain goods.",
"Disease outbreak decreased the demand for food.",
"New trade routes discovered, affecting supply.",
"Pirates disrupted trade in the seas.",
"Economic boom in Crimsonburg raised prices.",
"Market crash in Brightstone lowered prices.",
"Government imposed a tax on trade.",
"Discovery of a rare gem deposit increased gem supply.",
"Locusts devastated the food supplies in Dusktown.",
"Artisans in Amberville created new uses for spices, increasing their demand.",
"Floods in Riverside increased the supply of iron.",
"Harvest season in Lakeside boosted the demand for food.",
"Gold rush in Hilltop increased the supply and demand for gold.",
"Silk shortage in Sunset City raised silk prices.",
"Herbal harvest in Oakwood decreased the supply of herbs.",
"Tea festival in Fairview increased the demand for tea.",
"Ironworks expansion in Northport increased the supply of iron.",
"Wine tasting event in Stormhaven boosted wine prices.",
"Cloth market crash in Fairview lowered cloth prices.",
"Bandit attack in Oakwood stole some of your goods.",
"Natural disaster in Dusktown affecting multiple goods.",
"Town marketplace upgrade in Riverside lowered base prices for certain goods.",
]
class AITrader:
"""Represents an AI trader that interacts with the market each turn."""
def init(self, trader_id, aggressiveness=1.0):
self.trader_id = trader_id
self.name = f"Trader_{trader_id}"
self.aggressiveness = aggressiveness # Determines transaction sizes and frequency
code
def perform_action(self, market):
"""AI trader performs buy or sell actions based on strategy."""
num_actions = random.randint(1, 3) if self.aggressiveness > 1.0 else random.randint(1, 2)
for _ in range(num_actions):
action = random.choices(["BUY", "SELL"], weights=[self.aggressiveness, 1.0])[0]
good = random.choice(list(GOODS.keys()))
quantity = random.randint(1, int(10 * self.aggressiveness))
if action == "BUY":
if market.supply[good] >= quantity:
market.supply[good] -= quantity
market.demand[good] += quantity * 0.5
elif action == "SELL":
market.supply[good] += quantity
market.demand[good] -= quantity * 0.5
if market.demand[good] < 50:
market.demand[good] = 50
class Market:
"""Represents the market of a specific town."""
PRICE_FLOOR = 10
PRICE_CEILING = 2000
code
def __init__(self, town):
self.town = town
self.supply = {}
self.demand = {}
for good, info in GOODS.items():
supply_variation = random.uniform(0.9, 1.1)
demand_variation = random.uniform(0.9, 1.1)
self.supply[good] = info["base_supply"] * supply_variation
self.demand[good] = info["base_demand"] * demand_variation
self.prices = {}
self.generate_prices()
self.ai_traders = [AITrader(trader_id=i+1, aggressiveness=random.uniform(0.8, 1.2)) for i in range(10)]
def generate_prices(self):
"""Calculates current prices based on supply and demand with elasticity and price constraints."""
for good, info in GOODS.items():
if self.supply[good] == 0:
price_multiplier = 2
else:
ratio = self.demand[good] / self.supply[good]
elasticity = random.uniform(0.90, 1.10)
price_multiplier = ratio * elasticity
new_price = int(GOODS[good]["base_price"] * price_multiplier)
new_price = max(self.PRICE_FLOOR, min(new_price, self.PRICE_CEILING))
self.prices[good] = new_price
async def display_prices(self, relationship):
"""Displays the current prices, supply, demand, and relationship for all goods in the market."""
status = Game.get_relationship_status(relationship)
await slow_print(f"\nMarket Overview in {self.town}: Relationship: {relationship} ({status})", color='magenta')
for good, price in self.prices.items():
supply = int(self.supply[good])
demand = int(self.demand[good])
await fast_print(f"{good}: ${price} (Supply: {supply}, Demand: {demand})")
await fast_print("")
def process_ai_traders(self):
"""Processes all AI traders' actions for the market."""
for trader in self.ai_traders:
trader.perform_action(self)
self.generate_prices()
class Player:
"""Represents the player with money, inventory, and cargo capacity."""
def init(self, starting_money, starting_cargo):
self.money = starting_money
self.inventory = {good: 0 for good in GOODS}
self.location = random.choice(TOWNS)
self.turns = 0
self.max_cargo = starting_cargo
self.current_cargo = 0
self.cargo_upgrades = 0
self.relationships = {town: RELATIONSHIP_BASE for town in TOWNS}
self.event_log = [] # To track key events per turn
code
async def status(self):
"""Displays the player's current status."""
await slow_print(f"\nPlayer Status:", color='green')
await fast_print(f"Location: {self.location}")
await fast_print(f"Money: ${self.money}")
await fast_print(f"Cargo: {self.current_cargo}/{self.max_cargo} units used")
await fast_print("Inventory:")
for good, qty in self.inventory.items():
await fast_print(f" {good}: {qty}")
await fast_print("")
def add_cargo(self, good, quantity):
"""Attempts to add cargo to the player's inventory."""
weight = GOODS[good]["weight"]
total_weight = weight * quantity
if self.current_cargo + total_weight > self.max_cargo:
return False, total_weight
self.current_cargo += total_weight
self.inventory[good] += quantity
return True, total_weight
def remove_cargo(self, good, quantity):
"""Removes cargo from the player's inventory."""
weight = GOODS[good]["weight"]
total_weight = weight * quantity
self.current_cargo -= total_weight
if self.current_cargo < 0:
self.current_cargo = 0
self.inventory[good] -= quantity
if self.inventory[good] < 0:
self.inventory[good] = 0
async def upgrade_cargo(self):
"""Allows the player to upgrade cargo capacity."""
upgrade_cost = 500 + (self.cargo_upgrades * 200)
upgrade_amount = 50
if self.money < upgrade_cost:
await slow_print("Insufficient funds to upgrade cargo capacity.")
return
confirm = await slow_input(f"Upgrade cargo capacity by {upgrade_amount} for {upgrade_cost} gold? (Y/N): ")
if confirm.lower() == 'y':
self.money -= upgrade_cost
self.max_cargo += upgrade_amount
self.cargo_upgrades += 1
await slow_print(f"Cargo capacity increased by {upgrade_amount}. New capacity: {self.max_cargo}")
self.event_log.append(f"Upgraded cargo capacity by {upgrade_amount} for {upgrade_cost} gold.")
class Game:
"""Represents the main game loop and logic."""
code
def __init__(self):
self.difficulty = None
self.player = None
self.turns_total = 0
self.markets = {}
self.current_market = None
self.current_event = None
self.supply_decay_rate = 0.02
self.demand_decay_rate = 0.02
self.turn_counter = 1
self.game_over = False
self.key_events = []
@staticmethod
def get_relationship_status(relation):
"""Converts a numerical relationship score into a descriptive status."""
if relation > 50:
return "Friendly"
elif relation >= -50:
return "Neutral"
else:
return "Hostile"
async def choose_difficulty(self):
"""Allows the player to choose a difficulty level."""
await fast_print("Choose Difficulty Level:")
difficulties = list(DIFFICULTIES.keys())
for idx, level in enumerate(difficulties, 1):
await fast_print(f"{idx}. {level.capitalize()}")
choice = await safe_int_input(f"Enter the number corresponding to your choice (1-{len(DIFFICULTIES)}): ", 1, len(DIFFICULTIES))
selected = difficulties[choice - 1]
await fast_print(f"Selected {selected.capitalize()} difficulty.\n")
self.difficulty = selected
self.player = Player(
starting_money=DIFFICULTIES[self.difficulty]["starting_money"],
starting_cargo=DIFFICULTIES[self.difficulty]["starting_cargo"]
)
self.turns_total = DIFFICULTIES[self.difficulty]["turns"]
self.markets = {town: Market(town) for town in TOWNS}
self.current_market = self.markets[self.player.location]
async def start(self):
"""Starts the game by displaying the title and welcome message."""
ascii_art_lines = [
" __ __ _ ____ _ _______ _____ ",
"| \\/ | / \\ | _ \\| |/ / ____|_ _|",
"| |\\/| | / _ \\ | |_) | ' /| _| | | ",
"| | | |/ ___ \\| _ <| . \\| |___ | | ",
"|_| |_/_/ \\_\\_| \\_\\_|\\_\\_____| |_| ",
]
ascii_art = '\n'.join(ascii_art_lines) # Use newline characters
await insta_print(ascii_art, color='cyan')
# Insta print lines of '=' signs
await insta_print("=" * 60, color='yellow')
await slow_print("Welcome to the Text-Based Trading Game!", color='yellow')
await insta_print("=" * 60, color='yellow')
# Slow print game introduction
game_description = (
"Your goal is to accumulate as much wealth as possible within a set number of turns.\n"
"Explore a variety of goods, manage your cargo capacity, and navigate the dynamic market."
)
await slow_print(game_description, color='yellow')
await self.choose_difficulty()
# Start the first turn
await self.game_turn()
async def game_turn(self):
"""Handles a single turn in the game."""
if self.turn_counter > self.turns_total:
await self.end_game()
return
await medium_print(f"\n--- Turn {self.turn_counter}/{self.turns_total} ---")
self.apply_decay()
for market in self.markets.values():
market.process_ai_traders()
self.trigger_event()
current_relationship = self.player.relationships[self.player.location]
await self.current_market.display_prices(current_relationship)
await self.player.status()
command = await slow_input("Enter command (BUY/SELL/TRAVEL/STATUS/UPGRADE/OVERVIEW/HELP/EXIT): ")
await self.process_command(command)
async def process_command(self, command):
"""Processes user command received from input."""
command = command.lower()
if command == "buy":
await self.buy()
elif command == "sell":
await self.sell()
elif command == "travel":
await self.travel()
elif command == "status":
await self.player.status()
elif command == "upgrade":
await self.player.upgrade_cargo()
elif command == "overview":
await self.market_overview()
elif command == "help":
await slow_print("""
Available Commands:
BUY - Purchase goods from the market.
SELL - Sell goods from your inventory.
TRAVEL - Move to a different town.
STATUS - View your current status.
UPGRADE - Upgrade your cargo capacity.
OVERVIEW - View market overview across all towns.
HELP - Display this help message.
EXIT - Exit the game.
""".strip(), color='yellow')
elif command == "exit":
await slow_print("Thank you for playing!")
await self.end_game()
self.game_over = True
return
else:
await fast_print("Invalid command.")
code
if not self.game_over:
self.turn_counter += 1
await self.game_turn()
async def buy(self):
"""Handles the buying process for the player."""
good = await self.choose_good("buy")
if not good:
return
price = self.current_market.prices[good]
max_affordable_quantity = self.player.money // price
available_cargo_space = self.player.max_cargo - self.player.current_cargo
max_cargo_quantity = available_cargo_space // GOODS[good]["weight"]
max_supply = int(self.current_market.supply[good])
max_quantity = min(max_affordable_quantity, max_cargo_quantity, max_supply)
if max_quantity <= 0:
await slow_print("You cannot buy any units of this good due to insufficient funds, cargo space, or supply.")
return
await fast_print(f"You can afford up to {max_quantity} units.")
quantity = await safe_int_input(f"Enter the quantity of {good} to buy (max {max_quantity}): ", 1, max_quantity)
cost = price * quantity
success, added_weight = self.player.add_cargo(good, quantity)
if not success:
await slow_print("Not enough cargo space.")
return
self.player.money -= cost
self.current_market.supply[good] -= quantity
self.current_market.demand[good] += quantity * 0.3
await slow_print(f"Bought {quantity} {good} for ${cost}.")
async def sell(self):
"""Handles the selling process for the player."""
good = await self.choose_good("sell")
if not good or self.player.inventory[good] == 0:
await fast_print(f"You have no {good} to sell.")
return
max_sell_quantity = self.player.inventory[good]
quantity = await safe_int_input(f"Enter the quantity of {good} to sell (max {max_sell_quantity}): ", 1, max_sell_quantity)
price = self.current_market.prices[good]
revenue = price * quantity
self.player.money += revenue
self.player.remove_cargo(good, quantity)
self.current_market.supply[good] += quantity
self.current_market.demand[good] -= quantity * 0.3
await slow_print(f"Sold {quantity} {good} for ${revenue}.")
async def travel(self):
"""Handles the travel process for the player."""
available_towns = [town for town in TOWNS if town != self.player.location]
await slow_print("Available towns to travel to:")
for idx, town in enumerate(available_towns, 1):
await fast_print(f"{idx}. {town}")
choice = await safe_int_input("Enter the number of the town you want to travel to: ", 1, len(available_towns))
new_location = available_towns[choice - 1]
self.player.location = new_location
self.current_market = self.markets[new_location]
await slow_print(f"Traveled to {new_location}.")
async def choose_good(self, action):
"""Prompts the player to choose a good to buy or sell."""
await fast_print("Available goods:")
for idx, good in enumerate(GOODS.keys(), 1):
await fast_print(f"{idx}. {good}")
choice = await safe_int_input(f"Enter the number of the good to {action}: ", 1, len(GOODS))
return list(GOODS.keys())[choice - 1]
async def end_game(self):
"""Displays the final game results and concludes the game."""
await slow_print("\nGame Over!", color='red')
await fast_print(f"Final Money: ${self.player.money}", color='yellow')
total_goods = sum(self.player.inventory.values())
await fast_print(f"Total Goods: {total_goods}", color='yellow')
await slow_print("Thank you for playing the Text-Based Trading Game!", color='yellow')
async def market_overview(self):
"""Displays an overview of all markets."""
await slow_print("\nMarket Overview Across All Towns:", color='magenta')
for town, market in self.markets.items():
relationship = self.player.relationships[town]
await market.display_prices(relationship)
await fast_print("")
def apply_decay(self):
"""Applies decay to supply and demand in all markets."""
for good, info in GOODS.items():
for market in self.markets.values():
market.supply[good] += (info["base_supply"] - market.supply[good]) * self.supply_decay_rate
market.demand[good] += (info["base_demand"] - market.demand[good]) * self.demand_decay_rate
def trigger_event(self):
"""Randomly triggers a global or local event."""
event_chance = DIFFICULTIES[self.difficulty]["event_chance"]
if random.random() < event_chance:
event = random.choice(GLOBAL_EVENTS + LOCAL_EVENTS)
asyncio.create_task(insta_print(f"\nEvent: {event}", color='red'))
It looks like you're experiencing an issue where selecting the difficulty level in your Text-Based Trading Game results in an "Invalid command." message followed by an immediate "Game Over!" This behavior suggests that there's a conflict in how user inputs are being handled during the difficulty selection phase versus the main game loop.
Root Cause Analysis
The core of the problem lies in how the game processes user inputs. Here's a breakdown of the flow based on your provided code:
Difficulty Selection:
The game starts by prompting the user to select a difficulty level (1, 2, or 3).
It uses the safe_int_input function to handle this input, which awaits a numerical input within the specified range.
Event Handling:
Simultaneously, there's a global event listener set up to handle all inputs as game commands (BUY, SELL, etc.) via the process_command function.
Conflict:
When the user inputs 3 for selecting the "Hard" difficulty, both the safe_int_input (within choose_difficulty) and the global process_command function receive this input.
The process_command function doesn't recognize 3 as a valid command, resulting in the "Invalid command." message.
After processing the invalid command, the game erroneously proceeds to terminate, displaying "Game Over!" even though the difficulty was selected correctly.
Solution
To resolve this issue, you need to manage the input flow more effectively, ensuring that inputs meant for difficulty selection are not simultaneously processed as game commands. Here's how you can achieve this:
Implement a Game State Mechanism:
Introduce a game state variable that tracks whether the game is in the difficulty selection phase or in the main game loop.
Only allow the process_command function to handle inputs when the game is in the main game loop.
Modify Event Handling:
Adjust the on_input_received function to respect the current game state.
Ensure that during the difficulty selection phase, inputs are directed exclusively to choose_difficulty and not to process_command.
Code Adjustments:
Here's how you can implement these changes in your code:
python
Explanation of Changes
Game State Management:
Introduced a self.state attribute in the Game class to track the current phase of the game (INIT, DIFFICULTY_SELECTION, MAIN_GAME, GAME_OVER).
Separate Input Handling:
Modified the on_input_received function to check the current game state.
If the game is in the DIFFICULTY_SELECTION state, it directs the input to a new method choose_difficulty_input.
If the game is in the MAIN_GAME state, it processes the input as a regular game command.
Handling Difficulty Selection Separately:
Created a new method choose_difficulty_input to handle inputs specifically for difficulty selection.
This method validates the input and updates the game state to MAIN_GAME upon successful selection, preventing the input from being processed as a game command.
Transitioning Between States:
After successfully selecting the difficulty, the game transitions to the MAIN_GAME state and initiates the first game turn.
Benefits of This Approach
Isolation of Input Phases: By clearly separating input handling based on the game state, you prevent unintended processing of inputs, such as treating difficulty selection inputs as game commands.
Enhanced Maintainability: Using a state mechanism makes the game's flow easier to manage and extend in the future, allowing for more complex interactions and phases.
Improved User Experience: Users won't encounter confusing "Invalid command." messages during initial setup, leading to a smoother and more intuitive gameplay experience.
Final Thoughts
Implementing a state management system is crucial for handling complex interactions in applications like text-based games. It ensures that inputs are contextually relevant and processed appropriately, thereby enhancing both functionality and user satisfaction.
If you continue to experience issues after implementing these changes, consider adding more detailed logging to trace the flow of inputs and game state transitions. This can help identify and resolve any remaining conflicts or bugs in the input handling logic.
# Add a game state attribute to the Game class
class Game:
"""Represents the main game loop and logic."""
def __init__(self):
self.state = "INIT" # Possible states: INIT, DIFFICULTY_SELECTION, MAIN_GAME, GAME_OVER
self.difficulty = None
self.player = None
self.turns_total = 0
self.markets = {}
self.current_market = None
self.current_event = None
self.supply_decay_rate = 0.02
self.demand_decay_rate = 0.02
self.turn_counter = 1
self.game_over = False
self.key_events = []
# ... [rest of the Game class]
async def choose_difficulty(self):
"""Allows the player to choose a difficulty level."""
self.state = "DIFFICULTY_SELECTION"
await fast_print("Choose Difficulty Level:")
difficulties = list(DIFFICULTIES.keys())
for idx, level in enumerate(difficulties, 1):
await fast_print(f"{idx}. {level.capitalize()}")
choice = await safe_int_input(f"Enter the number corresponding to your choice (1-{len(DIFFICULTIES)}): ", 1, len(DIFFICULTIES))
selected = difficulties[choice - 1]
await fast_print(f"Selected {selected.capitalize()} difficulty.\n")
self.difficulty = selected
self.player = Player(
starting_money=DIFFICULTIES[self.difficulty]["starting_money"],
starting_cargo=DIFFICULTIES[self.difficulty]["starting_cargo"]
)
self.turns_total = DIFFICULTIES[self.difficulty]["turns"]
self.markets = {town: Market(town) for town in TOWNS}
self.current_market = self.markets[self.player.location]
self.state = "MAIN_GAME" # Transition to main game state
async def process_command(self, command):
"""Processes user command received from input."""
if self.state != "MAIN_GAME":
# Ignore commands if not in main game state
return
command = command.lower()
if command == "buy":
await self.buy()
elif command == "sell":
await self.sell()
elif command == "travel":
await self.travel()
elif command == "status":
await self.player.status()
elif command == "upgrade":
await self.player.upgrade_cargo()
elif command == "overview":
await self.market_overview()
elif command == "help":
await slow_print("""
Available Commands:
BUY - Purchase goods from the market.
SELL - Sell goods from your inventory.
TRAVEL - Move to a different town.
STATUS - View your current status.
UPGRADE - Upgrade your cargo capacity.
OVERVIEW - View market overview across all towns.
HELP - Display this help message.
EXIT - Exit the game.
""".strip(), color='yellow')
elif command == "exit":
await slow_print("Thank you for playing!")
await self.end_game()
self.game_over = True
return
else:
await fast_print("Invalid command.")
if not self.game_over:
self.turn_counter += 1
await self.game_turn()
# Update the event listener to respect game state
def on_input_received(event):
command = event.detail
if game_instance.state == "DIFFICULTY_SELECTION":
asyncio.create_task(game_instance.choose_difficulty_input(command))
elif game_instance.state == "MAIN_GAME":
asyncio.create_task(game_instance.process_command(command))
# Add a new method to handle difficulty input separately
async def choose_difficulty_input(self, command):
"""Handles input specifically for difficulty selection."""
if command.isdigit():
choice = int(command)
if 1 <= choice <= len(DIFFICULTIES):
selected = list(DIFFICULTIES.keys())[choice - 1]
await fast_print(f"Selected {selected.capitalize()} difficulty.\n")
self.difficulty = selected
self.player = Player(
starting_money=DIFFICULTIES[self.difficulty]["starting_money"],
starting_cargo=DIFFICULTIES[self.difficulty]["starting_cargo"]
)
self.turns_total = DIFFICULTIES[self.difficulty]["turns"]
self.markets = {town: Market(town) for town in TOWNS}
self.current_market = self.markets[self.player.location]
self.state = "MAIN_GAME"
await self.game_turn()
else:
await fast_print("Invalid choice. Please enter a number corresponding to the difficulty levels.")
else:
await fast_print("Invalid input. Please enter a number.")
# Assign the new method to the Game class
Game.choose_difficulty_input = choose_difficulty_input
# Update the event listener proxy
input_received_handler = create_proxy(on_input_received)
document.addEventListener('input-received', input_received_handler)