Compare commits

...

13 Commits

Author SHA1 Message Date
minecartchris
11413efe69 added the options to not auto score save 2026-01-02 02:47:07 -06:00
minecartchris
321277fa56 fixed my local git server 2026-01-02 02:26:09 -06:00
2aa087ecdd Update bots/httpTest.py 2025-12-13 17:04:46 -05:00
0b510393f4 Update static/style.css 2025-12-12 16:13:00 -05:00
21765f2b0b Update templates/index.html 2025-12-12 16:12:47 -05:00
6365882d00 Update static/game.js 2025-12-12 16:12:31 -05:00
a59c2c5919 Update mainweb.py 2025-12-12 16:12:13 -05:00
1946cc515a Upload files to "bots" 2025-12-12 12:54:49 -05:00
d8dc4f1c87 Merge pull request 'minecartchris-markdown' (#1) from minecartchris-markdown into main
Reviewed-on: minecartchris/Stock-Game#1
2025-12-11 12:36:02 -05:00
b5a0394c7b Update readme.md 2025-12-11 12:34:56 -05:00
Maple Redleaf
fda8122213 Update readme.md formatting 2025-12-11 11:21:07 -06:00
96f632e1eb Update readme.md 2025-12-11 11:55:56 -05:00
45aa453c69 Add readme.md 2025-12-11 11:54:49 -05:00
8 changed files with 2370 additions and 891 deletions

175
httpTest.py Normal file
View File

@@ -0,0 +1,175 @@
import requests
import time
import webbrowser
BASE_URL = 'https://stock.minecartchris.cc'
log_file = "tradeLog.txt"
dayRun = 100
saveScore = False
asked = input("Do you want to save the score? (y/n): ")
if asked.lower() == 'y':
saveScore = True
else:
saveScore = False
# webbrowser.get('firefox').open(BASE_URL)
# Create a session object to maintain cookies/session across requests
session = requests.Session()
def log(message):
"""Print to console and write to file"""
print(message)
if log_file:
log_file.write(message + '\n')
log_file.flush()
def find_cheapest_stock(stocks):
cheapest = min(stocks, key=lambda s: s['price'])
return cheapest
def get_holding_amount(holdings, stock_id):
for h in holdings:
if h['id'] == stock_id:
return h['amount']
return 0
def wait_for_server():
for i in range(30):
try:
session.get(f'{BASE_URL}/api/game-state', timeout=1)
return True
except:
log(f"Waiting for server... ({i+1}/10)")
return False
def main():
global log_file
log_file = open('tradeLog.txt', 'w')
if not wait_for_server():
log("Server not available!")
log_file.close()
return
response = session.post(f'{BASE_URL}/api/start', json={'days': dayRun})
if response.status_code != 200:
log(f"Error starting game: {response.status_code} - {response.text}")
log_file.close()
return
data = response.json()
log("Game started!")
log(f"Balance: ${data['balance']}")
cheapest = find_cheapest_stock(data['stocks'])
log(f"\nCheapest stock: {cheapest['name']} at ${cheapest['price']}")
shares_to_buy = data['balance'] // cheapest['price']
if shares_to_buy > 0:
response = session.post(f'{BASE_URL}/api/buy',
json={
'stock_id': cheapest['id'],
'amount': shares_to_buy
})
if response.status_code != 200:
log(f"Error buying stock: {response.status_code} - {response.text}")
log_file.close()
return
data = response.json()
log(f"Bought {shares_to_buy} shares of {cheapest['name']}")
#log(f"Balance: ${data['balance']}")
current_stock_id = cheapest['id']
while data['daysleft'] > 0:
response = session.post(f'{BASE_URL}/api/next-day')
if response.status_code != 200:
log(f"Error on next day: {response.status_code} - {response.text}")
break
data = response.json()
log(f"\n--- Day {data['day']} ---")
new_cheapest = find_cheapest_stock(data['stocks'])
log(f"Cheapest stock now: {new_cheapest['name']} at ${new_cheapest['price']}")
if new_cheapest['id'] != current_stock_id:
log(f"Different stock is cheaper! Switching...")
current_holdings = get_holding_amount(data['holdings'], current_stock_id)
if current_holdings > 0:
response = session.post(f'{BASE_URL}/api/sell',
json={
'stock_id': current_stock_id,
'amount': current_holdings
})
if response.status_code != 200:
log(f"Error selling stock: {response.status_code} - {response.text}")
break
data = response.json()
log(f"Sold {current_holdings} shares")
log(f"Balance: ${data['balance']}")
shares_to_buy = data['balance'] // new_cheapest['price']
if shares_to_buy > 0:
response = session.post(f'{BASE_URL}/api/buy',
json={
'stock_id': new_cheapest['id'],
'amount': shares_to_buy
})
if response.status_code != 200:
log(f"Error buying stock: {response.status_code} - {response.text}")
break
data = response.json()
log(f"Bought {shares_to_buy} shares of {new_cheapest['name']}")
current_stock_id = new_cheapest['id']
else:
log("Same stock is still cheapest, holding position.")
log(f"\n=== GAME OVER - SELLING ALL ===")
for h in data['holdings']:
if h['amount'] > 0:
response = session.post(f'{BASE_URL}/api/sell',
json={
'stock_id': h['id'],
'amount': h['amount']
})
if response.status_code != 200:
log(f"Error selling: {response.status_code} - {response.text}")
continue
data = response.json()
log(f"Sold {h['amount']} shares of {h['name']}")
log(f"\n=== FINAL RESULTS ===")
log(f"Starting balance: $1000")
log(f"Ending balance: ${data['balance']}")
log(f"Profit: ${data['balance'] - 1000}")
if saveScore == True:
response = session.post(f'{BASE_URL}/api/save-score',
json={
'name': "Chris's AutoTrader",
})
if response.status_code == 200:
log("Score saved successfully!")
else:
log(f"Error saving score: {response.status_code}")
log_file.close()
main()

42
leaderboard.json Normal file
View File

@@ -0,0 +1,42 @@
[
{
"name": "test",
"profit": 29242282,
"net_worth": 29243282,
"final_balance": 29243282,
"leaderboardDays": 100,
"timestamp": "2025-12-11 22:53:08"
},
{
"name": "Nvidia",
"profit": 20420,
"net_worth": 21420,
"final_balance": 21420,
"leaderboardDays": 10,
"timestamp": "2025-12-13 15:30:26"
},
{
"name": "test",
"profit": 1680,
"net_worth": 2680,
"final_balance": 2680,
"leaderboardDays": 5,
"timestamp": "2025-12-13 15:25:16"
},
{
"name": "test",
"profit": 0,
"net_worth": 1000,
"final_balance": 1000,
"leaderboardDays": 5,
"timestamp": "2025-12-13 15:24:32"
},
{
"name": "easports",
"profit": 0,
"net_worth": 1000,
"final_balance": 1000,
"leaderboardDays": 5,
"timestamp": "2025-12-13 15:27:17"
}
]

View File

@@ -1,230 +1,325 @@
from flask import Flask, render_template, request, jsonify, session from flask import Flask, render_template, request, jsonify, session
import random import random
from datetime import datetime import json
import os
app = Flask(__name__) from datetime import datetime
app.secret_key = 'your_secret_key_here'
app = Flask(__name__)
# Game state management app.secret_key = 'your-secret-key-change-this-in-production'
game_state = {}
# Leaderboard file path
def init_game(days): LEADERBOARD_FILE = 'leaderboard.json'
"""Initialize a new game session"""
return { # List of all companies - EASY TO ADD/REMOVE COMPANIES HERE
'balance': 1000, COMPANIES = [
'kwiktripStockPrice': 100 + random.randint(-100, 100), {'id': 1, 'name': 'Kwik trip', 'key': 'kwiktrip'},
'appleStockPrice': 100 + random.randint(-100, 100), {'id': 2, 'name': 'Apple computers', 'key': 'apple'},
'microsoftStockPrice': 100 + random.randint(-100, 100), {'id': 3, 'name': 'Microsoft', 'key': 'microsoft'},
'walmartStockPrice': 100 + random.randint(-100, 100), {'id': 4, 'name': 'Walmart Super Store', 'key': 'walmart'},
'carStockPrice': 100 + random.randint(-100, 100), {'id': 5, 'name': 'Car company', 'key': 'car'},
'kwiktrip': 0, {'id': 6, 'name': 'Tesla', 'key': 'tesla'},
'apple': 0, {'id': 7, 'name': 'Amazon', 'key': 'amazon'},
'microsoft': 0, {'id': 8, 'name': 'Google', 'key': 'google'},
'walmart': 0, {'id': 9, 'name': 'Netflix', 'key': 'netflix'},
'car': 0, {'id': 10, 'name': 'Steam', 'key': 'steam',},
'day': 1, {'id': 11, 'name': 'Nvidia', 'key': 'nvidia'}
'daysleft': days, ]
'message': ''
} # Game state management - now per-client via session
# Removed: game_state = {}
def calculate_index(state): leaderboard = []
"""Calculate market index"""
prices = [state['kwiktripStockPrice'], state['appleStockPrice'], def load_leaderboard():
state['microsoftStockPrice'], state['walmartStockPrice'], """Load leaderboard from file"""
state['carStockPrice']] global leaderboard
return sum(prices) / 5 if os.path.exists(LEADERBOARD_FILE):
try:
def get_stock_list(state): with open(LEADERBOARD_FILE, 'r') as f:
"""Return list of stocks with prices""" leaderboard = json.load(f)
return [ except (json.JSONDecodeError, IOError):
{'id': 1, 'name': 'Kwik trip', 'price': state['kwiktripStockPrice']}, leaderboard = []
{'id': 2, 'name': 'Apple computers', 'price': state['appleStockPrice']}, else:
{'id': 3, 'name': 'Microsoft', 'price': state['microsoftStockPrice']}, leaderboard = []
{'id': 4, 'name': 'Walmart Super Store', 'price': state['walmartStockPrice']},
{'id': 5, 'name': 'Car company', 'price': state['carStockPrice']} def save_leaderboard():
] """Save leaderboard to file"""
try:
def get_holdings(state): with open(LEADERBOARD_FILE, 'w') as f:
"""Return user's stock holdings""" json.dump(leaderboard, f, indent=4)
return [ except IOError as e:
{'id': 1, 'name': 'Kwik trip', 'amount': state['kwiktrip']}, print(f"Error saving leaderboard: {e}")
{'id': 2, 'name': 'Apple computers', 'amount': state['apple']},
{'id': 3, 'name': 'Microsoft', 'amount': state['microsoft']}, def init_game(days):
{'id': 4, 'name': 'Walmart Super Store', 'amount': state['walmart']}, """Initialize a new game session"""
{'id': 5, 'name': 'Car company', 'amount': state['car']} # Generate random offsets for initial prices for each company
] price_offsets = {company['key']: random.randint(-1000, 1000) for company in COMPANIES}
def get_game_state_data(): # Build state with dynamic company prices and history
"""Get current game state data as dictionary""" state = {
if 'current' not in game_state: 'balance': 1000,
return None 'day': 1,
'daysleft': days,
state = game_state['current'] 'leaderboardDays': days,
stocks = get_stock_list(state) 'message': '',
holdings = get_holdings(state) 'priceHistory': {},
}
return {
'balance': state['balance'], # Add stock prices and holdings for each company
'day': state['day'], for company in COMPANIES:
'daysleft': state['daysleft'], key = company['key']
'index': round(calculate_index(state), 2), offset = price_offsets[key]
'stocks': stocks, # Ensure initial price is at least $1
'holdings': holdings, initial_price = max(50, 100 + offset)
'message': state.get('message', '') state[f'{key}StockPrice'] = initial_price
} state[key] = 0
state['priceHistory'][key] = [initial_price]
@app.route('/')
def home(): return state
"""Home page - ask for number of days"""
return render_template('index.html') def calculate_index(state):
"""Calculate market index"""
@app.route('/api/start', methods=['POST']) prices = [state[f"{company['key']}StockPrice"] for company in COMPANIES]
def start_game(): return sum(prices) / len(prices) if prices else 0
"""Initialize a new game"""
data = request.json def get_stock_list(state):
days = int(data.get('days', 5)) """Return list of stocks with prices"""
return [
state = init_game(days) {'id': company['id'], 'name': company['name'], 'price': state[f"{company['key']}StockPrice"]}
game_state['current'] = state for company in COMPANIES
]
return jsonify(get_game_state_data())
def get_holdings(state):
@app.route('/api/game-state', methods=['GET']) """Return user's stock holdings"""
def get_game_state(): return [
"""Get current game state""" {'id': company['id'], 'name': company['name'], 'amount': state[company['key']]}
state_data = get_game_state_data() for company in COMPANIES
if state_data is None: ]
return jsonify({'error': 'Game not started'}), 400
def get_game_state_data():
return jsonify(state_data) """Get current game state data as dictionary"""
if 'game_state' not in session:
@app.route('/api/buy', methods=['POST']) return None
def buy_stock():
"""Buy stocks""" state = session['game_state']
if 'current' not in game_state: stocks = get_stock_list(state)
return jsonify({'error': 'Game not started'}), 400 holdings = get_holdings(state)
state = game_state['current'] return {
data = request.json 'balance': state['balance'],
'day': state['day'],
try: 'daysleft': state['daysleft'],
stock_id = int(data['stock_id']) 'index': round(calculate_index(state), 2),
amount = int(data['amount']) 'stocks': stocks,
'holdings': holdings,
stocks = get_stock_list(state) 'message': state.get('message', ''),
stock_price = stocks[stock_id - 1]['price'] 'priceHistory': state.get('priceHistory', {})
total_cost = amount * stock_price }
if state['balance'] < total_cost: @app.route('/')
state['message'] = f"Insufficient funds. Cost: ${total_cost}, Balance: ${state['balance']}" def home():
return jsonify({'error': state['message']}), 400 """Home page - ask for number of days"""
return render_template('index.html')
state['balance'] -= total_cost
@app.route('/api/start', methods=['POST'])
stock_keys = ['kwiktrip', 'apple', 'microsoft', 'walmart', 'car'] def start_game():
state[stock_keys[stock_id - 1]] += amount """Initialize a new game"""
data = request.json
state['message'] = f"Successfully bought {amount} shares of {stocks[stock_id - 1]['name']} for ${total_cost}" days = int(data.get('days', 5))
return jsonify(get_game_state_data()) state = init_game(days)
except (ValueError, IndexError, KeyError) as e: session['game_state'] = state
return jsonify({'error': str(e)}), 400
return jsonify(get_game_state_data())
@app.route('/api/sell', methods=['POST'])
def sell_stock(): @app.route('/api/game-state', methods=['GET'])
"""Sell stocks""" def get_game_state():
if 'current' not in game_state: """Get current game state"""
return jsonify({'error': 'Game not started'}), 400 state_data = get_game_state_data()
if state_data is None:
state = game_state['current'] return jsonify({'error': 'Game not started'}), 400
data = request.json
return jsonify(state_data)
try:
stock_id = int(data['stock_id']) @app.route('/api/buy', methods=['POST'])
amount = int(data['amount']) def buy_stock():
"""Buy stocks"""
stocks = get_stock_list(state) if 'game_state' not in session:
holdings = get_holdings(state) return jsonify({'error': 'Game not started'}), 400
user_holdings = holdings[stock_id - 1]['amount'] state = session['game_state']
data = request.json
if user_holdings < amount:
state['message'] = f"You don't own enough shares. You own: {user_holdings}" try:
return jsonify({'error': state['message']}), 400 stock_id = int(data['stock_id'])
amount = int(data['amount'])
stock_price = stocks[stock_id - 1]['price']
total_payout = amount * stock_price stocks = get_stock_list(state)
stock_price = stocks[stock_id - 1]['price']
state['balance'] += total_payout total_cost = amount * stock_price
stock_keys = ['kwiktrip', 'apple', 'microsoft', 'walmart', 'car'] if state['balance'] < total_cost:
state[stock_keys[stock_id - 1]] -= amount state['message'] = f"Insufficient funds. Cost: ${total_cost}, Balance: ${state['balance']}"
return jsonify({'error': state['message']}), 400
state['message'] = f"Successfully sold {amount} shares of {stocks[stock_id - 1]['name']} for ${total_payout}"
state['balance'] -= total_cost
return jsonify(get_game_state_data())
except (ValueError, IndexError, KeyError) as e: # Use dynamic COMPANIES list instead of hardcoded array
return jsonify({'error': str(e)}), 400 stock_key = COMPANIES[stock_id - 1]['key']
state[stock_key] += amount
@app.route('/api/next-day', methods=['POST'])
def next_day(): state['message'] = f"Successfully bought {amount} shares of {stocks[stock_id - 1]['name']} for ${total_cost}"
"""Progress to next day"""
if 'current' not in game_state: session['game_state'] = state
return jsonify({'error': 'Game not started'}), 400 return jsonify(get_game_state_data())
except (ValueError, IndexError, KeyError) as e:
state = game_state['current'] return jsonify({'error': str(e)}), 400
if state['daysleft'] <= 0: @app.route('/api/sell', methods=['POST'])
return jsonify({'error': 'Game over!', 'game_over': True}), 400 def sell_stock():
"""Sell stocks"""
state['day'] += 1 if 'game_state' not in session:
state['daysleft'] -= 1 return jsonify({'error': 'Game not started'}), 400
# Update stock prices state = session['game_state']
state['kwiktripStockPrice'] = abs(state['kwiktripStockPrice'] + random.randint(-100, 100)) data = request.json
state['appleStockPrice'] = abs(state['appleStockPrice'] + random.randint(-100, 100))
state['microsoftStockPrice'] = abs(state['microsoftStockPrice'] + random.randint(-100, 100)) try:
state['walmartStockPrice'] = abs(state['walmartStockPrice'] + random.randint(-100, 100)) stock_id = int(data['stock_id'])
state['carStockPrice'] = abs(state['carStockPrice'] + random.randint(-100, 100)) amount = int(data['amount'])
# Market crash chance stocks = get_stock_list(state)
if random.randint(0, 1000) == 555: holdings = get_holdings(state)
state['kwiktripStockPrice'] = 10
state['appleStockPrice'] = 10 user_holdings = holdings[stock_id - 1]['amount']
state['microsoftStockPrice'] = 10
state['walmartStockPrice'] = 10 if user_holdings < amount:
state['carStockPrice'] = 10 state['message'] = f"You don't own enough shares. You own: {user_holdings}"
state['message'] = "Market crash! All stocks dropped to $10" return jsonify({'error': state['message']}), 400
else:
state['message'] = f"Moved to day {state['day']}" stock_price = stocks[stock_id - 1]['price']
total_payout = amount * stock_price
return jsonify(get_game_state_data())
state['balance'] += total_payout
@app.route('/api/end-game', methods=['GET'])
def end_game(): # Use dynamic COMPANIES list instead of hardcoded array
"""Get end game statistics""" stock_key = COMPANIES[stock_id - 1]['key']
if 'current' not in game_state: state[stock_key] -= amount
return jsonify({'error': 'Game not started'}), 400
state['message'] = f"Successfully sold {amount} shares of {stocks[stock_id - 1]['name']} for ${total_payout}"
state = game_state['current']
stocks = get_stock_list(state) session['game_state'] = state
return jsonify(get_game_state_data())
total_net_worth = state['balance'] except (ValueError, IndexError, KeyError) as e:
holdings = get_holdings(state) return jsonify({'error': str(e)}), 400
for i, holding in enumerate(holdings): @app.route('/api/next-day', methods=['POST'])
total_net_worth += holding['amount'] * stocks[i]['price'] def next_day():
"""Progress to next day"""
profit = state['balance'] - 1000 if 'game_state' not in session:
return jsonify({'error': 'Game not started'}), 400
return jsonify({
'starting_balance': 1000, state = session['game_state']
'ending_balance': state['balance'],
'total_net_worth': round(total_net_worth, 2), if state['daysleft'] <= 0:
'profit': profit, return jsonify({'error': 'Game over!', 'game_over': True}), 400
'holdings': holdings,
'stocks': stocks state['day'] += 1
}) state['daysleft'] -= 1
if __name__ == '__main__': # Update stock prices dynamically for all companies
app.run(debug=True) for company in COMPANIES:
key = company['key']
price_key = f"{key}StockPrice"
new_price = state[price_key] + random.randint(-100, 100)
# Ensure price is at least $1
state[price_key] = max(1, new_price)
state['priceHistory'][key].append(state[price_key])
# Market crash chance
if random.randint(0, 1000) == 555:
# Market crash - set all prices to $1 minimum
for company in COMPANIES:
key = company['key']
crash_price = max(1, int(state[f"{key}StockPrice"] * 0.2)) # Drop to 20% of current price, but no lower than $1
state[f"{key}StockPrice"] = crash_price
state['priceHistory'][key][-1] = crash_price
state['message'] = "Market crash! All stocks dropped significantly!"
else:
state['message'] = f"Moved to day {state['day']}"
session['game_state'] = state
return jsonify(get_game_state_data())
@app.route('/api/end-game', methods=['GET'])
def end_game():
"""Get end game statistics"""
if 'game_state' not in session:
return jsonify({'error': 'Game not started'}), 400
state = session['game_state']
stocks = get_stock_list(state)
total_net_worth = state['balance']
holdings = get_holdings(state)
for i, holding in enumerate(holdings):
total_net_worth += holding['amount'] * stocks[i]['price']
profit = state['balance'] - 1000
return jsonify({
'starting_balance': 1000,
'ending_balance': state['balance'],
'total_net_worth': round(total_net_worth, 2),
'profit': profit,
'holdings': holdings,
'stocks': stocks
})
@app.route('/api/save-score', methods=['POST'])
def save_score():
"""Save game score to leaderboard"""
if 'game_state' not in session:
return jsonify({'error': 'Game not started'}), 400
data = request.json
player_name = data.get('name', 'Anonymous')
state = session['game_state']
stocks = get_stock_list(state)
total_net_worth = state['balance']
holdings = get_holdings(state)
for i, holding in enumerate(holdings):
total_net_worth += holding['amount'] * stocks[i]['price']
profit = state['balance'] - 1000
score_entry = {
'name': player_name,
'profit': profit,
'net_worth': round(total_net_worth, 2),
'final_balance': state['balance'],
'leaderboardDays': state['leaderboardDays'],
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
leaderboard.append(score_entry)
leaderboard.sort(key=lambda x: x['profit'], reverse=True)
# Save leaderboard to file
save_leaderboard()
return jsonify({'success': True, 'rank': leaderboard.index(score_entry) + 1})
@app.route('/api/leaderboard', methods=['GET'])
def get_leaderboard():
"""Get leaderboard scores"""
return jsonify({'scores': leaderboard[:10]})
# Load leaderboard from file at startup
load_leaderboard()
if __name__ == '__main__':
app.run(debug=False)

22
readme.md Normal file
View File

@@ -0,0 +1,22 @@
# How to Run
There are two different interfaces available: CLI, and Web.
## Web
Run these commands to run the flask:
```sh
python3 mainweb.py
```
Or
```sh
flask run mainweb.py -p {port}
```
## CLI
Run main.py for the CLI interface:
```sh
python3 main.py
```

View File

@@ -1,258 +1,607 @@
// Game state // Game state
let gameActive = false; let gameActive = false;
let stockCharts = {};
async function startGame() {
const daysInput = document.getElementById('daysInput'); // Format large numbers: add commas for thousands
const days = parseInt(daysInput.value); function formatNumber(value) {
const num = Number(value);
if (!days || days < 1) { if (isNaN(num)) return value;
alert('Please enter a valid number of days'); if (Number.isInteger(num)) return num.toLocaleString();
return; return num.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
} }
async function startGame() {
try { const daysInput = document.getElementById('daysInput');
const response = await fetch('/api/start', { const days = parseInt(daysInput.value);
method: 'POST',
headers: { if (!days || days < 1) {
'Content-Type': 'application/json' alert('Please enter a valid number of days');
}, return;
body: JSON.stringify({ days: days }) }
});
try {
if (!response.ok) throw new Error('Failed to start game'); const response = await fetch('/api/start', {
method: 'POST',
gameActive = true; headers: {
document.getElementById('startScreen').classList.add('hidden'); 'Content-Type': 'application/json'
document.getElementById('gameScreen').classList.remove('hidden'); },
document.getElementById('totalDays').textContent = days; body: JSON.stringify({ days: days })
});
await updateGameDisplay();
populateStockSelect(); if (!response.ok) throw new Error('Failed to start game');
} catch (error) {
alert('Error starting game: ' + error.message); gameActive = true;
} document.getElementById('startScreen').classList.add('hidden');
} document.getElementById('gameScreen').classList.remove('hidden');
document.getElementById('totalDays').textContent = days;
async function updateGameDisplay() {
try { await updateGameDisplay();
const response = await fetch('/api/game-state'); populateStockSelect();
if (!response.ok) throw new Error('Failed to fetch game state'); } catch (error) {
alert('Error starting game: ' + error.message);
const data = await response.json(); }
}
document.getElementById('balance').textContent = data.balance;
document.getElementById('day').textContent = data.day; async function updateGameDisplay() {
document.getElementById('index').textContent = data.index; try {
const response = await fetch('/api/game-state');
displayStocks(data.stocks); if (!response.ok) throw new Error('Failed to fetch game state');
displayHoldings(data.holdings);
displayMessage(data.message); const data = await response.json();
} catch (error) {
console.error('Error updating game display:', error); document.getElementById('balance').textContent = formatNumber(data.balance);
} document.getElementById('day').textContent = data.day;
} document.getElementById('index').textContent = formatNumber(data.index);
function displayStocks(stocks) { displayStocks(data.stocks);
const stocksList = document.getElementById('stocksList'); displayHoldings(data.holdings);
stocksList.innerHTML = ''; displayMessage(data.message);
updateCharts(data.priceHistory, data.stocks, data.day);
stocks.forEach(stock => { } catch (error) {
const div = document.createElement('div'); console.error('Error updating game display:', error);
div.className = 'stock-item'; }
div.innerHTML = `<span>${stock.name}</span><span>$${stock.price}</span>`; }
stocksList.appendChild(div);
}); function displayStocks(stocks) {
} const stocksList = document.getElementById('stocksList');
stocksList.innerHTML = '';
function displayHoldings(holdings) {
const holdingsList = document.getElementById('holdingsList'); stocks.forEach(stock => {
holdingsList.innerHTML = ''; const div = document.createElement('div');
div.className = 'stock-item';
holdings.forEach(holding => { div.innerHTML = `<span>${stock.name}</span><span>$${formatNumber(stock.price)}</span>`;
const div = document.createElement('div'); stocksList.appendChild(div);
div.className = 'holding-item'; });
div.innerHTML = `<span>${holding.name}</span><span>${holding.amount} shares</span>`; }
holdingsList.appendChild(div);
}); function displayHoldings(holdings) {
} const holdingsList = document.getElementById('holdingsList');
holdingsList.innerHTML = '';
function displayMessage(message) {
const messageDiv = document.getElementById('message'); holdings.forEach(holding => {
if (message) { const div = document.createElement('div');
messageDiv.textContent = message; div.className = 'holding-item';
messageDiv.classList.add('show'); div.innerHTML = `<span>${holding.name}</span><span>${holding.amount} shares</span>`;
messageDiv.classList.remove('error'); holdingsList.appendChild(div);
} else { });
messageDiv.classList.remove('show'); }
}
} function displayMessage(message) {
const messageDiv = document.getElementById('message');
function populateStockSelect() { if (message) {
const stocks = [ messageDiv.textContent = message;
{ id: 1, name: 'Kwik trip' }, messageDiv.classList.add('show');
{ id: 2, name: 'Apple computers' }, messageDiv.classList.remove('error');
{ id: 3, name: 'Microsoft' }, } else {
{ id: 4, name: 'Walmart Super Store' }, messageDiv.classList.remove('show');
{ id: 5, name: 'Car company' } }
]; }
const select = document.getElementById('stockSelect'); function populateStockSelect() {
select.innerHTML = ''; // Fetch the current game state to get the actual stocks
stocks.forEach(stock => { fetch('/api/game-state')
const option = document.createElement('option'); .then(response => response.json())
option.value = stock.id; .then(data => {
option.textContent = `${stock.name}`; const stocks = data.stocks;
select.appendChild(option); const select = document.getElementById('stockSelect');
}); select.innerHTML = '';
} stocks.forEach(stock => {
const option = document.createElement('option');
async function buyStock() { option.value = stock.id;
if (!gameActive) return; option.textContent = `${stock.name}`;
select.appendChild(option);
const stockId = parseInt(document.getElementById('stockSelect').value); });
const amount = parseInt(document.getElementById('amountInput').value); })
.catch(error => console.error('Error populating stock select:', error));
if (!amount || amount < 1) { }
showError('Please enter a valid amount');
return; async function buyStock() {
} if (!gameActive) return;
try { const stockId = parseInt(document.getElementById('stockSelect').value);
const response = await fetch('/api/buy', { const amount = parseInt(document.getElementById('amountInput').value);
method: 'POST',
headers: { if (!amount || amount < 1) {
'Content-Type': 'application/json' showError('Please enter a valid amount');
}, return;
body: JSON.stringify({ }
stock_id: stockId,
amount: amount try {
}) const response = await fetch('/api/buy', {
}); method: 'POST',
headers: {
const data = await response.json(); 'Content-Type': 'application/json'
},
if (!response.ok) { body: JSON.stringify({
showError(data.error); stock_id: stockId,
return; amount: amount
} })
});
document.getElementById('amountInput').value = '1';
await updateGameDisplay(); const data = await response.json();
} catch (error) {
showError('Error buying stock: ' + error.message); if (!response.ok) {
} showError(data.error);
} return;
}
async function sellStock() {
if (!gameActive) return; document.getElementById('amountInput').value = '1';
await updateGameDisplay();
const stockId = parseInt(document.getElementById('stockSelect').value); } catch (error) {
const amount = parseInt(document.getElementById('amountInput').value); showError('Error buying stock: ' + error.message);
}
if (!amount || amount < 1) { }
showError('Please enter a valid amount');
return; async function sellStock() {
} if (!gameActive) return;
try { const stockId = parseInt(document.getElementById('stockSelect').value);
const response = await fetch('/api/sell', { const amount = parseInt(document.getElementById('amountInput').value);
method: 'POST',
headers: { if (!amount || amount < 1) {
'Content-Type': 'application/json' showError('Please enter a valid amount');
}, return;
body: JSON.stringify({ }
stock_id: stockId,
amount: amount try {
}) const response = await fetch('/api/sell', {
}); method: 'POST',
headers: {
const data = await response.json(); 'Content-Type': 'application/json'
},
if (!response.ok) { body: JSON.stringify({
showError(data.error); stock_id: stockId,
return; amount: amount
} })
});
document.getElementById('amountInput').value = '1';
await updateGameDisplay(); const data = await response.json();
} catch (error) {
showError('Error selling stock: ' + error.message); if (!response.ok) {
} showError(data.error);
} return;
}
async function nextDay() {
if (!gameActive) return; document.getElementById('amountInput').value = '1';
await updateGameDisplay();
try { } catch (error) {
const response = await fetch('/api/next-day', { showError('Error selling stock: ' + error.message);
method: 'POST' }
}); }
const data = await response.json(); async function buyAll() {
if (!gameActive) return;
if (data.game_over) {
await endGame(); const stockId = parseInt(document.getElementById('stockSelect').value);
return;
} try {
const gameStateResponse = await fetch('/api/game-state');
await updateGameDisplay(); const gameStateData = await gameStateResponse.json();
} catch (error) {
showError('Error advancing to next day: ' + error.message); const stocks = gameStateData.stocks;
} const balance = gameStateData.balance;
} const stockPrice = stocks[stockId - 1]['price'];
async function endGame() { // Calculate maximum amount we can buy
try { const maxAmount = Math.min(Math.floor(balance / stockPrice), 999999999999999999);
const response = await fetch('/api/end-game');
if (!response.ok) throw new Error('Failed to fetch end game stats'); if (maxAmount <= 0) {
showError('Insufficient funds to buy any shares of this stock');
const data = await response.json(); return;
}
document.getElementById('startBalance').textContent = data.starting_balance;
document.getElementById('endBalance').textContent = data.ending_balance; try {
document.getElementById('netWorth').textContent = data.total_net_worth; const response = await fetch('/api/buy', {
document.getElementById('profit').textContent = data.profit; method: 'POST',
headers: {
// Color profit red or green 'Content-Type': 'application/json'
const profitText = document.getElementById('profitText'); },
if (data.profit >= 0) { body: JSON.stringify({
profitText.style.color = '#4caf50'; stock_id: stockId,
} else { amount: maxAmount
profitText.style.color = '#f44336'; })
} });
// Display final holdings const data = await response.json();
const finalHoldings = document.getElementById('finalHoldings');
finalHoldings.innerHTML = ''; if (!response.ok) {
data.holdings.forEach((holding, index) => { showError(data.error);
if (holding.amount > 0) { return;
const div = document.createElement('div'); }
div.className = 'holding-final';
const stockPrice = data.stocks[index].price; document.getElementById('amountInput').value = '1';
const value = holding.amount * stockPrice; await updateGameDisplay();
div.innerHTML = ` } catch (error) {
<span>${holding.name}: ${holding.amount} shares</span> showError('Error buying stock: ' + error.message);
<span>Value: $${value}</span> }
`; } catch (error) {
finalHoldings.appendChild(div); showError('Error fetching game state: ' + error.message);
} }
}); }
gameActive = false; async function sellAll() {
document.getElementById('gameScreen').classList.add('hidden'); if (!gameActive) return;
document.getElementById('endScreen').classList.remove('hidden');
} catch (error) { const stockId = parseInt(document.getElementById('stockSelect').value);
showError('Error getting game stats: ' + error.message);
} try {
} const gameStateResponse = await fetch('/api/game-state');
const gameStateData = await gameStateResponse.json();
function showError(message) {
const messageDiv = document.getElementById('message'); const holdings = gameStateData.holdings;
messageDiv.textContent = message; const amountToSell = Math.min(holdings[stockId - 1]['amount'], 999999999999999999);
messageDiv.classList.add('show', 'error');
} if (amountToSell <= 0) {
showError('You do not own any shares of this stock');
// Initialize when page loads return;
document.addEventListener('DOMContentLoaded', () => { }
populateStockSelect();
}); try {
const response = await fetch('/api/sell', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
stock_id: stockId,
amount: amountToSell
})
});
const data = await response.json();
if (!response.ok) {
showError(data.error);
return;
}
document.getElementById('amountInput').value = '1';
await updateGameDisplay();
} catch (error) {
showError('Error selling stock: ' + error.message);
}
} catch (error) {
showError('Error fetching game state: ' + error.message);
}
}
async function nextDay() {
if (!gameActive) return;
try {
const response = await fetch('/api/next-day', {
method: 'POST'
});
const data = await response.json();
if (data.game_over) {
await endGame();
return;
}
await updateGameDisplay();
} catch (error) {
showError('Error advancing to next day: ' + error.message);
}
}
async function endGame() {
try {
const response = await fetch('/api/end-game');
if (!response.ok) throw new Error('Failed to fetch end game stats');
const data = await response.json();
document.getElementById('startBalance').textContent = formatNumber(data.starting_balance);
document.getElementById('endBalance').textContent = formatNumber(data.ending_balance);
document.getElementById('netWorth').textContent = formatNumber(data.total_net_worth);
document.getElementById('profit').textContent = formatNumber(data.profit);
// Color profit red or green
const profitText = document.getElementById('profitText');
if (data.profit >= 0) {
profitText.style.color = '#4caf50';
} else {
profitText.style.color = '#f44336';
}
// Display final holdings
const finalHoldings = document.getElementById('finalHoldings');
finalHoldings.innerHTML = '';
data.holdings.forEach((holding, index) => {
if (holding.amount > 0) {
const div = document.createElement('div');
div.className = 'holding-final';
const stockPrice = Number(data.stocks[index].price);
const value = holding.amount * stockPrice;
div.innerHTML = `
<span>${holding.name}: ${holding.amount} shares</span>
<span>Value: $${formatNumber(value)}</span>
`;
finalHoldings.appendChild(div);
}
});
// Fetch current game state to get price history for the chart
const gameStateResponse = await fetch('/api/game-state');
const gameStateData = await gameStateResponse.json();
// Display the final price chart
if (gameStateData.priceHistory) {
createEndPriceChart(gameStateData.priceHistory);
}
gameActive = false;
document.getElementById('gameScreen').classList.add('hidden');
document.getElementById('endScreen').classList.remove('hidden');
} catch (error) {
showError('Error getting game stats: ' + error.message);
}
}
function showError(message) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = message;
messageDiv.classList.add('show', 'error');
}
async function saveScore() {
const playerName = document.getElementById('playerName').value.trim();
if (!playerName) {
alert('Please enter your name');
return;
}
try {
const response = await fetch('/api/save-score', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: playerName })
});
const data = await response.json();
if (data.success) {
alert(`Score saved! You ranked #${data.rank} on the leaderboard!`);
// Clear the name input
document.getElementById('playerName').value = '';
}
} catch (error) {
showError('Error saving score: ' + error.message);
}
}
async function viewLeaderboard() {
try {
const response = await fetch('/api/leaderboard');
const data = await response.json();
document.getElementById('startScreen').classList.add('hidden');
document.getElementById('leaderboardScreen').classList.remove('hidden');
displayLeaderboard(data.scores);
} catch (error) {
showError('Error loading leaderboard: ' + error.message);
}
}
function displayLeaderboard(scores) {
const leaderboardList = document.getElementById('leaderboardList');
const emptyMessage = document.getElementById('emptyLeaderboard');
if (scores.length === 0) {
leaderboardList.innerHTML = '';
emptyMessage.style.display = 'block';
return;
}
emptyMessage.style.display = 'none';
leaderboardList.innerHTML = '';
scores.forEach((score, index) => {
const rank = index + 1;
const div = document.createElement('div');
div.className = `leaderboard-entry rank-${rank}`;
const profitClass = score.profit >= 0 ? 'positive' : 'negative';
const profitSign = score.profit >= 0 ? '+' : '';
div.innerHTML = `
<div class="leaderboard-rank">#${rank}</div>
<div class="leaderboard-info">
<div class="leaderboard-name">${score.name}</div>
<div class="leaderboard-stats">Days: ${score.leaderboardDays} | Balance: $${formatNumber(score.final_balance)} | Net Worth: $${formatNumber(score.net_worth)} | ${score.timestamp}</div>
</div>
<div class="leaderboard-profit ${profitClass}">${profitSign}$${formatNumber(score.profit)}</div>
`;
leaderboardList.appendChild(div);
});
}
function backToStart() {
document.getElementById('leaderboardScreen').classList.add('hidden');
document.getElementById('startScreen').classList.remove('hidden');
}
function createEndPriceChart(priceHistory) {
// Define colors for stocks
const colors = ['#667eea', '#764ba2', '#4caf50', '#ff9800', '#f44336', '#e91e63', '#9c27b0'];
// Get the history for all stocks
let history = [];
const stockKeys = Object.keys(priceHistory);
if (stockKeys.length > 0) {
history = priceHistory[stockKeys[0]] || [];
}
const days = Array.from({ length: history.length }, (_, i) => i + 1);
// Create datasets for each stock dynamically
const datasets = stockKeys.map((key, index) => ({
label: key.charAt(0).toUpperCase() + key.slice(1),
data: priceHistory[key] || [],
borderColor: colors[index % colors.length],
backgroundColor: colors[index % colors.length] + '15',
fill: false,
tension: 0.4,
borderWidth: 2,
pointRadius: 3,
pointHoverRadius: 5,
pointBackgroundColor: colors[index % colors.length],
pointBorderColor: '#fff',
pointBorderWidth: 1
}));
const ctx = document.getElementById('endPriceChart');
if (!ctx) return;
new Chart(ctx, {
type: 'line',
data: {
labels: days,
datasets: datasets
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: {
display: true,
position: 'top',
labels: {
font: { size: 12 },
padding: 15,
usePointStyle: true
}
}
},
scales: {
y: {
beginAtZero: false,
ticks: {
callback: function(value) {
return '$' + formatNumber(value);
}
}
},
x: {
title: {
display: true,
text: 'Day'
}
}
}
}
});
}
function updateCharts(priceHistory, stocks, currentDay) {
// Define colors for stocks
const colors = ['#667eea', '#764ba2', '#4caf50', '#ff9800', '#f44336', '#e91e63', '#9c27b0'];
// Get the history for all stocks - use first stock to get day count
let history = [];
const priceHistoryKeys = Object.keys(priceHistory);
if (priceHistoryKeys.length > 0) {
history = priceHistory[priceHistoryKeys[0]] || [];
}
const days = Array.from({ length: history.length }, (_, i) => i + 1);
// Create datasets for each stock dynamically
const datasets = priceHistoryKeys.map((key, index) => {
// Find the stock name from the stocks array that matches this key
const matchingStock = stocks.find(s => s.name.toLowerCase().replace(/\s+/g, '').replace(/[^a-z0-9]/g, '') === key.toLowerCase());
const label = matchingStock ? matchingStock.name : key.charAt(0).toUpperCase() + key.slice(1);
return {
label: label,
data: priceHistory[key] || [],
borderColor: colors[index % colors.length],
backgroundColor: colors[index % colors.length] + '15',
fill: false,
tension: 0.4,
borderWidth: 2,
pointRadius: 3,
pointHoverRadius: 5,
pointBackgroundColor: colors[index % colors.length],
pointBorderColor: '#fff',
pointBorderWidth: 1
};
});
const ctx = document.getElementById('priceChart');
if (!ctx) return;
if (stockCharts['combined']) {
stockCharts['combined'].data.labels = days;
stockCharts['combined'].data.datasets = datasets;
stockCharts['combined'].update();
} else {
stockCharts['combined'] = new Chart(ctx, {
type: 'line',
data: {
labels: days,
datasets: datasets
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: {
display: true,
position: 'top',
labels: {
font: { size: 12 },
padding: 15,
usePointStyle: true
}
}
},
scales: {
y: {
beginAtZero: false,
ticks: {
callback: function(value) {
return '$' + formatNumber(value);
}
}
},
x: {
title: {
display: true,
text: 'Day'
}
}
}
}
});
}
}
// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
populateStockSelect();
});

