Okay, here's a Python-based web app using Flask to display your college baseball game predictions. It assumes your JSON data structure now includes two lists of runs scored for each team in each simulation. The winner is determined by comparing the runs scored.
JSON Structure
The JSON file structure should look like this:
{
"matchups": [
{
"team1": "Team A",
"team2": "Team B",
"simulations": [
{
"team1_runs": [2, 3, 1], // Runs scored by Team A in the simulation
"team2_runs": [1, 1, 0] // Runs scored by Team B in the simulation
},
{
"team1_runs": [0, 0, 1],
"team2_runs": [1, 2, 2]
}
// More simulation objects...
]
},
{
"team1": "Team C",
"team2": "Team D",
"simulations": [
{
"team1_runs": [4, 2, 0],
"team2_runs": [3, 1, 1]
},
{
"team1_runs": [1, 2, 3],
"team2_runs": [0, 1, 0]
}
// More simulation objects...
]
}
// More matchups...
]
}
Code Setup
- app.py: Python Flask web application.
- templates/index.html: HTML template to display the predictions.
File: app.py
from flask import Flask, render_template
import json
app = Flask(__name__)
def calculate_winner(team1_runs, team2_runs):
"""Calculates the winner based on total runs."""
team1_total = sum(team1_runs)
team2_total = sum(team2_runs)
if team1_total > team2_total:
return "team1"
elif team2_total > team1_total:
return "team2"
else:
return "tie"
def calculate_win_probabilities(matchup):
"""Calculates win probabilities for each team."""
team1 = matchup['team1']
team2 = matchup['team2']
simulations = matchup['simulations']
team1_wins = 0
team2_wins = 0
for sim in simulations:
team1_runs = sim['team1_runs']
team2_runs = sim['team2_runs']
winner = calculate_winner(team1_runs, team2_runs)
if winner == "team1":
team1_wins += 1
elif winner == "team2":
team2_wins += 1
total_simulations = len(simulations)
if total_simulations == 0:
return 0, 0 #Avoid division by zero
team1_win_probability = (team1_wins / total_simulations) * 100
team2_win_probability = (team2_wins / total_simulations) * 100
return team1_win_probability, team2_win_probability
@app.route('/')
def index():
"""Renders the main page with predictions."""
try:
with open('data.json', 'r') as f:
data = json.load(f)
matchups = data['matchups']
except FileNotFoundError:
return "Error: data.json not found"
except json.JSONDecodeError:
return "Error: Invalid JSON in data.json"
predictions = []
for matchup in matchups:
team1_win_prob, team2_win_prob = calculate_win_probabilities(matchup)
predictions.append({
'team1': matchup['team1'],
'team2': matchup['team2'],
'team1_win_probability': round(team1_win_prob, 2),
'team2_win_probability': round(team2_win_prob, 2)
})
return render_template('index.html', predictions=predictions)
if __name__ == '__main__':
app.run(debug=True)
File: templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>College Baseball Predictions</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f4f4f4;
}
h1 {
color: #333;
text-align: center;
}
.matchup {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.matchup h2 {
color: #007bff;
}
.matchup p {
font-size: 16px;
margin: 5px 0;
}
</style>
</head>
<body>
<h1>College Baseball Game Predictions</h1>
{% for prediction in predictions %}
<div class="matchup">
<h2>{{ prediction.team1 }} vs {{ prediction.team2 }}</h2>
<p>{{ prediction.team1 }} win probability: {{ prediction.team1_win_probability }}%</p>
<p>{{ prediction.team2 }} win probability: {{ prediction.team2_win_probability }}%</p>
</div>
{% endfor %}
</body>
</html>
Instructions:
- Install Flask: Make sure you have Flask installed.
pip install Flask
- Save Files: Save
app.py and index.html in the same directory. Create a templates subdirectory and put index.html inside it.
- Run the App: Open your terminal, navigate to the directory containing
app.py, and run:
python app.py
- Access in Browser: Open your web browser and go to
http://127.0.0.1:5000/.
Key improvements and explanations:
calculate_winner(team1_runs, team2_runs): Determines the winner of a single simulation by comparing the sum of the runs scored by each team. Handles ties.
calculate_win_probabilities(matchup): Iterates through the simulations, determines the winner of each simulation using calculate_winner, and calculates the win probabilities. Handles the case of zero simulations gracefully to avoid division by zero errors.
- Flask Integration: Uses Flask to create a web server that serves the predictions.
- Data Loading: The Python code loads the JSON file, parses the data, and sends it to the HTML template. Error handling included if the JSON can't be loaded or is malformed.
- HTML Templating: Uses Jinja2 templating (Flask's default) to dynamically generate the HTML content. This keeps your Python code clean and separates the presentation logic from the data processing logic.
- Error Handling: Includes basic error handling for missing or invalid JSON files.
- Clearer Code: The code is now more modular and readable.
This revised solution addresses the requirements more accurately and provides a functional web application using Flask and Jinja2 templating. Remember to adjust the data.json path if necessary for your environment.