ii
This commit is contained in:
parent
a2dc8a3c5e
commit
4ea7f8c32d
1 changed files with 119 additions and 33 deletions
152
crypto.py
152
crypto.py
|
@ -1,57 +1,143 @@
|
||||||
import random
|
import random
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
from colorama import Fore, Style, init
|
||||||
|
init(autoreset=True) # Auto-reset color after each print
|
||||||
|
|
||||||
# Game parameters
|
import os
|
||||||
coin_price = 100.0
|
os.system('cls' if os.name == 'nt' else 'clear') # Clear screen on start
|
||||||
price_sensitivity = 0.5
|
|
||||||
volatility = 0.3
|
|
||||||
price_history = [coin_price]
|
|
||||||
trade_history = [0] # User's buy/sell behavior per turn
|
|
||||||
cumulative_trades = [0] # Net amount of coins user holds over time
|
|
||||||
|
|
||||||
def save_graph():
|
cryptos = {
|
||||||
|
"Bitcoin": {"price": 100.0, "sensitivity": 0.5, "volatility": 0.0, "total_supply": 1000.0, "price_history": [100.0]},
|
||||||
|
"Ethereum": {"price": 50.0, "sensitivity": 0.3, "volatility": 0.0, "total_supply": 1500.0, "price_history": [50.0]},
|
||||||
|
}
|
||||||
|
|
||||||
|
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):
|
||||||
plt.clf()
|
plt.clf()
|
||||||
plt.plot(price_history, label="Coin Price", color='blue')
|
plt.plot(cryptos[coin]["price_history"], label=f"{coin} Price")
|
||||||
plt.plot(trade_history, label="Trade Behavior", color='orange')
|
plt.title(f"{coin} Price Over Time")
|
||||||
plt.plot(cumulative_trades, label="Net Coins Held", color='green')
|
|
||||||
plt.title("Coin Price, Trade Behavior & Net Holdings Over Time")
|
|
||||||
plt.xlabel("Turn")
|
plt.xlabel("Turn")
|
||||||
plt.ylabel("Value")
|
plt.ylabel("Price")
|
||||||
plt.legend()
|
plt.legend()
|
||||||
plt.grid(True)
|
plt.grid(True)
|
||||||
plt.savefig("coin_price.png")
|
filename = f"{coin.lower()}_price.png"
|
||||||
print("📊 Graph saved as 'coin_price.png'")
|
plt.savefig(filename)
|
||||||
|
print(Fore.MAGENTA + f"📊 Graph saved as '{filename}'")
|
||||||
|
|
||||||
print("💰 Welcome to Crypto Kids! Type +10 to buy or -10 to sell.")
|
def total_value(user):
|
||||||
print("Type 'exit' to stop the game.\n")
|
return user["cash"] + sum(user["coins"].get(c, 0.0) * cryptos[c]["price"] for c in cryptos)
|
||||||
|
|
||||||
|
# Intro
|
||||||
|
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")
|
||||||
|
|
||||||
|
# Register Users
|
||||||
while True:
|
while True:
|
||||||
print(f"\nCurrent Coin Price: {round(coin_price, 2)}")
|
user_input = input(Fore.CYAN + "Enter username to register/login (or type 'start' to begin): ").strip()
|
||||||
|
if user_input.lower() == "start":
|
||||||
|
if not users:
|
||||||
|
print(Fore.RED + "⚠️ Add at least one user to begin.")
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
if user_input not in users:
|
||||||
|
users[user_input] = {"cash": 1000.0, "coins": {coin: 0.0 for coin in cryptos}}
|
||||||
|
print(Fore.GREEN + f"🆕 User '{user_input}' registered with $1000 cash.")
|
||||||
|
else:
|
||||||
|
print(Fore.BLUE + f"👋 Welcome back, {user_input}!")
|
||||||
|
|
||||||
user_input = input("Enter buy/sell amount (e.g., +10 or -10): ").strip()
|
usernames = list(users.keys())
|
||||||
|
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
|
||||||
|
while True:
|
||||||
|
# Display all users' holdings before each turn
|
||||||
|
print(Fore.LIGHTWHITE_EX + "\n📊 CURRENT STANDINGS")
|
||||||
|
print("="*40)
|
||||||
|
for uname, data in users.items():
|
||||||
|
print(Fore.LIGHTCYAN_EX + f"👤 {uname}:")
|
||||||
|
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")
|
||||||
|
|
||||||
|
username = usernames[turn % len(usernames)]
|
||||||
|
user = users[username]
|
||||||
|
print(Fore.LIGHTWHITE_EX + "\n" + "="*40)
|
||||||
|
print(Fore.CYAN + f"🔁 {username.upper()}'S TURN")
|
||||||
|
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":
|
if user_input.lower() == "exit":
|
||||||
print("👋 Game Over. Thanks for playing!")
|
print(Fore.YELLOW + "\n📉 GAME OVER — FINAL BALANCES:\n")
|
||||||
|
for uname, data in users.items():
|
||||||
|
print(Fore.LIGHTWHITE_EX + f"👤 {uname}:")
|
||||||
|
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")
|
||||||
break
|
break
|
||||||
|
|
||||||
try:
|
try:
|
||||||
trade_amount = int(user_input)
|
trade_amount = int(user_input)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
print("⚠️ Please enter a valid number like +10 or -5.")
|
print(Fore.RED + "⚠️ Invalid input format. Use +10 or -5.")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
trade_history.append(trade_amount)
|
# Buy
|
||||||
new_total = cumulative_trades[-1] + trade_amount
|
if trade_amount > 0:
|
||||||
cumulative_trades.append(new_total)
|
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
|
||||||
|
|
||||||
buys = trade_amount if trade_amount > 0 else 0
|
# Sell
|
||||||
sells = -trade_amount if trade_amount < 0 else 0
|
elif trade_amount < 0:
|
||||||
net_demand = buys - sells
|
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}")
|
||||||
|
else:
|
||||||
|
print(Fore.RED + "❌ Not enough coins.")
|
||||||
|
continue
|
||||||
|
|
||||||
price_change_from_demand = net_demand * price_sensitivity
|
# Price Update
|
||||||
random_factor = random.uniform(-volatility, volatility) * coin_price
|
net_demand = trade_amount
|
||||||
coin_price += price_change_from_demand + random_factor
|
crypto = cryptos[coin]
|
||||||
coin_price = max(1, coin_price)
|
price_change = net_demand * 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"])
|
||||||
|
|
||||||
price_history.append(coin_price)
|
save_graph(coin)
|
||||||
save_graph()
|
turn += 1
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue