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
await slow_print(f"Upgrade Cargo Capacity by {upgrade_amount} units for {upgrade_cost} gold? (Y/N): ", color='yellow')
confirm = await slow_input("")
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}", color='green')
self.event_log.append(f"Upgraded cargo capacity by {upgrade_amount} for {upgrade_cost} gold.")
else:
await slow_print("Cargo upgrade canceled.", color='yellow')
class Game:
"""Represents the main game loop and logic."""
code
def __init__(self):
self.input_mode = "INIT" # Modes: INIT, DIFFICULTY_SELECTION, MAIN_GAME, GAME_OVER, TRAVEL_SELECTION, BUY_SELECTION, BUY_QUANTITY, SELL_SELECTION, SELL_QUANTITY, UPGRADE_CONFIRMATION, GENERAL_COMMAND
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 = []
self.selected_buy_good = None
self.selected_sell_good = None
@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_input(self, command):
"""Handles input specifically for difficulty selection."""
difficulties = list(DIFFICULTIES.keys())
if command.isdigit():
choice = int(command)
if 1 <= choice <= 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.input_mode = "GENERAL_COMMAND" # Transition to main game state
await self.game_turn()
else:
await fast_print("Invalid choice. Please enter a number corresponding to the difficulty levels.", color='red')
else:
await fast_print("Invalid input. Please enter a number.", color='red')
async def handle_travel_selection(self, command):
"""Handles input specifically for travel selection."""
if command.isdigit():
choice = int(command)
available_towns = [town for town in TOWNS if town != self.player.location]
if 1 <= choice <= 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}.", color='green')
self.input_mode = "GENERAL_COMMAND"
await self.game_turn()
else:
await fast_print("Invalid town number. Please enter a valid number.", color='red')
else:
await fast_print("Invalid input. Please enter a number.", color='red')
async def handle_buy_selection(self, command):
"""Handles input specifically for buy selection."""
if command.isdigit():
choice = int(command)
goods_list = list(GOODS.keys())
if 1 <= choice <= len(goods_list):
selected_good = goods_list[choice - 1]
self.selected_buy_good = selected_good
await self.buy(selected_good)
else:
await fast_print("Invalid good number. Please enter a valid number.", color='red')
else:
await fast_print("Invalid input. Please enter a number.", color='red')
async def buy_quantity_handler(self, command):
"""Handles the quantity input for buying."""
selected_good = self.selected_buy_good
price = self.current_market.prices[selected_good]
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
cost = price * quantity
can_afford = self.player.money >= cost
available_cargo_space = self.player.max_cargo - self.player.current_cargo
max_cargo_quantity = available_cargo_space // GOODS[selected_good]["weight"]
available_supply = int(self.current_market.supply[selected_good])
max_buyable = min(self.player.money // price, max_cargo_quantity, available_supply)
if quantity > max_buyable:
if max_buyable == 0:
await fast_print("You cannot buy any units of this good due to insufficient funds, cargo space, or supply.", color='red')
else:
await fast_print(f"You can only buy up to {max_buyable} units of {selected_good}.", color='yellow')
await self.buy(selected_good) # Reprompt for quantity
return
# Proceed with buying
self.player.money -= cost
self.player.add_cargo(selected_good, quantity)
self.current_market.supply[selected_good] -= quantity
self.current_market.demand[selected_good] += quantity * 0.3
await slow_print(f"Bought {quantity} units of {selected_good} for ${cost}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def handle_sell_selection(self, command):
"""Handles input specifically for sell selection."""
if command.isdigit():
choice = int(command)
goods_with_inventory = [good for good, qty in self.player.inventory.items() if qty > 0]
if not goods_with_inventory:
await fast_print("You have no goods to sell.", color='yellow')
self.input_mode = "GENERAL_COMMAND"
await self.game_turn()
return
if 1 <= choice <= len(goods_with_inventory):
selected_good = goods_with_inventory[choice - 1]
self.selected_sell_good = selected_good
await self.sell(selected_good)
else:
await fast_print("Invalid good number. Please enter a valid number.", color='red')
else:
await fast_print("Invalid input. Please enter a number.", color='red')
async def sell_quantity_handler(self, command):
"""Handles the quantity input for selling."""
selected_good = self.selected_sell_good
price = self.current_market.prices[selected_good]
inventory_qty = self.player.inventory[selected_good]
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.sell(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.sell(selected_good) # Reprompt for quantity
return
if quantity > inventory_qty:
await fast_print(f"You can only sell up to {inventory_qty} units of {selected_good}.", color='yellow')
await self.sell(selected_good) # Reprompt for quantity
return
# Proceed with selling
revenue = price * quantity
self.player.money += revenue
self.player.remove_cargo(selected_good, quantity)
self.current_market.supply[selected_good] += quantity
self.current_market.demand[selected_good] -= quantity * 0.3
await slow_print(f"Sold {quantity} units of {selected_good} for ${revenue}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def handle_upgrade_confirmation(self, command):
"""Handles input specifically for upgrade confirmation."""
if command.lower() == 'y':
await self.player.upgrade_cargo()
else:
await slow_print("Cargo upgrade canceled.", color='yellow')
self.input_mode = "GENERAL_COMMAND"
# Only advance the turn if the upgrade was successful
if self.game_over:
return
self.turn_counter +=1
await self.game_turn()
async def choose_difficulty(self):
"""Prompts the player to choose a difficulty level."""
self.input_mode = "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()}")
await fast_print(f"Enter the number corresponding to your choice (1-{len(difficulties)}): ")
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()
# Input mode is set to DIFFICULTY_SELECTION, awaiting user input via the event handler
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()
await fast_print("Enter command (BUY/SELL/TRAVEL/STATUS/UPGRADE/OVERVIEW/HELP/EXIT): ")
self.input_mode = "GENERAL_COMMAND"
async def process_command(self, command):
"""Processes user command received from input."""
command = command.strip().lower()
if self.input_mode != "GENERAL_COMMAND":
# If not in general command mode, ignore
return
if command == "buy":
await self.buy_command()
elif command == "sell":
await self.sell_command()
elif command == "travel":
await self.travel_command()
elif command == "status":
await self.player.status()
elif command == "upgrade":
await self.upgrade_command()
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!", color='yellow')
await self.end_game()
self.game_over = True
return
else:
await fast_print("Invalid command.", color='red')
# Do not advance the turn for invalid commands
code
# Only advance the turn if the command requires it
if command in ["buy", "sell", "travel", "upgrade"]:
# It is assumed that the sub-commands handle the turn advancement
pass # The turn is advanced in the respective handlers
else:
# Advance the turn for commands that don't require additional input
self.turn_counter +=1
await self.game_turn()
async def buy_command(self):
"""Handles the BUY command."""
goods_list = list(GOODS.keys())
await fast_print("Available goods to buy:")
for idx, good in enumerate(goods_list, 1):
await fast_print(f"{idx}. {good}")
await fast_print("Enter the number of the good you want to buy:")
self.input_mode = "BUY_SELECTION"
async def buy(self, selected_good):
"""Handles the buying process for the player with a pre-selected good."""
await fast_print(f"You selected: {selected_good}", color='yellow')
price = self.current_market.prices[selected_good]
await fast_print(f"Price per unit: ${price}")
await fast_print("Enter the quantity to buy:")
self.input_mode = "BUY_QUANTITY"
async def sell_command(self):
"""Handles the SELL command."""
goods_with_inventory = [good for good, qty in self.player.inventory.items() if qty > 0]
if not goods_with_inventory:
await fast_print("You have no goods to sell.", color='yellow')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
return
await fast_print("Available goods to sell:")
for idx, good in enumerate(goods_with_inventory, 1):
await fast_print(f"{idx}. {good}")
await fast_print("Enter the number of the good you want to sell:")
self.input_mode = "SELL_SELECTION"
async def sell(self, selected_good):
"""Handles the selling process for the player with a pre-selected good."""
await fast_print(f"You selected: {selected_good}", color='yellow')
price = self.current_market.prices[selected_good]
await fast_print(f"Price per unit: ${price}")
await fast_print("Enter the quantity to sell:")
self.input_mode = "SELL_QUANTITY"
async def travel_command(self):
"""Handles the TRAVEL command."""
available_towns = [town for town in TOWNS if town != self.player.location]
await fast_print("Available towns to travel to:")
for idx, town in enumerate(available_towns, 1):
await fast_print(f"{idx}. {town}")
await fast_print("Enter the number of the town you want to travel to:")
self.input_mode = "TRAVEL_SELECTION"
async def upgrade_command(self):
"""Handles the UPGRADE command."""
await fast_print("Upgrade Cargo Capacity:", color='yellow')
await slow_print("Upgrade cargo capacity by 50 units for 500 gold? (Y/N): ", color='yellow')
self.input_mode = "UPGRADE_CONFIRMATION"
async def buy_quantity_handler(self, command):
"""Handles the quantity input for buying."""
selected_good = self.selected_buy_good
price = self.current_market.prices[selected_good]
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
cost = price * quantity
can_afford = self.player.money >= cost
available_cargo_space = self.player.max_cargo - self.player.current_cargo
max_cargo_quantity = available_cargo_space // GOODS[selected_good]["weight"]
available_supply = int(self.current_market.supply[selected_good])
max_buyable = min(self.player.money // price, max_cargo_quantity, available_supply)
if quantity > max_buyable:
if max_buyable == 0:
await fast_print("You cannot buy any units of this good due to insufficient funds, cargo space, or supply.", color='red')
else:
await fast_print(f"You can only buy up to {max_buyable} units of {selected_good}.", color='yellow')
await self.buy(selected_good) # Reprompt for quantity
return
# Proceed with buying
self.player.money -= cost
self.player.add_cargo(selected_good, quantity)
self.current_market.supply[selected_good] -= quantity
self.current_market.demand[selected_good] += quantity * 0.3
await slow_print(f"Bought {quantity} units of {selected_good} for ${cost}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def sell_quantity_handler(self, command):
"""Handles the quantity input for selling."""
selected_good = self.selected_sell_good
price = self.current_market.prices[selected_good]
inventory_qty = self.player.inventory[selected_good]
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.sell(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.sell(selected_good) # Reprompt for quantity
return
if quantity > inventory_qty:
await fast_print(f"You can only sell up to {inventory_qty} units of {selected_good}.", color='yellow')
await self.sell(selected_good) # Reprompt for quantity
return
# Proceed with selling
revenue = price * quantity
self.player.money += revenue
self.player.remove_cargo(selected_good, quantity)
self.current_market.supply[selected_good] += quantity
self.current_market.demand[selected_good] -= quantity * 0.3
await slow_print(f"Sold {quantity} units of {selected_good} for ${revenue}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def handle_upgrade_confirmation(self, command):
"""Handles input specifically for upgrade confirmation."""
if command.lower() == 'y':
await self.player.upgrade_cargo()
elif command.lower() == 'n':
await slow_print("Cargo upgrade canceled.", color='yellow')
else:
await fast_print("Invalid input. Please enter Y or N.", color='red')
await self.upgrade_command() # Reprompt for confirmation
return
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def choose_difficulty(self):
"""Prompts the player to choose a difficulty level."""
self.input_mode = "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()}")
await fast_print(f"Enter the number corresponding to your choice (1-{len(difficulties)}): ")
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()
# Input mode is set to DIFFICULTY_SELECTION, awaiting user input via the event handler
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()
await fast_print("Enter command (BUY/SELL/TRAVEL/STATUS/UPGRADE/OVERVIEW/HELP/EXIT): ")
self.input_mode = "GENERAL_COMMAND"
async def process_command(self, command):
"""Processes user command received from input."""
command = command.strip().lower()
if self.input_mode != "GENERAL_COMMAND":
# If not in general command mode, ignore
return
if command == "buy":
await self.buy_command()
elif command == "sell":
await self.sell_command()
elif command == "travel":
await self.travel_command()
elif command == "status":
await self.player.status()
self.turn_counter +=1
await self.game_turn()
return
elif command == "upgrade":
await self.upgrade_command()
elif command == "overview":
await self.market_overview()
self.turn_counter +=1
await self.game_turn()
return
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')
self.turn_counter +=1
await self.game_turn()
return
elif command == "exit":
await slow_print("Thank you for playing!", color='yellow')
await self.end_game()
self.game_over = True
return
else:
await fast_print("Invalid command.", color='red')
# Do not advance the turn for invalid commands
await self.game_turn()
return
code
# Only advance the turn if the command requires it
if command in ["buy", "sell", "travel", "upgrade"]:
# The turn is advanced in the respective handlers
pass # Do nothing here
else:
# Advance the turn for commands that don't require additional input
self.turn_counter +=1
await self.game_turn()
async def buy_command(self):
"""Handles the BUY command."""
goods_list = list(GOODS.keys())
await fast_print("Available goods to buy:")
for idx, good in enumerate(goods_list, 1):
await fast_print(f"{idx}. {good}")
await fast_print("Enter the number of the good you want to buy:")
self.input_mode = "BUY_SELECTION"
async def buy(self, selected_good):
"""Handles the buying process for the player with a pre-selected good."""
await fast_print(f"You selected: {selected_good}", color='yellow')
price = self.current_market.prices[selected_good]
await fast_print(f"Price per unit: ${price}")
await fast_print("Enter the quantity to buy:")
self.input_mode = "BUY_QUANTITY"
async def sell_command(self):
"""Handles the SELL command."""
goods_with_inventory = [good for good, qty in self.player.inventory.items() if qty > 0]
if not goods_with_inventory:
await fast_print("You have no goods to sell.", color='yellow')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
return
await fast_print("Available goods to sell:")
for idx, good in enumerate(goods_with_inventory, 1):
await fast_print(f"{idx}. {good}")
await fast_print("Enter the number of the good you want to sell:")
self.input_mode = "SELL_SELECTION"
async def sell(self, selected_good):
"""Handles the selling process for the player with a pre-selected good."""
await fast_print(f"You selected: {selected_good}", color='yellow')
price = self.current_market.prices[selected_good]
await fast_print(f"Price per unit: ${price}")
await fast_print("Enter the quantity to sell:")
self.input_mode = "SELL_QUANTITY"
async def travel_command(self):
"""Handles the TRAVEL command."""
available_towns = [town for town in TOWNS if town != self.player.location]
await fast_print("Available towns to travel to:")
for idx, town in enumerate(available_towns, 1):
await fast_print(f"{idx}. {town}")
await fast_print("Enter the number of the town you want to travel to:")
self.input_mode = "TRAVEL_SELECTION"
async def upgrade_command(self):
"""Handles the UPGRADE command."""
await fast_print("Upgrade Cargo Capacity:", color='yellow')
await slow_print("Upgrade cargo capacity by 50 units for 500 gold? (Y/N): ", color='yellow')
self.input_mode = "UPGRADE_CONFIRMATION"
async def buy_quantity_handler(self, command):
"""Handles the quantity input for buying."""
selected_good = self.selected_buy_good
price = self.current_market.prices[selected_good]
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
cost = price * quantity
can_afford = self.player.money >= cost
available_cargo_space = self.player.max_cargo - self.player.current_cargo
max_cargo_quantity = available_cargo_space // GOODS[selected_good]["weight"]
available_supply = int(self.current_market.supply[selected_good])
max_buyable = min(self.player.money // price, max_cargo_quantity, available_supply)
if quantity > max_buyable:
if max_buyable == 0:
await fast_print("You cannot buy any units of this good due to insufficient funds, cargo space, or supply.", color='red')
else:
await fast_print(f"You can only buy up to {max_buyable} units of {selected_good}.", color='yellow')
await self.buy(selected_good) # Reprompt for quantity
return
# Proceed with buying
self.player.money -= cost
self.player.add_cargo(selected_good, quantity)
self.current_market.supply[selected_good] -= quantity
self.current_market.demand[selected_good] += quantity * 0.3
await slow_print(f"Bought {quantity} units of {selected_good} for ${cost}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def sell_quantity_handler(self, command):
"""Handles the quantity input for selling."""
selected_good = self.selected_sell_good
price = self.current_market.prices[selected_good]
inventory_qty = self.player.inventory[selected_good]
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.sell(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.sell(selected_good) # Reprompt for quantity
return
if quantity > inventory_qty:
await fast_print(f"You can only sell up to {inventory_qty} units of {selected_good}.", color='yellow')
await self.sell(selected_good) # Reprompt for quantity
return
# Proceed with selling
revenue = price * quantity
self.player.money += revenue
self.player.remove_cargo(selected_good, quantity)
self.current_market.supply[selected_good] += quantity
self.current_market.demand[selected_good] -= quantity * 0.3
await slow_print(f"Sold {quantity} units of {selected_good} for ${revenue}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
async def handle_upgrade_confirmation(self, command):
"""Handles input specifically for upgrade confirmation."""
if command.lower() == 'y':
await self.player.upgrade_cargo()
elif command.lower() == 'n':
await slow_print("Cargo upgrade canceled.", color='yellow')
else:
await fast_print("Invalid input. Please enter Y or N.", color='red')
await self.upgrade_command() # Reprompt for confirmation
return
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
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("")
# Do not advance the turn here; user can continue their turn after viewing overview
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'))
def on_input(event):
if event.key == 'Enter' and not event.shiftKey:
event.preventDefault()
# Correctly create and dispatch the CustomEvent
custom_event = CustomEvent.new('input-received', {'detail': user_input.value.strip()})
document.dispatchEvent(custom_event)
user_input.value = ''
user_input.disabled = True
user_input.placeholder = 'Enter your input...'
user_input.addEventListener('keypress', on_input, {'once': True})
return
To display the maximum quantity a player can buy based on their available money, cargo capacity, and the market's supply, you'll need to modify the buy method within the Game class in your PyScript section. This enhancement will inform players of their buying limits upfront, improving the user experience and preventing frustration from attempting invalid purchases.
Below are the steps and the modified code to implement this feature:
Calculate the Maximum Buyable Quantity:
Based on Money: Determine how many units the player can afford for the selected good.
Based on Cargo Capacity: Calculate how many units the player can carry given their remaining cargo space and the weight of the selected good.
Based on Market Supply: Consider the available supply of the selected good in the current market.
The maximum buyable quantity is the smallest of these three values.
Display the Maximum Quantity:
Inform the player of this limit before prompting them to enter the quantity they wish to buy.
Prevent Invalid Purchases:
Ensure that players cannot enter a quantity exceeding this limit.
Modified PyScript Code
Below is the updated buy method and related handler within your Game class. This code calculates and displays the maximum buyable quantity to the player.
python
class Game:
"""Represents the main game loop and logic."""
# ... [other parts of the Game class remain unchanged]
async def buy(self, selected_good):
"""Handles the buying process for the player with a pre-selected good."""
await fast_print(f"You selected: {selected_good}", color='yellow')
price = self.current_market.prices[selected_good]
await fast_print(f"Price per unit: ${price}")
# Calculate maximum buyable based on money
max_affordable = self.player.money // price
# Calculate maximum buyable based on cargo space
remaining_cargo = self.player.max_cargo - self.player.current_cargo
good_weight = GOODS[selected_good]["weight"]
max_cargo_quantity = remaining_cargo // good_weight
# Available supply in the market
available_supply = int(self.current_market.supply[selected_good])
# Determine the maximum buyable quantity
max_buyable = min(max_affordable, max_cargo_quantity, available_supply)
if max_buyable == 0:
await slow_print(
f"You cannot buy any units of {selected_good} due to insufficient funds, cargo space, or supply.",
color='red'
)
self.input_mode = "GENERAL_COMMAND"
self.turn_counter += 1
await self.game_turn()
return
await slow_print(
f"You can buy up to {max_buyable} units of {selected_good}.",
color='yellow'
)
await fast_print("Enter the quantity you want to buy:")
self.input_mode = "BUY_QUANTITY"
async def buy_quantity_handler(self, command):
"""Handles the quantity input for buying."""
selected_good = self.selected_buy_good
price = self.current_market.prices[selected_good]
# Calculate maximum buyable based on money
max_affordable = self.player.money // price
# Calculate maximum buyable based on cargo space
remaining_cargo = self.player.max_cargo - self.player.current_cargo
good_weight = GOODS[selected_good]["weight"]
max_cargo_quantity = remaining_cargo // good_weight
# Available supply in the market
available_supply = int(self.current_market.supply[selected_good])
# Determine the maximum buyable quantity
max_buyable = min(max_affordable, max_cargo_quantity, available_supply)
if not command.isdigit():
await fast_print("Invalid input. Please enter a number.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
quantity = int(command)
if quantity <= 0:
await fast_print("Quantity must be at least 1.", color='red')
await self.buy(selected_good) # Reprompt for quantity
return
if quantity > max_buyable:
if max_buyable == 0:
await fast_print(
"You cannot buy any units of this good due to insufficient funds, cargo space, or supply.",
color='red'
)
else:
await fast_print(
f"You can only buy up to {max_buyable} units of {selected_good}.",
color='yellow'
)
await self.buy(selected_good) # Reprompt for quantity
return
# Proceed with buying
cost = price * quantity
self.player.money -= cost
self.player.add_cargo(selected_good, quantity)
self.current_market.supply[selected_good] -= quantity
self.current_market.demand[selected_good] += quantity * 0.3
await slow_print(f"Bought {quantity} units of {selected_good} for ${cost}.", color='green')
self.input_mode = "GENERAL_COMMAND"
self.turn_counter +=1
await self.game_turn()
# ... [rest of the Game class]
Explanation of Changes
Calculating Maximum Buyable Quantity:
max_affordable: Determines the maximum number of units the player can afford based on their current money.
max_cargo_quantity: Determines the maximum number of units the player can carry based on remaining cargo space and the weight of the selected good.
available_supply: Retrieves the available supply of the selected good in the current market.
max_buyable: The smallest of the above three values is the maximum number of units the player can buy.
Displaying the Limit:
The player is informed of the maximum quantity they can buy before entering the quantity.
If max_buyable is 0, the player is informed that they cannot buy any units of the selected good due to constraints.
Handling Invalid Quantities:
If the player enters a quantity greater than max_buyable, they're prompted with the maximum allowable quantity and asked to re-enter their choice.
Updating Handlers:
Both the buy method and the buy_quantity_handler now calculate and consider max_buyable, ensuring consistency and preventing invalid purchases.
Final Notes
Duplicate Code Alert: It's noticeable that in your original code, the Game class methods like buy_quantity_handler and handle_upgrade_confirmation are defined multiple times. Ensure that each method is defined only once to prevent unexpected behavior.
Consistent User Feedback: By informing players of their buying limits upfront, you enhance the game's usability and make the trading experience smoother.
Further Enhancements: You might consider adding visual indicators or confirmations after purchases to reinforce player actions and game states.
Implementing these changes will ensure that players are fully aware of their purchasing capabilities at any point in the game, making for a more engaging and user-friendly trading experience.