View File

@@ -1,319 +1,533 @@
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh; min-height: 100vh;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
padding: 20px; padding: 20px;
} }
.container { .container {
background: white; background: white;
border-radius: 15px; border-radius: 15px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
max-width: 900px; max-width: 1400px;
width: 100%; width: 100%;
padding: 40px; padding: 40px;
} }
h1 { h1 {
text-align: center; text-align: center;
color: #333; color: #333;
margin-bottom: 30px; margin-bottom: 30px;
font-size: 2.5em; font-size: 2.5em;
} }
h2 { h2 {
color: #667eea; color: #667eea;
margin-bottom: 20px; margin-bottom: 20px;
text-align: center; text-align: center;
} }
h3 { h3 {
color: #555; color: #555;
margin-bottom: 15px; margin-bottom: 15px;
font-size: 1.1em; font-size: 1.1em;
} }
.screen { .section h3 {
display: block; text-align: center;
} }
.screen.hidden { .screen {
display: none; display: block;
} }
/* Start Screen */ .screen.hidden {
#startScreen .form-group { display: none;
text-align: center; }
margin-bottom: 20px;
} /* Start Screen */
#startScreen .form-group {
#startScreen label { text-align: center;
display: block; margin-bottom: 20px;
margin-bottom: 10px; }
font-size: 1.1em;
color: #333; #startScreen label {
} display: block;
margin-bottom: 10px;
#startScreen input { font-size: 1.1em;
padding: 10px 15px; color: #333;
font-size: 1em; }
border: 2px solid #667eea;
border-radius: 5px; #startScreen input {
margin-right: 10px; padding: 10px 15px;
width: 100px; font-size: 1em;
} border: 2px solid #667eea;
border-radius: 5px;
/* Game Header */ margin-right: 10px;
.game-header { width: 100px;
margin-bottom: 30px; }
padding: 20px;
background: #f8f9fa; /* Game Header */
border-radius: 10px; .game-header {
} margin-bottom: 30px;
padding: 20px;
.info-box { background: #f8f9fa;
display: grid; border-radius: 10px;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
gap: 15px;
margin-bottom: 15px; .info-box {
} display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
.info-box h3 { gap: 15px;
background: #667eea; margin-bottom: 15px;
color: white; }
padding: 15px;
border-radius: 8px; .info-box h3 {
margin-bottom: 0; background: #667eea;
font-size: 1em; color: white;
} padding: 15px;
border-radius: 8px;
.message { margin-bottom: 0;
padding: 15px; font-size: 1em;
background: #e8f5e9; }
border-left: 4px solid #4caf50;
border-radius: 5px; .section .info-box {
color: #2e7d32; margin-bottom: 20px;
display: none; }
margin-top: 10px;
} .message {
padding: 15px;
.message.show { background: #e8f5e9;
display: block; border-left: 4px solid #4caf50;
} border-radius: 5px;
color: #2e7d32;
.message.error { display: none;
background: #ffebee; }
border-left-color: #f44336;
color: #c62828; .message.show {
} display: block;
}
/* Game Content */
.game-content { .message.error {
display: grid; background: #ffebee;
grid-template-columns: 1fr 1fr; border-left-color: #f44336;
gap: 20px; color: #c62828;
} }
.section { /* Game Content */
background: #f8f9fa; .game-content {
padding: 20px; display: grid;
border-radius: 10px; grid-template-columns: 1fr 1fr 1fr;
border: 1px solid #e0e0e0; gap: 20px;
} }
.stocks-list, .section {
.holdings-list { background: #f8f9fa;
display: flex; padding: 20px;
flex-direction: column; border-radius: 10px;
gap: 10px; border: 1px solid #e0e0e0;
} }
.stock-item, .stocks-list,
.holding-item { .holdings-list,
background: white; .companies-list {
padding: 12px; display: flex;
border-radius: 6px; flex-direction: column;
border-left: 4px solid #667eea; gap: 10px;
display: flex; }
justify-content: space-between;
align-items: center; .stock-item,
} .holding-item,
.company-item {
.holding-item { background: white;
border-left-color: #764ba2; padding: 12px;
} border-radius: 6px;
border-left: 4px solid #667eea;
.stock-item span, display: flex;
.holding-item span { justify-content: space-between;
font-weight: bold; align-items: center;
color: #667eea; }
}
.holding-item {
/* Form Groups */ border-left-color: #764ba2;
.form-group { }
margin-bottom: 15px;
} .company-item {
border-left-color: #2196F3;
.form-group label { padding: 15px;
display: block; gap: 20px;
margin-bottom: 8px; }
color: #333;
font-weight: bold; .company-info {
} flex: 1;
}
.form-group input,
.form-group select { .company-name {
width: 100%; font-weight: bold;
padding: 10px; color: #333;
border: 2px solid #e0e0e0; font-size: 1.05em;
border-radius: 5px; margin-bottom: 5px;
font-size: 1em; }
transition: border-color 0.3s;
} .company-details {
display: flex;
.form-group input:focus, gap: 20px;
.form-group select:focus { font-size: 0.9em;
outline: none; color: #666;
border-color: #667eea; }
}
.company-details span {
/* Buttons */ font-weight: 500;
button { }
padding: 12px 20px;
border: none; .company-value {
border-radius: 6px; font-weight: bold;
font-size: 1em; color: #2196F3;
cursor: pointer; font-size: 1.1em;
transition: all 0.3s; min-width: 100px;
font-weight: bold; text-align: right;
} }
button:hover { .stock-item span,
transform: translateY(-2px); .holding-item span {
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); font-weight: bold;
} color: #667eea;
}
#startScreen button {
background: #667eea; /* Form Groups */
color: white; .form-group {
} margin-bottom: 15px;
}
#startScreen button:hover {
background: #764ba2; .form-group label {
} display: block;
margin-bottom: 8px;
.button-group { color: #333;
display: flex; font-weight: bold;
gap: 10px; }
}
.form-group input,
.btn-buy { .form-group select {
background: #4caf50; width: 100%;
color: white; padding: 10px;
flex: 1; border: 2px solid #e0e0e0;
} border-radius: 5px;
font-size: 1em;
.btn-buy:hover { transition: border-color 0.3s;
background: #45a049; }
}
.form-group input:focus,
.btn-sell { .form-group select:focus {
background: #ff9800; outline: none;
color: white; border-color: #667eea;
flex: 1; }
}
/* Buttons */
.btn-sell:hover { button {
background: #e68900; padding: 12px 20px;
} border: none;
border-radius: 6px;
.btn-next-day { font-size: 1em;
background: #667eea; cursor: pointer;
color: white; transition: all 0.3s;
width: 100%; font-weight: bold;
padding: 15px; }
font-size: 1.1em;
} button:hover {
transform: translateY(-2px);
.btn-next-day:hover { box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
background: #764ba2; }
}
#startScreen button {
/* End Screen */ background: #667eea;
.end-stats { color: white;
text-align: center; }
padding: 20px;
background: #f8f9fa; #startScreen button:hover {
border-radius: 10px; background: #764ba2;
} }
.end-stats p { .button-group {
font-size: 1.1em; display: flex;
margin: 10px 0; gap: 10px;
color: #333; }
}
.btn-buy {
.end-stats .profit { background: #4caf50;
font-size: 1.3em; color: white;
font-weight: bold; flex: 1;
color: #4caf50; }
margin-top: 20px;
} .btn-buy:hover {
background: #45a049;
#finalHoldings { }
text-align: left;
margin: 20px 0; .btn-sell {
padding: 15px; background: #ff9800;
background: white; color: white;
border-radius: 6px; flex: 1;
} }
.holding-final { .btn-sell:hover {
display: flex; background: #e68900;
justify-content: space-between; }
padding: 8px 0;
border-bottom: 1px solid #e0e0e0; .btn-buy-all {
} background: #2196F3;
color: white;
.holding-final:last-child { flex: 1;
border-bottom: none; }
}
.btn-buy-all:hover {
#endScreen button { background: #0b7dda;
background: #667eea; }
color: white;
margin-top: 20px; .btn-sell-all {
padding: 12px 30px; background: #f57c00;
} color: white;
flex: 1;
#endScreen button:hover { }
background: #764ba2;
} .btn-sell-all:hover {
background: #e65100;
/* Responsive */ }
@media (max-width: 768px) {
.container { .btn-next-day {
padding: 20px; background: #667eea;
} color: white;
width: 100%;
.game-content { padding: 15px;
grid-template-columns: 1fr; font-size: 1.1em;
} }
.info-box { .btn-next-day:hover {
grid-template-columns: 1fr; background: #764ba2;
} }
h1 { /* Charts Container */
font-size: 1.8em; .charts-container {
} display: grid;
} grid-template-columns: 1fr;
gap: 20px;
margin-top: 30px;
}
.chart-item {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
border: 1px solid #e0e0e0;
min-height: 400px;
position: relative;
}
.chart-item canvas {
max-height: 400px;
}
/* End Screen */
.end-stats {
text-align: center;
padding: 20px;
background: #f8f9fa;
border-radius: 10px;
}
.end-stats p {
font-size: 1.1em;
margin: 10px 0;
color: #333;
}
.end-stats .profit {
font-size: 1.3em;
font-weight: bold;
color: #4caf50;
margin-top: 20px;
}
#finalHoldings {
text-align: left;
margin: 20px 0;
padding: 15px;
background: white;
border-radius: 6px;
}
.holding-final {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #e0e0e0;
}
.holding-final:last-child {
border-bottom: none;
}
#endScreen button {
background: #667eea;
color: white;
margin-top: 20px;
padding: 12px 30px;
}
#endScreen button:hover {
background: #764ba2;
}
.btn-leaderboard {
background: #9c27b0;
color: white;
width: 100%;
margin-top: 10px;
}
.btn-leaderboard:hover {
background: #7b1fa2;
}
.btn-save-score {
background: #667eea;
color: white;
width: 100%;
}
.btn-save-score:hover {
background: #764ba2;
}
.btn-back {
background: #667eea;
color: white;
width: 100%;
margin-top: 20px;
padding: 12px;
}
.btn-back:hover {
background: #764ba2;
}
/* Leaderboard Screen */
.leaderboard-container {
background: #f8f9fa;
border-radius: 10px;
padding: 20px;
margin-bottom: 20px;
min-height: 300px;
}
.leaderboard-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.leaderboard-entry {
background: white;
padding: 15px;
border-radius: 8px;
border-left: 4px solid #667eea;
display: flex;
justify-content: space-between;
align-items: center;
}
.leaderboard-entry.rank-1 {
border-left-color: #ffd700;
background: #fffbf0;
}
.leaderboard-entry.rank-2 {
border-left-color: #c0c0c0;
background: #f5f5f5;
}
.leaderboard-entry.rank-3 {
border-left-color: #cd7f32;
background: #f9f5f0;
}
.leaderboard-rank {
font-size: 1.5em;
font-weight: bold;
color: #667eea;
min-width: 40px;
text-align: center;
}
.leaderboard-info {
flex: 1;
margin: 0 15px;
}
.leaderboard-name {
font-weight: bold;
color: #333;
font-size: 1.1em;
}
.leaderboard-stats {
font-size: 0.9em;
color: #666;
margin-top: 5px;
}
.leaderboard-profit {
font-size: 1.2em;
font-weight: bold;
min-width: 120px;
text-align: right;
}
.leaderboard-profit.positive {
color: #4caf50;
}
.leaderboard-profit.negative {
color: #f44336;
}
.empty-message {
text-align: center;
padding: 40px 20px;
color: #999;
font-size: 1.1em;
}
/* Responsive */
@media (max-width: 768px) {
.container {
padding: 20px;
}
.game-content {
grid-template-columns: 1fr;
}
.info-box {
grid-template-columns: 1fr;
}
.charts-container {
grid-template-columns: 1fr;
}
.chart-item {
min-height: 250px;
}
h1 {
font-size: 1.8em;
}
}

