Adding completed_at and winners to g ames

This commit is contained in:
ryan
2026-01-24 09:57:25 -05:00
parent e431ba45e9
commit d4345a4e09
5 changed files with 159 additions and 27 deletions

View File

@@ -114,6 +114,8 @@ class Game(db.Model):
current_question_index = db.Column(db.Integer, default=0) # Track current question
is_template = db.Column(db.Boolean, default=False) # Mark as reusable template
current_turn_team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True) # Track whose turn it is
completed_at = db.Column(db.DateTime, nullable=True) # When game ended
winners = db.Column(db.JSON, nullable=True) # [{"team_name": str, "score": int}, ...]
# Relationships
teams = db.relationship('Team', back_populates='game', cascade='all, delete-orphan',
@@ -146,7 +148,9 @@ class Game(db.Model):
'total_questions': len(self.game_questions),
'is_template': self.is_template,
'current_turn_team_id': self.current_turn_team_id,
'current_turn_team_name': self.current_turn_team.name if self.current_turn_team else None
'current_turn_team_name': self.current_turn_team.name if self.current_turn_team else None,
'completed_at': self.completed_at.isoformat() if self.completed_at else None,
'winners': self.winners
}
if include_questions:
@@ -194,7 +198,7 @@ class Team(db.Model):
phone_a_friend_count = db.Column(db.Integer, default=5) # Number of phone-a-friend lifelines
# Relationships
game = db.relationship('Game', back_populates='teams')
game = db.relationship('Game', back_populates='teams', foreign_keys=[game_id])
scores = db.relationship('Score', back_populates='team', cascade='all, delete-orphan')
@property

View File

@@ -4,6 +4,16 @@ from backend.models import db, Team
bp = Blueprint('teams', __name__, url_prefix='/api/teams')
@bp.route('/past-names', methods=['GET'])
def get_past_team_names():
"""Get distinct team names from past games"""
past_names = db.session.query(Team.name)\
.distinct()\
.order_by(Team.name)\
.all()
return jsonify([name[0] for name in past_names]), 200
@bp.route('/<int:team_id>', methods=['DELETE'])
def delete_team(team_id):
"""Delete a team"""

View File

@@ -203,20 +203,33 @@ def reset_timer(game, socketio_instance):
def end_game(game, socketio_instance):
"""End/deactivate a game"""
"""End/deactivate a game and record winners"""
from datetime import datetime
# Calculate winners (team(s) with highest score)
if game.teams:
team_scores = [(team.name, team.total_score) for team in game.teams]
if team_scores:
max_score = max(score for _, score in team_scores)
winners = [
{"team_name": name, "score": score}
for name, score in team_scores
if score == max_score
]
game.winners = winners
game.is_active = False
game.completed_at = datetime.utcnow()
db.session.commit()
# Emit game_ended event to all rooms
socketio_instance.emit('game_ended', {
# Emit game_ended event with winners
end_data = {
'game_id': game.id,
'game_name': game.name
}, room=f'game_{game.id}_contestant')
socketio_instance.emit('game_ended', {
'game_id': game.id,
'game_name': game.name
}, room=f'game_{game.id}_admin')
'game_name': game.name,
'winners': game.winners
}
socketio_instance.emit('game_ended', end_data, room=f'game_{game.id}_contestant')
socketio_instance.emit('game_ended', end_data, room=f'game_{game.id}_admin')
def restart_game(game, socketio_instance):

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import { questionsAPI, gamesAPI } from "../../services/api";
import { questionsAPI, gamesAPI, teamsAPI } from "../../services/api";
import AdminNavbar from "../common/AdminNavbar";
export default function GameSetupView() {
@@ -13,11 +13,24 @@ export default function GameSetupView() {
const [showTemplateModal, setShowTemplateModal] = useState(false);
const [templates, setTemplates] = useState([]);
const [randomSelections, setRandomSelections] = useState({});
const [pastTeamNames, setPastTeamNames] = useState([]);
const [showTeamSuggestions, setShowTeamSuggestions] = useState(false);
const teamInputRef = useRef(null);
useEffect(() => {
loadQuestions();
loadPastTeamNames();
}, []);
const loadPastTeamNames = async () => {
try {
const response = await teamsAPI.getPastNames();
setPastTeamNames(response.data);
} catch (error) {
console.error("Error loading past team names:", error);
}
};
const loadQuestions = async () => {
try {
const response = await questionsAPI.getAll();
@@ -100,10 +113,12 @@ export default function GameSetupView() {
setSelectedQuestions((prev) => prev.filter((id) => id !== questionId));
};
const addTeam = () => {
if (newTeamName.trim()) {
setTeams([...teams, newTeamName.trim()]);
const addTeam = (name = newTeamName) => {
const teamName = name.trim();
if (teamName && !teams.includes(teamName)) {
setTeams([...teams, teamName]);
setNewTeamName("");
setShowTeamSuggestions(false);
}
};
@@ -111,6 +126,18 @@ export default function GameSetupView() {
setTeams(teams.filter((_, i) => i !== index));
};
// Filter past team names based on input and exclude already added teams
const filteredSuggestions = pastTeamNames.filter(
(name) =>
name.toLowerCase().includes(newTeamName.toLowerCase()) &&
!teams.includes(name)
);
// Get quick-add suggestions (past names not yet added to this game)
const quickAddSuggestions = pastTeamNames
.filter((name) => !teams.includes(name))
.slice(0, 8);
const updateRandomSelection = (category, count) => {
setRandomSelections((prev) => ({
...prev,
@@ -589,20 +616,97 @@ export default function GameSetupView() {
4. Add Teams
</h2>
<div
style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}
style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem", position: "relative" }}
>
<input
type="text"
value={newTeamName}
onChange={(e) => setNewTeamName(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && addTeam()}
placeholder="Enter team name"
style={{ padding: "0.5rem", flex: 1 }}
/>
<button onClick={addTeam} style={{ padding: "0.5rem 1rem" }}>
<div style={{ flex: 1, position: "relative" }}>
<input
ref={teamInputRef}
type="text"
value={newTeamName}
onChange={(e) => {
setNewTeamName(e.target.value);
setShowTeamSuggestions(e.target.value.length > 0);
}}
onFocus={() => setShowTeamSuggestions(newTeamName.length > 0)}
onBlur={() => {
// Delay hiding to allow click on suggestion
setTimeout(() => setShowTeamSuggestions(false), 200);
}}
onKeyPress={(e) => e.key === "Enter" && addTeam()}
placeholder="Enter team name"
style={{ padding: "0.5rem", width: "100%", boxSizing: "border-box" }}
/>
{showTeamSuggestions && filteredSuggestions.length > 0 && (
<div
style={{
position: "absolute",
top: "100%",
left: 0,
right: 0,
background: "white",
border: "1px solid #ccc",
borderRadius: "4px",
boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
zIndex: 10,
maxHeight: "200px",
overflowY: "auto",
}}
>
{filteredSuggestions.slice(0, 8).map((name) => (
<div
key={name}
onClick={() => addTeam(name)}
style={{
padding: "0.5rem 0.75rem",
cursor: "pointer",
borderBottom: "1px solid #eee",
}}
onMouseEnter={(e) => (e.target.style.background = "#f5f5f5")}
onMouseLeave={(e) => (e.target.style.background = "white")}
>
{name}
</div>
))}
</div>
)}
</div>
<button onClick={() => addTeam()} style={{ padding: "0.5rem 1rem" }}>
Add Team
</button>
</div>
{quickAddSuggestions.length > 0 && (
<div style={{ marginBottom: "1rem" }}>
<p style={{ margin: "0 0 0.5rem 0", fontSize: "0.9rem", color: "#666" }}>
Quick add from past games:
</p>
<div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem" }}>
{quickAddSuggestions.map((name) => (
<button
key={name}
onClick={() => addTeam(name)}
style={{
padding: "0.4rem 0.75rem",
background: "#f5f5f5",
border: "1px solid #ddd",
borderRadius: "16px",
cursor: "pointer",
fontSize: "0.9rem",
}}
onMouseEnter={(e) => {
e.target.style.background = "#e3f2fd";
e.target.style.borderColor = "#2196F3";
}}
onMouseLeave={(e) => {
e.target.style.background = "#f5f5f5";
e.target.style.borderColor = "#ddd";
}}
>
+ {name}
</button>
))}
</div>
</div>
)}
<div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem" }}>
{teams.map((team, index) => (
<div

View File

@@ -85,6 +85,7 @@ export const gamesAPI = {
// Teams API
export const teamsAPI = {
delete: (id) => api.delete(`/teams/${id}`),
getPastNames: () => api.get("/teams/past-names"),
};
// Admin API