mirror of
https://git.astronand.dev/minecartchris/Stock-Game.git
synced 2026-06-28 20:17:32 -04:00
Update mainweb.py
This commit is contained in:
181
mainweb.py
181
mainweb.py
@@ -1,57 +1,97 @@
|
|||||||
from flask import Flask, render_template, request, jsonify, session
|
from flask import Flask, render_template, request, jsonify, session
|
||||||
import random
|
import random
|
||||||
|
import json
|
||||||
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.secret_key = 'your_secret_key_here'
|
|
||||||
|
# Leaderboard file path
|
||||||
|
LEADERBOARD_FILE = 'leaderboard.json'
|
||||||
|
|
||||||
|
# List of all companies - EASY TO ADD/REMOVE COMPANIES HERE
|
||||||
|
COMPANIES = [
|
||||||
|
{'id': 1, 'name': 'Kwik trip', 'key': 'kwiktrip'},
|
||||||
|
{'id': 2, 'name': 'Apple computers', 'key': 'apple'},
|
||||||
|
{'id': 3, 'name': 'Microsoft', 'key': 'microsoft'},
|
||||||
|
{'id': 4, 'name': 'Walmart Super Store', 'key': 'walmart'},
|
||||||
|
{'id': 5, 'name': 'Car company', 'key': 'car'},
|
||||||
|
{'id': 6, 'name': 'Tesla', 'key': 'tesla'},
|
||||||
|
{'id': 7, 'name': 'Amazon', 'key': 'amazon'},
|
||||||
|
{'id': 8, 'name': 'Google', 'key': 'google'},
|
||||||
|
{'id': 9, 'name': 'Netflix', 'key': 'netflix'},
|
||||||
|
{'id': 10, 'name': 'Steam', 'key': 'steam',},
|
||||||
|
{'id': 11, 'name': 'Nvidia', 'key': 'nvidia'}
|
||||||
|
]
|
||||||
|
|
||||||
# Game state management
|
# Game state management
|
||||||
game_state = {}
|
game_state = {}
|
||||||
|
leaderboard = []
|
||||||
|
|
||||||
|
def load_leaderboard():
|
||||||
|
"""Load leaderboard from file"""
|
||||||
|
global leaderboard
|
||||||
|
if os.path.exists(LEADERBOARD_FILE):
|
||||||
|
try:
|
||||||
|
with open(LEADERBOARD_FILE, 'r') as f:
|
||||||
|
leaderboard = json.load(f)
|
||||||
|
except (json.JSONDecodeError, IOError):
|
||||||
|
leaderboard = []
|
||||||
|
else:
|
||||||
|
leaderboard = []
|
||||||
|
|
||||||
|
def save_leaderboard():
|
||||||
|
"""Save leaderboard to file"""
|
||||||
|
try:
|
||||||
|
with open(LEADERBOARD_FILE, 'w') as f:
|
||||||
|
json.dump(leaderboard, f, indent=4)
|
||||||
|
except IOError as e:
|
||||||
|
print(f"Error saving leaderboard: {e}")
|
||||||
|
|
||||||
def init_game(days):
|
def init_game(days):
|
||||||
"""Initialize a new game session"""
|
"""Initialize a new game session"""
|
||||||
return {
|
# Generate random offsets for initial prices for each company
|
||||||
|
price_offsets = {company['key']: random.randint(-100, 100) for company in COMPANIES}
|
||||||
|
|
||||||
|
# Build state with dynamic company prices and history
|
||||||
|
state = {
|
||||||
'balance': 1000,
|
'balance': 1000,
|
||||||
'kwiktripStockPrice': 100 + random.randint(-100, 100),
|
|
||||||
'appleStockPrice': 100 + random.randint(-100, 100),
|
|
||||||
'microsoftStockPrice': 100 + random.randint(-100, 100),
|
|
||||||
'walmartStockPrice': 100 + random.randint(-100, 100),
|
|
||||||
'carStockPrice': 100 + random.randint(-100, 100),
|
|
||||||
'kwiktrip': 0,
|
|
||||||
'apple': 0,
|
|
||||||
'microsoft': 0,
|
|
||||||
'walmart': 0,
|
|
||||||
'car': 0,
|
|
||||||
'day': 1,
|
'day': 1,
|
||||||
'daysleft': days,
|
'daysleft': days,
|
||||||
'message': ''
|
'leaderboardDays': days,
|
||||||
|
'message': '',
|
||||||
|
'priceHistory': {},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Add stock prices and holdings for each company
|
||||||
|
for company in COMPANIES:
|
||||||
|
key = company['key']
|
||||||
|
offset = price_offsets[key]
|
||||||
|
# Ensure initial price is at least $1
|
||||||
|
initial_price = max(1, 100 + offset)
|
||||||
|
state[f'{key}StockPrice'] = initial_price
|
||||||
|
state[key] = 0
|
||||||
|
state['priceHistory'][key] = [initial_price]
|
||||||
|
|
||||||
|
return state
|
||||||
|
|
||||||
def calculate_index(state):
|
def calculate_index(state):
|
||||||
"""Calculate market index"""
|
"""Calculate market index"""
|
||||||
prices = [state['kwiktripStockPrice'], state['appleStockPrice'],
|
prices = [state[f"{company['key']}StockPrice"] for company in COMPANIES]
|
||||||
state['microsoftStockPrice'], state['walmartStockPrice'],
|
return sum(prices) / len(prices) if prices else 0
|
||||||
state['carStockPrice']]
|
|
||||||
return sum(prices) / 5
|
|
||||||
|
|
||||||
def get_stock_list(state):
|
def get_stock_list(state):
|
||||||
"""Return list of stocks with prices"""
|
"""Return list of stocks with prices"""
|
||||||
return [
|
return [
|
||||||
{'id': 1, 'name': 'Kwik trip', 'price': state['kwiktripStockPrice']},
|
{'id': company['id'], 'name': company['name'], 'price': state[f"{company['key']}StockPrice"]}
|
||||||
{'id': 2, 'name': 'Apple computers', 'price': state['appleStockPrice']},
|
for company in COMPANIES
|
||||||
{'id': 3, 'name': 'Microsoft', 'price': state['microsoftStockPrice']},
|
|
||||||
{'id': 4, 'name': 'Walmart Super Store', 'price': state['walmartStockPrice']},
|
|
||||||
{'id': 5, 'name': 'Car company', 'price': state['carStockPrice']}
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_holdings(state):
|
def get_holdings(state):
|
||||||
"""Return user's stock holdings"""
|
"""Return user's stock holdings"""
|
||||||
return [
|
return [
|
||||||
{'id': 1, 'name': 'Kwik trip', 'amount': state['kwiktrip']},
|
{'id': company['id'], 'name': company['name'], 'amount': state[company['key']]}
|
||||||
{'id': 2, 'name': 'Apple computers', 'amount': state['apple']},
|
for company in COMPANIES
|
||||||
{'id': 3, 'name': 'Microsoft', 'amount': state['microsoft']},
|
|
||||||
{'id': 4, 'name': 'Walmart Super Store', 'amount': state['walmart']},
|
|
||||||
{'id': 5, 'name': 'Car company', 'amount': state['car']}
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_game_state_data():
|
def get_game_state_data():
|
||||||
@@ -70,7 +110,8 @@ def get_game_state_data():
|
|||||||
'index': round(calculate_index(state), 2),
|
'index': round(calculate_index(state), 2),
|
||||||
'stocks': stocks,
|
'stocks': stocks,
|
||||||
'holdings': holdings,
|
'holdings': holdings,
|
||||||
'message': state.get('message', '')
|
'message': state.get('message', ''),
|
||||||
|
'priceHistory': state.get('priceHistory', {})
|
||||||
}
|
}
|
||||||
|
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
@@ -121,8 +162,9 @@ def buy_stock():
|
|||||||
|
|
||||||
state['balance'] -= total_cost
|
state['balance'] -= total_cost
|
||||||
|
|
||||||
stock_keys = ['kwiktrip', 'apple', 'microsoft', 'walmart', 'car']
|
# Use dynamic COMPANIES list instead of hardcoded array
|
||||||
state[stock_keys[stock_id - 1]] += amount
|
stock_key = COMPANIES[stock_id - 1]['key']
|
||||||
|
state[stock_key] += amount
|
||||||
|
|
||||||
state['message'] = f"Successfully bought {amount} shares of {stocks[stock_id - 1]['name']} for ${total_cost}"
|
state['message'] = f"Successfully bought {amount} shares of {stocks[stock_id - 1]['name']} for ${total_cost}"
|
||||||
|
|
||||||
@@ -157,8 +199,9 @@ def sell_stock():
|
|||||||
|
|
||||||
state['balance'] += total_payout
|
state['balance'] += total_payout
|
||||||
|
|
||||||
stock_keys = ['kwiktrip', 'apple', 'microsoft', 'walmart', 'car']
|
# Use dynamic COMPANIES list instead of hardcoded array
|
||||||
state[stock_keys[stock_id - 1]] -= amount
|
stock_key = COMPANIES[stock_id - 1]['key']
|
||||||
|
state[stock_key] -= amount
|
||||||
|
|
||||||
state['message'] = f"Successfully sold {amount} shares of {stocks[stock_id - 1]['name']} for ${total_payout}"
|
state['message'] = f"Successfully sold {amount} shares of {stocks[stock_id - 1]['name']} for ${total_payout}"
|
||||||
|
|
||||||
@@ -180,21 +223,24 @@ def next_day():
|
|||||||
state['day'] += 1
|
state['day'] += 1
|
||||||
state['daysleft'] -= 1
|
state['daysleft'] -= 1
|
||||||
|
|
||||||
# Update stock prices
|
# Update stock prices dynamically for all companies
|
||||||
state['kwiktripStockPrice'] = abs(state['kwiktripStockPrice'] + random.randint(-100, 100))
|
for company in COMPANIES:
|
||||||
state['appleStockPrice'] = abs(state['appleStockPrice'] + random.randint(-100, 100))
|
key = company['key']
|
||||||
state['microsoftStockPrice'] = abs(state['microsoftStockPrice'] + random.randint(-100, 100))
|
price_key = f"{key}StockPrice"
|
||||||
state['walmartStockPrice'] = abs(state['walmartStockPrice'] + random.randint(-100, 100))
|
new_price = state[price_key] + random.randint(-100, 100)
|
||||||
state['carStockPrice'] = abs(state['carStockPrice'] + 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
|
# Market crash chance
|
||||||
if random.randint(0, 1000) == 555:
|
if random.randint(0, 1000) == 555:
|
||||||
state['kwiktripStockPrice'] = 10
|
# Market crash - set all prices to $1 minimum
|
||||||
state['appleStockPrice'] = 10
|
for company in COMPANIES:
|
||||||
state['microsoftStockPrice'] = 10
|
key = company['key']
|
||||||
state['walmartStockPrice'] = 10
|
crash_price = max(1, int(state[f"{key}StockPrice"] * 0.2)) # Drop to 20% of current price, but no lower than $1
|
||||||
state['carStockPrice'] = 10
|
state[f"{key}StockPrice"] = crash_price
|
||||||
state['message'] = "Market crash! All stocks dropped to $10"
|
state['priceHistory'][key][-1] = crash_price
|
||||||
|
state['message'] = "Market crash! All stocks dropped significantly!"
|
||||||
else:
|
else:
|
||||||
state['message'] = f"Moved to day {state['day']}"
|
state['message'] = f"Moved to day {state['day']}"
|
||||||
|
|
||||||
@@ -226,5 +272,50 @@ def end_game():
|
|||||||
'stocks': stocks
|
'stocks': stocks
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@app.route('/api/save-score', methods=['POST'])
|
||||||
|
def save_score():
|
||||||
|
"""Save game score to leaderboard"""
|
||||||
|
if 'current' not in game_state:
|
||||||
|
return jsonify({'error': 'Game not started'}), 400
|
||||||
|
|
||||||
|
data = request.json
|
||||||
|
player_name = data.get('name', 'Anonymous')
|
||||||
|
|
||||||
|
state = game_state['current']
|
||||||
|
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__':
|
if __name__ == '__main__':
|
||||||
app.run(debug=True)
|
app.run(debug=False)
|
||||||
|
|||||||
Reference in New Issue
Block a user