View File

@@ -1,84 +1,120 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Trading Game</title> <title>Stock Trading Game</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" href="static/style.css"></link>
</head> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<body> <script src="./static/game.js"></script>
<div class="container"> </head>
<h1>Stock Trading Game</h1> <body>
<div class="container">
<!-- Start Game Screen --> <h1>Stock Trading Game</h1>
<div id="startScreen" class="screen">
<h2>Welcome to the Stock Game!</h2> <!-- Start Game Screen -->
<div class="form-group"> <div id="startScreen" class="screen">
<label for="daysInput">How many days do you wish to play?</label> <h2>Welcome to the Stock Game!</h2>
<input type="number" id="daysInput" min="1" max="100" value="5"> <div class="form-group">
<button onclick="startGame()">Start Game</button> <label for="daysInput">How many days do you wish to play?</label>
</div> <input type="number" id="daysInput" min="1" max="100" value="5">
</div> <button onclick="startGame()">Start Game</button>
</div>
<!-- Game Screen --> <div class="form-group">
<div id="gameScreen" class="screen hidden"> <button onclick="viewLeaderboard()" class="btn-leaderboard">View Leaderboard</button>
<div class="game-header"> </div>
<div class="info-box"> </div>
<h3>Balance: $<span id="balance">0</span></h3>
<h3>Day: <span id="day">1</span>/<span id="totalDays">5</span></h3> <!-- Game Screen -->
<h3>Market Index: <span id="index">0</span></h3> <div id="gameScreen" class="screen hidden">
</div>
<div id="message" class="message"></div> <div class="game-content">
</div>
<div class="section">
<div class="game-content"> <h3>Your Holdings</h3>
<div class="section"> <div id="holdingsList" class="holdings-list"></div>
<h3>Stock Prices</h3> </div>
<div id="stocksList" class="stocks-list"></div>
</div> <div class="section">
<h3>Buy/Sell Stocks</h3>
<div class="section"> <div class="form-group">
<h3>Your Holdings</h3> <label for="stockSelect">Select Stock:</label>
<div id="holdingsList" class="holdings-list"></div> <select id="stockSelect"></select>
</div> </div>
<div class="form-group">
<div class="section"> <label for="amountInput">Amount:</label>
<h3>Buy/Sell Stocks</h3> <input type="number" id="amountInput" min="1" value="1">
<div class="form-group"> </div>
<label for="stockSelect">Select Stock:</label> <div class="button-group">
<select id="stockSelect"></select> <button onclick="sellStock()" class="btn-sell">Sell</button>
</div> <button onclick="buyStock()" class="btn-buy">Buy</button>
<div class="form-group"> </div>
<label for="amountInput">Amount:</label> <div class="button-group" style="margin-top: 10px;">
<input type="number" id="amountInput" min="1" value="1"> <button onclick="sellAll()" class="btn-sell-all">Sell All</button>
</div> <button onclick="buyAll()" class="btn-buy-all">Buy All</button>
<div class="button-group"> </div>
<button onclick="buyStock()" class="btn-buy">Buy</button> <div class="info-box" style="margin-top: 10px;">
<button onclick="sellStock()" class="btn-sell">Sell</button> <h3>Balance: $<span id="balance">0</span></h3>
</div> <h3>Day: <span id="day">1</span>/<span id="totalDays">5</span></h3>
</div> <h3>Market Index: <span id="index">0</span></h3>
</div>
<div class="section"> <button onclick="nextDay()" class="btn-next-day">Next Day</button>
<button onclick="nextDay()" class="btn-next-day">Next Day</button> <div id="message" class="message" style="margin-top: 10px;"></div>
</div> </div>
</div>
</div> <div class="section">
<h3>Stock Prices</h3>
<!-- End Game Screen --> <div id="stocksList" class="stocks-list"></div>
<div id="endScreen" class="screen hidden"> </div>
<h2>Game Over!</h2> </div>
<div class="end-stats">
<p>Starting Balance: $<span id="startBalance">1000</span></p> <div class="charts-container" style="margin-top: 10px;">
<p>Ending Balance: $<span id="endBalance">0</span></p> <div class="chart-item" style="grid-column: 1/-1; padding-top: 10px;">
<p>Total Net Worth: $<span id="netWorth">0</span></p> <h3 style="margin-bottom: 5px; text-align: center;">Stock Price Trends</h3>
<p class="profit" id="profitText">Profit: $<span id="profit">0</span></p> <canvas id="priceChart"></canvas>
<h3>Final Holdings:</h3> </div>
<div id="finalHoldings"></div> </div>
<button onclick="location.reload()">Play Again</button>
</div> </div>
</div>
</div> <!-- End Game Screen -->
<div id="endScreen" class="screen hidden">
<script src="{{ url_for('static', filename='game.js') }}"></script> <h2>Game Over!</h2>
</body> <div class="end-stats">
</html> <p>Starting Balance: $<span id="startBalance">1000</span></p>
<p>Ending Balance: $<span id="endBalance">0</span></p>
<p>Total Net Worth: $<span id="netWorth">0</span></p>
<p class="profit" id="profitText">Profit: $<span id="profit">0</span></p>
<h3>Final Holdings:</h3>
<div id="finalHoldings"></div>
<div class="charts-container" style="margin-top: 30px;">
<h3 style="grid-column: 1/-1; margin-bottom: 10px;">Final Price Trends</h3>
<div class="chart-item" style="grid-column: 1/-1;">
<canvas id="endPriceChart"></canvas>
</div>
</div>
<div class="form-group">
<label for="playerName">Enter your name for the scoreboard:</label>
<input type="text" id="playerName" placeholder="Your Name" value="">
<button onclick="saveScore()" class="btn-save-score">Save Score</button>
</div>
<button onclick="location.reload()">Play Again</button>
</div>
</div>
<!-- Leaderboard Screen -->
<div id="leaderboardScreen" class="screen hidden">
<h2>Leaderboard</h2>
<div class="leaderboard-container">
<div id="leaderboardList" class="leaderboard-list"></div>
<div id="emptyLeaderboard" class="empty-message">No scores yet. Be the first to play!</div>
</div>
<button onclick="backToStart()" class="btn-back">Back to Start</button>
</div>
</div>
</body>
</html>

