This commit is contained in:
reinoud 2025-07-29 20:45:24 +02:00
parent 4ea7f8c32d
commit 7441f67809

177
crypto.py
View file

@ -1,22 +1,19 @@
import random import random
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from colorama import Fore, Style, init from colorama import Fore, Style, init
init(autoreset=True) # Auto-reset color after each print init(autoreset=True)
import os import os
os.system('cls' if os.name == 'nt' else 'clear') # Clear screen on start os.system('cls' if os.name == 'nt' else 'clear')
cryptos = { cryptos = {
"Bitcoin": {"price": 100.0, "sensitivity": 0.5, "volatility": 0.0, "total_supply": 1000.0, "price_history": [100.0]}, "Bitcoin": {"price": 1427.3, "sensitivity": 0.4, "volatility": 0.19, "price_history": [100.0]},
"Ethereum": {"price": 50.0, "sensitivity": 0.3, "volatility": 0.0, "total_supply": 1500.0, "price_history": [50.0]}, "Ethereum": {"price": 690.1, "sensitivity": 0.6, "volatility": 0.24, "price_history": [50.0]},
"Dodge": {"price": 42.9, "sensitivity": 0.9, "volatility": 0.4, "price_history": [50.0]},
} }
users = {} users = {}
def available_supply(coin):
owned = sum(user['coins'].get(coin, 0.0) for user in users.values())
return max(0.0, cryptos[coin]["total_supply"] - owned)
def save_graph(coin): def save_graph(coin):
plt.clf() plt.clf()
plt.plot(cryptos[coin]["price_history"], label=f"{coin} Price") plt.plot(cryptos[coin]["price_history"], label=f"{coin} Price")
@ -34,7 +31,7 @@ def total_value(user):
# Intro # Intro
print(Fore.YELLOW + Style.BRIGHT + "💰 Welcome to Crypto Kids Multiplayer — Multi-Coin Edition!") print(Fore.YELLOW + Style.BRIGHT + "💰 Welcome to Crypto Kids Multiplayer — Multi-Coin Edition!")
print(Style.DIM + "🎮 Register users, then trade Bitcoin and Ethereum in turn-based rounds.\n") print(Style.DIM + "🎮 Register users, then trade Bitcoin, Ethereum, or Dodge in turn-based rounds.\n")
# Register Users # Register Users
while True: while True:
@ -50,94 +47,102 @@ while True:
else: else:
print(Fore.BLUE + f"👋 Welcome back, {user_input}!") print(Fore.BLUE + f"👋 Welcome back, {user_input}!")
usernames = list(users.keys()) print(Fore.YELLOW + "\n🎬 Game started! Trade using +amount to buy or -amount to sell. Type 'done' to end your turn, or 'exit' to quit.\n")
turn = 0
print(Fore.YELLOW + "\n🎬 Game started! Trade using +amount to buy or -amount to sell. Type 'exit' to quit.\n")
# Main Game Loop # Main Game Loop
while True: while True:
# Display all users' holdings before each turn print(Fore.LIGHTMAGENTA_EX + "\n🔀 NEW ROUND — Set the trading order")
print(Fore.LIGHTWHITE_EX + "\n📊 CURRENT STANDINGS") print(Fore.CYAN + f"Registered players: {', '.join(users.keys())}")
print("="*40) while True:
for uname, data in users.items(): turn_input = input(Fore.YELLOW + "Enter usernames in desired order (space-separated): ").strip().split()
print(Fore.LIGHTCYAN_EX + f"👤 {uname}:") if set(turn_input) == set(users.keys()):
print(f" 💼 Cash: {Fore.GREEN}${data['cash']:.2f}") turn_order = turn_input
for c in cryptos: break
print(f" 🪙 {c}: {Fore.YELLOW}{data['coins'][c]:.2f}") else:
print(f" 📈 Total Value: {Fore.CYAN}${total_value(data):.2f}\n") print(Fore.RED + "⚠️ Invalid order. Must include all registered users.")
username = usernames[turn % len(usernames)] for username in turn_order:
user = users[username] user = users[username]
print(Fore.LIGHTWHITE_EX + "\n" + "="*40) print(Fore.LIGHTWHITE_EX + "\n📊 CURRENT STANDINGS")
print(Fore.CYAN + f"🔁 {username.upper()}'S TURN") print("="*40)
print(Fore.LIGHTWHITE_EX + "="*40)
print(f"💼 Cash: {Fore.GREEN}${user['cash']:.2f}")
print("🪙 Your Holdings:")
for coin in cryptos:
print(f" - {Fore.YELLOW}{coin}: {user['coins'][coin]:.2f}")
coin = input(Fore.CYAN + f"\nSelect a coin to trade {list(cryptos.keys())}: ").strip()
if coin not in cryptos:
print(Fore.RED + "⚠️ Invalid coin selection.")
continue
price = cryptos[coin]["price"]
supply = available_supply(coin)
print(Fore.LIGHTBLUE_EX + f"\n📈 {coin} Price: ${price:.2f}")
print(f"📊 Supply Available: {supply:.2f} / {cryptos[coin]['total_supply']:.0f}")
user_input = input(Fore.CYAN + f"Enter trade amount for {coin} (e.g., +10 or -5), or 'exit': ").strip()
if user_input.lower() == "exit":
print(Fore.YELLOW + "\n📉 GAME OVER — FINAL BALANCES:\n")
for uname, data in users.items(): for uname, data in users.items():
print(Fore.LIGHTWHITE_EX + f"👤 {uname}:") print(Fore.LIGHTCYAN_EX + f"👤 {uname}:")
print(f" 💼 Cash: {Fore.GREEN}${data['cash']:.2f}") print(f" 💼 Cash: {Fore.GREEN}${data['cash']:.2f}")
for c in cryptos: for c in cryptos:
print(f" 🪙 {c}: {Fore.YELLOW}{data['coins'][c]:.2f}") print(f" 🪙 {c}: {data['coins'][c]:.2f}")
print(f" 📈 Total Value: {Fore.CYAN}${total_value(data):.2f}\n") print(f" 📈 Total Value: {Fore.CYAN}${total_value(data):.2f}\n")
break
try: print(Fore.LIGHTWHITE_EX + "\n" + "="*40)
trade_amount = int(user_input) print(Fore.CYAN + f"🔁 {username.upper()}'S TURN")
except ValueError: print(Fore.LIGHTWHITE_EX + "="*40)
print(Fore.RED + "⚠️ Invalid input format. Use +10 or -5.")
continue
# Buy coin_trades = []
if trade_amount > 0:
if supply < trade_amount:
print(Fore.RED + "❌ Not enough coins available.")
continue
cost = trade_amount * price
if user["cash"] >= cost:
user["cash"] -= cost
user["coins"][coin] += trade_amount
print(Fore.GREEN + f"✅ Bought {trade_amount} {coin} for ${cost:.2f}")
else:
print(Fore.RED + "❌ Not enough cash.")
continue
# Sell while True:
elif trade_amount < 0: print(f"💼 Cash: {Fore.GREEN}${user['cash']:.2f}")
sell_amt = -trade_amount print("🪙 Your Holdings:")
if user["coins"][coin] >= sell_amt: for coin in cryptos:
user["coins"][coin] -= sell_amt print(f" - {Fore.YELLOW}{coin}: {user['coins'][coin]:.2f}")
user["cash"] += sell_amt * price
print(Fore.GREEN + f"✅ Sold {sell_amt} {coin} for ${sell_amt * price:.2f}")
else:
print(Fore.RED + "❌ Not enough coins.")
continue
# Price Update coin = input(Fore.CYAN + f"\nSelect a coin to trade {list(cryptos.keys())} (or type 'done' to finish turn): ").strip()
net_demand = trade_amount if coin.lower() == "done":
crypto = cryptos[coin] break
price_change = net_demand * crypto["sensitivity"] if coin.lower() == "exit":
randomness = random.uniform(-crypto["volatility"], crypto["volatility"]) * crypto["price"] print(Fore.YELLOW + "\n📉 GAME OVER — FINAL BALANCES:\n")
new_price = crypto["price"] + price_change + randomness for uname, data in users.items():
crypto["price"] = max(1.0, new_price) print(Fore.LIGHTWHITE_EX + f"👤 {uname}:")
crypto["price_history"].append(crypto["price"]) print(f" 💼 Cash: {Fore.GREEN}${data['cash']:.2f}")
for c in cryptos:
print(f" 🪙 {c}: {Fore.YELLOW}{data['coins'][c]:.2f}")
print(f" 📈 Total Value: {Fore.CYAN}${total_value(data):.2f}\n")
exit()
if coin not in cryptos:
print(Fore.RED + "⚠️ Invalid coin selection.")
continue
save_graph(coin) price = cryptos[coin]["price"]
turn += 1 print(Fore.LIGHTBLUE_EX + f"\n📈 {coin} Price: ${price:.2f}")
user_input = input(Fore.CYAN + f"Enter trade amount for {coin} (e.g., +10 or -5): ").strip()
try:
trade_amount = int(user_input)
except ValueError:
print(Fore.RED + "⚠️ Invalid input format. Use +10 or -5.")
continue
if trade_amount > 0:
cost = trade_amount * price
if user["cash"] >= cost:
user["cash"] -= cost
user["coins"][coin] += trade_amount
print(Fore.GREEN + f"✅ Bought {trade_amount} {coin} for ${cost:.2f}")
coin_trades.append((coin, trade_amount))
else:
print(Fore.RED + "❌ Not enough cash.")
continue
elif trade_amount < 0:
sell_amt = -trade_amount
if user["coins"][coin] >= sell_amt:
user["coins"][coin] -= sell_amt
user["cash"] += sell_amt * price
print(Fore.GREEN + f"✅ Sold {sell_amt} {coin} for ${sell_amt * price:.2f}")
coin_trades.append((coin, trade_amount))
else:
print(Fore.RED + "❌ Not enough coins.")
continue
# Update price for each coin traded this turn
updated_coins = set()
for coin, trade_amount in coin_trades:
if coin in updated_coins:
continue # Avoid multiple updates per coin per turn
crypto = cryptos[coin]
price_change = trade_amount * crypto["sensitivity"]
randomness = random.uniform(-crypto["volatility"], crypto["volatility"]) * crypto["price"]
new_price = crypto["price"] + price_change + randomness
crypto["price"] = max(1.0, new_price)
crypto["price_history"].append(crypto["price"])
save_graph(coin)
updated_coins.add(coin)