546
tradeLog.txt Normal file
View File

@@ -0,0 +1,546 @@
Game started!
Balance: $1000
Cheapest stock: Kwik trip at $50
Bought 20 shares of Kwik trip
--- Day 2 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 20 shares
Balance: $2240
Bought 2240 shares of Microsoft
--- Day 3 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 4 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 2240 shares
Balance: $2240
Bought 2240 shares of Apple computers
--- Day 5 ---
Cheapest stock now: Car company at $1
Different stock is cheaper! Switching...
Sold 2240 shares
Balance: $224000
Bought 224000 shares of Car company
--- Day 6 ---
Cheapest stock now: Netflix at $1
Different stock is cheaper! Switching...
Sold 224000 shares
Balance: $5152000
Bought 5152000 shares of Netflix
--- Day 7 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 5152000 shares
Balance: $288512000
Bought 288512000 shares of Microsoft
--- Day 8 ---
Cheapest stock now: Amazon at $1
Different stock is cheaper! Switching...
Sold 288512000 shares
Balance: $26831616000
Bought 26831616000 shares of Amazon
--- Day 9 ---
Cheapest stock now: Amazon at $1
Same stock is still cheapest, holding position.
--- Day 10 ---
Cheapest stock now: Amazon at $1
Same stock is still cheapest, holding position.
--- Day 11 ---
Cheapest stock now: Netflix at $1
Different stock is cheaper! Switching...
Sold 26831616000 shares
Balance: $2441677056000
Bought 2441677056000 shares of Netflix
--- Day 12 ---
Cheapest stock now: Netflix at $1
Same stock is still cheapest, holding position.
--- Day 13 ---
Cheapest stock now: Google at $1
Different stock is cheaper! Switching...
Sold 2441677056000 shares
Balance: $2441677056000
Bought 2441677056000 shares of Google
--- Day 14 ---
Cheapest stock now: Netflix at $1
Different stock is cheaper! Switching...
Sold 2441677056000 shares
Balance: $107433790464000
Bought 107433790464000 shares of Netflix
--- Day 15 ---
Cheapest stock now: Netflix at $1
Same stock is still cheapest, holding position.
--- Day 16 ---
Cheapest stock now: Netflix at $1
Same stock is still cheapest, holding position.
--- Day 17 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 107433790464000 shares
Balance: $107433790464000
Bought 107433790464000 shares of Microsoft
--- Day 18 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 19 ---
Cheapest stock now: Apple computers at $30
Different stock is cheaper! Switching...
Sold 107433790464000 shares
Balance: $4082484037632000
Bought 136082801254400 shares of Apple computers
--- Day 20 ---
Cheapest stock now: Amazon at $31
Different stock is cheaper! Switching...
Sold 136082801254400 shares
Balance: $6259808857702400
Bought 201929317990400 shares of Amazon
--- Day 21 ---
Cheapest stock now: Amazon at $22
Same stock is still cheapest, holding position.
--- Day 22 ---
Cheapest stock now: Microsoft at $24
Different stock is cheaper! Switching...
Sold 201929317990400 shares
Balance: $18577497255116800
Bought 774062385629866 shares of Microsoft
--- Day 23 ---
Cheapest stock now: Microsoft at $66
Same stock is still cheapest, holding position.
--- Day 24 ---
Cheapest stock now: Microsoft at $54
Same stock is still cheapest, holding position.
--- Day 25 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 26 ---
Cheapest stock now: Apple computers at $44
Different stock is cheaper! Switching...
Sold 774062385629866 shares
Balance: $64247178007278894
Bought 1460163136529065 shares of Apple computers
--- Day 27 ---
Cheapest stock now: Apple computers at $1
Same stock is still cheapest, holding position.
--- Day 28 ---
Cheapest stock now: Amazon at $1
Different stock is cheaper! Switching...
Sold 1460163136529065 shares
Balance: $73008156826453284
Bought 73008156826453284 shares of Amazon
--- Day 29 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 73008156826453284 shares
Balance: $73008156826453284
Bought 73008156826453284 shares of Apple computers
--- Day 30 ---
Cheapest stock now: Apple computers at $1
Same stock is still cheapest, holding position.
--- Day 31 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 73008156826453284 shares
Balance: $4234473095934290472
Bought 4234473095934290472 shares of Microsoft
--- Day 32 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 33 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 34 ---
Cheapest stock now: Microsoft at $19
Same stock is still cheapest, holding position.
--- Day 35 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 36 ---
Cheapest stock now: Car company at $1
Different stock is cheaper! Switching...
Sold 4234473095934290472 shares
Balance: $203254708604845942656
Bought 203254708604845942656 shares of Car company
--- Day 37 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 38 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 39 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 203254708604845942656 shares
Balance: $203254708604845942656
Bought 203254708604845942656 shares of Microsoft
--- Day 40 ---
Cheapest stock now: Microsoft at $20
Same stock is still cheapest, holding position.
--- Day 41 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 42 ---
Cheapest stock now: Microsoft at $69
Same stock is still cheapest, holding position.
--- Day 43 ---
Cheapest stock now: Google at $20
Different stock is cheaper! Switching...
Sold 203254708604845942656 shares
Balance: $4268348880701764795776
Bought 213417444035088239788 shares of Google
--- Day 44 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 213417444035088239788 shares
Balance: $11311124533859676708780
Bought 11311124533859676708780 shares of Microsoft
--- Day 45 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 46 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 47 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 48 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 49 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 50 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 51 ---
Cheapest stock now: Car company at $30
Different stock is cheaper! Switching...
Sold 11311124533859676708780 shares
Balance: $1119801328852107994169220
Bought 37326710961736933138974 shares of Car company
--- Day 52 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 53 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 37326710961736933138974 shares
Balance: $37326710961736933138974
Bought 37326710961736933138974 shares of Microsoft
--- Day 54 ---
Cheapest stock now: Car company at $1
Different stock is cheaper! Switching...
Sold 37326710961736933138974 shares
Balance: $447920531540843197667688
Bought 447920531540843197667688 shares of Car company
--- Day 55 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 447920531540843197667688 shares
Balance: $447920531540843197667688
Bought 447920531540843197667688 shares of Apple computers
--- Day 56 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 447920531540843197667688 shares
Balance: $24635629234746375871722840
Bought 24635629234746375871722840 shares of Microsoft
--- Day 57 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 58 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 59 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 60 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 24635629234746375871722840 shares
Balance: $24635629234746375871722840
Bought 24635629234746375871722840 shares of Apple computers
--- Day 61 ---
Cheapest stock now: Apple computers at $1
Same stock is still cheapest, holding position.
--- Day 62 ---
Cheapest stock now: Apple computers at $1
Same stock is still cheapest, holding position.
--- Day 63 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 24635629234746375871722840 shares
Balance: $270991921582210134588951240
Bought 270991921582210134588951240 shares of Microsoft
--- Day 64 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 65 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 270991921582210134588951240 shares
Balance: $15446539530185977671570220680
Bought 15446539530185977671570220680 shares of Apple computers
--- Day 66 ---
Cheapest stock now: Google at $1
Different stock is cheaper! Switching...
Sold 15446539530185977671570220680 shares
Balance: $880452753220600727279502578760
Bought 880452753220600727279502578760 shares of Google
--- Day 67 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 880452753220600727279502578760 shares
Balance: $880452753220600727279502578760
Bought 880452753220600727279502578760 shares of Apple computers
--- Day 68 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 880452753220600727279502578760 shares
Balance: $11445885791867809454633533523880
Bought 11445885791867809454633533523880 shares of Microsoft
--- Day 69 ---
Cheapest stock now: Apple computers at $1
Different stock is cheaper! Switching...
Sold 11445885791867809454633533523880 shares
Balance: $824103777014482280733614413719360
Bought 824103777014482280733614413719360 shares of Apple computers
--- Day 70 ---
Cheapest stock now: Apple computers at $1
Same stock is still cheapest, holding position.
--- Day 71 ---
Cheapest stock now: Car company at $1
Different stock is cheaper! Switching...
Sold 824103777014482280733614413719360 shares
Balance: $33788254857593773510078190962493760
Bought 33788254857593773510078190962493760 shares of Car company
--- Day 72 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 73 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 33788254857593773510078190962493760 shares
Balance: $33788254857593773510078190962493760
Bought 33788254857593773510078190962493760 shares of Microsoft
--- Day 74 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 75 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 76 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 77 ---
Cheapest stock now: Microsoft at $11
Same stock is still cheapest, holding position.
--- Day 78 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 79 ---
Cheapest stock now: Car company at $18
Different stock is cheaper! Switching...
Sold 33788254857593773510078190962493760 shares
Balance: $2534119114319533013255864322187032000
Bought 140784395239974056291992462343724000 shares of Car company
--- Day 80 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 81 ---
Cheapest stock now: Car company at $37
Same stock is still cheapest, holding position.
--- Day 82 ---
Cheapest stock now: Car company at $42
Same stock is still cheapest, holding position.
--- Day 83 ---
Cheapest stock now: Microsoft at $66
Different stock is cheaper! Switching...
Sold 140784395239974056291992462343724000 shares
Balance: $19569030938356393824586952265777636000
Bought 296500468762975664008893216148146000 shares of Microsoft
--- Day 84 ---
Cheapest stock now: Microsoft at $1
Same stock is still cheapest, holding position.
--- Day 85 ---
Cheapest stock now: Microsoft at $64
Same stock is still cheapest, holding position.
--- Day 86 ---
Cheapest stock now: Car company at $109
Different stock is cheaper! Switching...
Sold 296500468762975664008893216148146000 shares
Balance: $45068071251972300929351768854518192000
Bought 413468543596076155315153842702001761 shares of Car company
--- Day 87 ---
Cheapest stock now: Car company at $27
Same stock is still cheapest, holding position.
--- Day 88 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 89 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 90 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 91 ---
Cheapest stock now: Microsoft at $78
Different stock is cheaper! Switching...
Sold 413468543596076155315153842702001761 shares
Balance: $40933385816011539376200230427498174390
Bought 524786997641173581746156800352540697 shares of Microsoft
--- Day 92 ---
Cheapest stock now: Microsoft at $46
Same stock is still cheapest, holding position.
--- Day 93 ---
Cheapest stock now: Car company at $13
Different stock is cheaper! Switching...
Sold 524786997641173581746156800352540697 shares
Balance: $74519753665046648607954265650060778998
Bought 5732288743465126815996481973081598384 shares of Car company
--- Day 94 ---
Cheapest stock now: Microsoft at $71
Different stock is cheaper! Switching...
Sold 5732288743465126815996481973081598384 shares
Balance: $429921655759884511199736147981119878806
Bought 6055234588167387481686424619452392659 shares of Microsoft
--- Day 95 ---
Cheapest stock now: Car company at $37
Different stock is cheaper! Switching...
Sold 6055234588167387481686424619452392659 shares
Balance: $538915878346897485870091791131262946668
Bought 14565294009375607726218697057601701261 shares of Car company
--- Day 96 ---
Cheapest stock now: Car company at $1
Same stock is still cheapest, holding position.
--- Day 97 ---
Cheapest stock now: Microsoft at $1
Different stock is cheaper! Switching...
Sold 14565294009375607726218697057601701261 shares
Balance: $14565294009375607726218697057601701272
Bought 14565294009375607726218697057601701272 shares of Microsoft
--- Day 98 ---
Cheapest stock now: Car company at $1
Different stock is cheaper! Switching...
Sold 14565294009375607726218697057601701272 shares
Balance: $903048228581287679025559217571305478864
Bought 903048228581287679025559217571305478864 shares of Car company
--- Day 99 ---
Cheapest stock now: Car company at $33
Same stock is still cheapest, holding position.
--- Day 100 ---
Cheapest stock now: Car company at $37
Same stock is still cheapest, holding position.
--- Day 101 ---
Cheapest stock now: Car company at $51
Same stock is still cheapest, holding position.
=== GAME OVER - SELLING ALL ===
Sold 903048228581287679025559217571305478864 shares of Car company
=== FINAL RESULTS ===
Starting balance: $1000
Ending balance: $46055459657645671630303520096136579422064
Profit: $46055459657645671630303520096136579421064
Score saved successfully!