Compare commits
115 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc936d7e1c | ||
|
|
1cdf1cf281 | ||
|
|
17f7d8ce7a | ||
|
|
9a5bc888cb | ||
|
|
3dcad3dfdf | ||
|
|
b129aa4f29 | ||
|
|
86697dd454 | ||
|
|
77cbefc30c | ||
|
|
e2c7a55dac | ||
|
|
8d5b2ee655 | ||
|
|
06b15f002d | ||
|
|
76f80f3f44 | ||
|
|
0a9993a82f | ||
|
|
e463d929e3 | ||
|
|
1b923838e0 | ||
|
|
4503198021 | ||
|
|
cb49fd545b | ||
|
|
cb311ec0da | ||
|
|
873bdfc75a | ||
|
|
bd41afbca8 | ||
|
|
21985b7e9b | ||
|
|
56305424ff | ||
|
|
0bfe9d5f9f | ||
|
|
a0bb28d5eb | ||
|
|
55006d6ff4 | ||
|
|
adcc59b6fc | ||
|
|
7e0c006f5e | ||
|
|
02f9b3c44d | ||
|
|
9f75cdb0dc | ||
|
|
519d08a2a6 | ||
|
|
9419cb562e | ||
|
|
17c8e574ab | ||
|
|
94edb685a7 | ||
|
|
6b7d6c459e | ||
|
|
1de282afc2 | ||
|
|
9b0a8295eb | ||
|
|
28a0f90374 | ||
|
|
0df451aa99 | ||
|
|
8d7b024525 | ||
|
|
9c08b4735a | ||
|
|
49916e6a6c | ||
|
|
e0641de449 | ||
|
|
e2a90c0f34 | ||
|
|
86f5222746 | ||
|
|
60997e8ad4 | ||
|
|
3e133b17c0 | ||
|
|
9866fb8e92 | ||
|
|
4a5cfb68f1 | ||
|
|
ebb00f613c | ||
|
|
98aa0823ed | ||
|
|
4a3d62e26e | ||
|
|
d958258066 | ||
|
|
26bc151458 | ||
|
|
0d5c0c613d | ||
|
|
e9692de6c6 | ||
|
|
3414bfad1a | ||
|
|
ecad259db2 | ||
|
|
932e9ca4ef | ||
|
|
10825e8b82 | ||
|
|
53abde53ac | ||
|
|
d7ba3154a1 | ||
|
|
197595fc4d | ||
|
|
e38d8c1561 | ||
|
|
afb4869b21 | ||
|
|
c6769f9257 | ||
|
|
8657a0501f | ||
|
|
730ba9c462 | ||
|
|
1ba80606a7 | ||
|
|
3261e6ee26 | ||
|
|
de3495635b | ||
|
|
4c23f2b4a9 | ||
|
|
7b071afdfb | ||
|
|
c7fb85d281 | ||
|
|
118912dd13 | ||
|
|
0e594a5e28 | ||
|
|
a6ec72d72c | ||
|
|
e2f353d4ab | ||
|
|
e601eb04c9 | ||
|
|
6c771810f7 | ||
|
|
dbad7037d1 | ||
|
|
21362ba125 | ||
|
|
2dcdaf2b49 | ||
|
|
1fa13bbe3b | ||
|
|
a76fd8da32 | ||
|
|
634d101f2c | ||
|
|
28c9882b17 | ||
|
|
a1d8a127dc | ||
|
|
65b4af9831 | ||
|
|
8942238f9c | ||
|
|
7dc27fe882 | ||
|
|
097f241c6f | ||
|
|
1c5d6b09e2 | ||
|
|
889f8ce1cd | ||
|
|
b4e9390f16 | ||
|
|
94e2bdaaa7 | ||
|
|
d322403764 | ||
|
|
9c6ce255bd | ||
|
|
06d52a9d2c | ||
|
|
76cbd4ae22 | ||
|
|
9b04bc85c2 | ||
|
|
2ccbfc8120 | ||
|
|
1678077c53 | ||
|
|
0dbb2d13ed | ||
|
|
82e5226acc | ||
|
|
b81874f5ba | ||
|
|
797d1e0280 | ||
|
|
538ca51ba5 | ||
|
|
9339abe19c | ||
|
|
ac2d53b404 | ||
|
|
7e108a71f9 | ||
|
|
7642d120e2 | ||
|
|
6ba0639d51 | ||
|
|
3b9522fec3 | ||
|
|
aa2093d6c8 | ||
|
|
3227c92d63 |
18
.env.example
18
.env.example
@@ -20,6 +20,24 @@ DEBUG=false
|
|||||||
# Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL
|
# Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL
|
||||||
LOG_LEVEL=INFO
|
LOG_LEVEL=INFO
|
||||||
|
|
||||||
|
# Per-module log level overrides (optional)
|
||||||
|
# These override LOG_LEVEL for specific modules.
|
||||||
|
# LOG_LEVEL_GAME=DEBUG # Core game logic
|
||||||
|
# LOG_LEVEL_AI=DEBUG # AI decisions (very verbose at DEBUG)
|
||||||
|
# LOG_LEVEL_HANDLERS=DEBUG # WebSocket message handlers
|
||||||
|
# LOG_LEVEL_ROOM=DEBUG # Room/lobby management
|
||||||
|
# LOG_LEVEL_AUTH=DEBUG # Auth stack (auth, routers.auth, services.auth_service)
|
||||||
|
# LOG_LEVEL_STORES=DEBUG # Database/Redis operations
|
||||||
|
|
||||||
|
# --- Preset examples ---
|
||||||
|
# Staging (debug game logic, quiet everything else):
|
||||||
|
# LOG_LEVEL=INFO
|
||||||
|
# LOG_LEVEL_GAME=DEBUG
|
||||||
|
# LOG_LEVEL_AI=DEBUG
|
||||||
|
#
|
||||||
|
# Production (minimal logging):
|
||||||
|
# LOG_LEVEL=WARNING
|
||||||
|
|
||||||
# Environment name (development, staging, production)
|
# Environment name (development, staging, production)
|
||||||
ENVIRONMENT=development
|
ENVIRONMENT=development
|
||||||
|
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -201,6 +201,9 @@ pyvenv.cfg
|
|||||||
# Personal notes
|
# Personal notes
|
||||||
lookfah.md
|
lookfah.md
|
||||||
|
|
||||||
|
# Internal docs (deployment info, credentials references, etc.)
|
||||||
|
internal/
|
||||||
|
|
||||||
# Ruff stuff:
|
# Ruff stuff:
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
|
||||||
|
|||||||
@@ -317,7 +317,7 @@ async function loadUsers() {
|
|||||||
<td>${user.games_played} (${user.games_won} wins)</td>
|
<td>${user.games_played} (${user.games_won} wins)</td>
|
||||||
<td>${formatDateShort(user.created_at)}</td>
|
<td>${formatDateShort(user.created_at)}</td>
|
||||||
<td>
|
<td>
|
||||||
<button class="btn btn-small" onclick="viewUser('${user.id}')">View</button>
|
<button class="btn btn-small" data-action="view-user" data-id="${user.id}">View</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
`;
|
`;
|
||||||
@@ -404,7 +404,7 @@ async function loadGames() {
|
|||||||
<td><span class="badge badge-${game.status === 'playing' ? 'success' : 'info'}">${game.status}</span></td>
|
<td><span class="badge badge-${game.status === 'playing' ? 'success' : 'info'}">${game.status}</span></td>
|
||||||
<td>${formatDate(game.created_at)}</td>
|
<td>${formatDate(game.created_at)}</td>
|
||||||
<td>
|
<td>
|
||||||
<button class="btn btn-small btn-danger" onclick="promptEndGame('${game.game_id}')">End</button>
|
<button class="btn btn-small btn-danger" data-action="end-game" data-id="${game.game_id}">End</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
`;
|
`;
|
||||||
@@ -454,7 +454,8 @@ async function loadInvites() {
|
|||||||
<td>${status}</td>
|
<td>${status}</td>
|
||||||
<td>
|
<td>
|
||||||
${invite.is_active && !isExpired && invite.remaining_uses > 0
|
${invite.is_active && !isExpired && invite.remaining_uses > 0
|
||||||
? `<button class="btn btn-small btn-danger" onclick="promptRevokeInvite('${invite.code}')">Revoke</button>`
|
? `<button class="btn btn-small" data-action="copy-invite" data-code="${escapeHtml(invite.code)}">Copy Link</button>
|
||||||
|
<button class="btn btn-small btn-danger" data-action="revoke-invite" data-code="${escapeHtml(invite.code)}">Revoke</button>`
|
||||||
: '-'
|
: '-'
|
||||||
}
|
}
|
||||||
</td>
|
</td>
|
||||||
@@ -619,6 +620,16 @@ async function handleCreateInvite() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function copyInviteLink(code) {
|
||||||
|
const link = `${window.location.origin}/?invite=${encodeURIComponent(code)}`;
|
||||||
|
navigator.clipboard.writeText(link).then(() => {
|
||||||
|
showToast('Invite link copied!', 'success');
|
||||||
|
}).catch(() => {
|
||||||
|
// Fallback: select text for manual copy
|
||||||
|
prompt('Copy this link:', link);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async function promptRevokeInvite(code) {
|
async function promptRevokeInvite(code) {
|
||||||
if (!confirm(`Are you sure you want to revoke invite code ${code}?`)) return;
|
if (!confirm(`Are you sure you want to revoke invite code ${code}?`)) return;
|
||||||
|
|
||||||
@@ -804,6 +815,18 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Delegated click handlers for dynamically-created buttons
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
const btn = e.target.closest('[data-action]');
|
||||||
|
if (!btn) return;
|
||||||
|
|
||||||
|
const action = btn.dataset.action;
|
||||||
|
if (action === 'view-user') viewUser(btn.dataset.id);
|
||||||
|
else if (action === 'end-game') promptEndGame(btn.dataset.id);
|
||||||
|
else if (action === 'copy-invite') copyInviteLink(btn.dataset.code);
|
||||||
|
else if (action === 'revoke-invite') promptRevokeInvite(btn.dataset.code);
|
||||||
|
});
|
||||||
|
|
||||||
// Check auth on load
|
// Check auth on load
|
||||||
checkAuth();
|
checkAuth();
|
||||||
});
|
});
|
||||||
|
|||||||
405
client/app.js
405
client/app.js
@@ -90,10 +90,20 @@ class GolfGame {
|
|||||||
}
|
}
|
||||||
|
|
||||||
initMobileDetection() {
|
initMobileDetection() {
|
||||||
|
// Set --app-height custom property to actual visible viewport height.
|
||||||
|
// This works around Chrome Android's 100vh bug where vh includes the
|
||||||
|
// space behind the dynamic URL bar.
|
||||||
|
const setAppHeight = () => {
|
||||||
|
document.documentElement.style.setProperty('--app-height', `${window.innerHeight}px`);
|
||||||
|
};
|
||||||
|
window.addEventListener('resize', setAppHeight);
|
||||||
|
setAppHeight();
|
||||||
|
|
||||||
const mql = window.matchMedia('(max-width: 500px) and (orientation: portrait)');
|
const mql = window.matchMedia('(max-width: 500px) and (orientation: portrait)');
|
||||||
const update = (e) => {
|
const update = (e) => {
|
||||||
this.isMobile = e.matches;
|
this.isMobile = e.matches;
|
||||||
document.body.classList.toggle('mobile-portrait', e.matches);
|
document.body.classList.toggle('mobile-portrait', e.matches);
|
||||||
|
setAppHeight();
|
||||||
// Close any open drawers on layout change
|
// Close any open drawers on layout change
|
||||||
if (!e.matches) {
|
if (!e.matches) {
|
||||||
this.closeDrawers();
|
this.closeDrawers();
|
||||||
@@ -119,6 +129,7 @@ class GolfGame {
|
|||||||
panel.classList.add('drawer-open');
|
panel.classList.add('drawer-open');
|
||||||
btn.classList.add('active');
|
btn.classList.add('active');
|
||||||
if (backdrop) backdrop.classList.add('visible');
|
if (backdrop) backdrop.classList.add('visible');
|
||||||
|
if (bottomBar) bottomBar.classList.add('hidden');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -132,6 +143,8 @@ class GolfGame {
|
|||||||
document.querySelectorAll('.mobile-bar-btn.active').forEach(b => b.classList.remove('active'));
|
document.querySelectorAll('.mobile-bar-btn.active').forEach(b => b.classList.remove('active'));
|
||||||
const backdrop = document.getElementById('drawer-backdrop');
|
const backdrop = document.getElementById('drawer-backdrop');
|
||||||
if (backdrop) backdrop.classList.remove('visible');
|
if (backdrop) backdrop.classList.remove('visible');
|
||||||
|
const bottomBar = document.getElementById('mobile-bottom-bar');
|
||||||
|
if (bottomBar) bottomBar.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
initAudio() {
|
initAudio() {
|
||||||
@@ -366,7 +379,7 @@ class GolfGame {
|
|||||||
// Only show tooltips on your turn
|
// Only show tooltips on your turn
|
||||||
if (!this.isMyTurn() && !this.gameState?.waiting_for_initial_flip) return;
|
if (!this.isMyTurn() && !this.gameState?.waiting_for_initial_flip) return;
|
||||||
|
|
||||||
const value = this.getCardPointValue(cardData);
|
const value = this.getCardPointValueForTooltip(cardData);
|
||||||
const special = this.getCardSpecialNote(cardData);
|
const special = this.getCardSpecialNote(cardData);
|
||||||
|
|
||||||
let content = `<span class="tooltip-value ${value < 0 ? 'negative' : ''}">${value} pts</span>`;
|
let content = `<span class="tooltip-value ${value < 0 ? 'negative' : ''}">${value} pts</span>`;
|
||||||
@@ -396,14 +409,15 @@ class GolfGame {
|
|||||||
if (this.tooltip) this.tooltip.classList.add('hidden');
|
if (this.tooltip) this.tooltip.classList.add('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
getCardPointValue(cardData) {
|
getCardPointValueForTooltip(cardData) {
|
||||||
const values = this.gameState?.card_values || this.getDefaultCardValues();
|
const values = this.gameState?.card_values || this.getDefaultCardValues();
|
||||||
return values[cardData.rank] ?? 0;
|
const rules = this.gameState?.scoring_rules || {};
|
||||||
|
return this.getCardPointValue(cardData, values, rules);
|
||||||
}
|
}
|
||||||
|
|
||||||
getCardSpecialNote(cardData) {
|
getCardSpecialNote(cardData) {
|
||||||
const rank = cardData.rank;
|
const rank = cardData.rank;
|
||||||
const value = this.getCardPointValue(cardData);
|
const value = this.getCardPointValueForTooltip(cardData);
|
||||||
if (value < 0) return 'Negative - keep it!';
|
if (value < 0) return 'Negative - keep it!';
|
||||||
if (rank === 'K' && value === 0) return 'Safe card';
|
if (rank === 'K' && value === 0) return 'Safe card';
|
||||||
if (rank === 'K' && value === -2) return 'Super King!';
|
if (rank === 'K' && value === -2) return 'Super King!';
|
||||||
@@ -545,6 +559,8 @@ class GolfGame {
|
|||||||
this.addSelectedCpusBtn.addEventListener('click', () => { this.playSound('success'); this.addSelectedCpus(); });
|
this.addSelectedCpusBtn.addEventListener('click', () => { this.playSound('success'); this.addSelectedCpus(); });
|
||||||
this.muteBtn.addEventListener('click', () => this.toggleSound());
|
this.muteBtn.addEventListener('click', () => this.toggleSound());
|
||||||
this.leaveGameBtn.addEventListener('click', () => { this.playSound('click'); this.leaveGame(); });
|
this.leaveGameBtn.addEventListener('click', () => { this.playSound('click'); this.leaveGame(); });
|
||||||
|
const mobileLeaveBtn = document.getElementById('mobile-leave-btn');
|
||||||
|
if (mobileLeaveBtn) mobileLeaveBtn.addEventListener('click', () => { this.playSound('click'); this.leaveGame(); });
|
||||||
this.gameLogoutBtn.addEventListener('click', () => { this.playSound('click'); this.auth?.logout(); });
|
this.gameLogoutBtn.addEventListener('click', () => { this.playSound('click'); this.auth?.logout(); });
|
||||||
|
|
||||||
// Copy room code to clipboard
|
// Copy room code to clipboard
|
||||||
@@ -807,11 +823,29 @@ class GolfGame {
|
|||||||
newState.phase === 'round_over';
|
newState.phase === 'round_over';
|
||||||
|
|
||||||
if (roundJustEnded && oldState) {
|
if (roundJustEnded && oldState) {
|
||||||
// Save pre-reveal state for the reveal animation
|
// Update state first so animations can read new card data
|
||||||
this.preRevealState = JSON.parse(JSON.stringify(oldState));
|
|
||||||
this.postRevealState = newState;
|
|
||||||
// Update state but DON'T render yet - reveal animation will handle it
|
|
||||||
this.gameState = newState;
|
this.gameState = newState;
|
||||||
|
|
||||||
|
// Fire animations for the last turn (swap/discard) before deferring
|
||||||
|
try {
|
||||||
|
this.triggerAnimationsForStateChange(oldState, newState);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Animation error on round end:', e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build preRevealState from oldState, but mark swap position as
|
||||||
|
// already handled so reveal animation doesn't double-flip it
|
||||||
|
const preReveal = JSON.parse(JSON.stringify(oldState));
|
||||||
|
if (this.opponentSwapAnimation) {
|
||||||
|
const { playerId, position } = this.opponentSwapAnimation;
|
||||||
|
const player = preReveal.players.find(p => p.id === playerId);
|
||||||
|
if (player?.cards[position]) {
|
||||||
|
player.cards[position].face_up = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.preRevealState = preReveal;
|
||||||
|
this.postRevealState = newState;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -908,16 +942,16 @@ class GolfGame {
|
|||||||
this.displayHeldCard(data.card, true);
|
this.displayHeldCard(data.card, true);
|
||||||
this.renderGame();
|
this.renderGame();
|
||||||
}
|
}
|
||||||
this.showToast('Swap with a card or discard', '', 3000);
|
this.showToast('Swap with a card or discard', 'your-turn', 3000);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'can_flip':
|
case 'can_flip':
|
||||||
this.waitingForFlip = true;
|
this.waitingForFlip = true;
|
||||||
this.flipIsOptional = data.optional || false;
|
this.flipIsOptional = data.optional || false;
|
||||||
if (this.flipIsOptional) {
|
if (this.flipIsOptional) {
|
||||||
this.showToast('Flip a card or skip', '', 3000);
|
this.showToast('Flip a card or skip', 'your-turn', 3000);
|
||||||
} else {
|
} else {
|
||||||
this.showToast('Flip a face-down card', '', 3000);
|
this.showToast('Flip a face-down card', 'your-turn', 3000);
|
||||||
}
|
}
|
||||||
this.renderGame();
|
this.renderGame();
|
||||||
break;
|
break;
|
||||||
@@ -935,7 +969,7 @@ class GolfGame {
|
|||||||
// Host ended the game or player was kicked
|
// Host ended the game or player was kicked
|
||||||
this._intentionalClose = true;
|
this._intentionalClose = true;
|
||||||
if (this.ws) this.ws.close();
|
if (this.ws) this.ws.close();
|
||||||
this.showScreen('lobby');
|
this.showLobby();
|
||||||
if (data.reason) {
|
if (data.reason) {
|
||||||
this.showError(data.reason);
|
this.showError(data.reason);
|
||||||
}
|
}
|
||||||
@@ -960,7 +994,7 @@ class GolfGame {
|
|||||||
|
|
||||||
case 'queue_left':
|
case 'queue_left':
|
||||||
this.stopMatchmakingTimer();
|
this.stopMatchmakingTimer();
|
||||||
this.showScreen('lobby');
|
this.showLobby();
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'error':
|
case 'error':
|
||||||
@@ -980,7 +1014,7 @@ class GolfGame {
|
|||||||
cancelMatchmaking() {
|
cancelMatchmaking() {
|
||||||
this.send({ type: 'queue_leave' });
|
this.send({ type: 'queue_leave' });
|
||||||
this.stopMatchmakingTimer();
|
this.stopMatchmakingTimer();
|
||||||
this.showScreen('lobby');
|
this.showLobby();
|
||||||
}
|
}
|
||||||
|
|
||||||
startMatchmakingTimer() {
|
startMatchmakingTimer() {
|
||||||
@@ -1416,8 +1450,9 @@ class GolfGame {
|
|||||||
this.swapAnimationCardEl = handCardEl;
|
this.swapAnimationCardEl = handCardEl;
|
||||||
this.swapAnimationHandCardEl = handCardEl;
|
this.swapAnimationHandCardEl = handCardEl;
|
||||||
|
|
||||||
// Hide originals during animation
|
// Hide originals and UI during animation
|
||||||
handCardEl.classList.add('swap-out');
|
handCardEl.classList.add('swap-out');
|
||||||
|
this.discardBtn.classList.add('hidden');
|
||||||
if (this.heldCardFloating) {
|
if (this.heldCardFloating) {
|
||||||
this.heldCardFloating.style.visibility = 'hidden';
|
this.heldCardFloating.style.visibility = 'hidden';
|
||||||
}
|
}
|
||||||
@@ -1558,11 +1593,29 @@ class GolfGame {
|
|||||||
this.heldCardFloating.classList.add('hidden');
|
this.heldCardFloating.classList.add('hidden');
|
||||||
|
|
||||||
if (this.pendingGameState) {
|
if (this.pendingGameState) {
|
||||||
this.gameState = this.pendingGameState;
|
const oldState = this.gameState;
|
||||||
|
const newState = this.pendingGameState;
|
||||||
this.pendingGameState = null;
|
this.pendingGameState = null;
|
||||||
|
|
||||||
|
// Check if the deferred state is a round_over transition
|
||||||
|
const roundJustEnded = oldState?.phase !== 'round_over' &&
|
||||||
|
newState.phase === 'round_over';
|
||||||
|
|
||||||
|
if (roundJustEnded && oldState) {
|
||||||
|
// Same intercept as the game_state handler: store pre/post
|
||||||
|
// reveal states so runRoundEndReveal can animate the reveal
|
||||||
|
this.gameState = newState;
|
||||||
|
const preReveal = JSON.parse(JSON.stringify(oldState));
|
||||||
|
this.preRevealState = preReveal;
|
||||||
|
this.postRevealState = newState;
|
||||||
|
// Don't renderGame - let the reveal sequence handle it
|
||||||
|
} else {
|
||||||
|
this.gameState = newState;
|
||||||
|
this.checkForNewPairs(oldState, newState);
|
||||||
this.renderGame();
|
this.renderGame();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
flipCard(position) {
|
flipCard(position) {
|
||||||
this.send({ type: 'flip_card', position });
|
this.send({ type: 'flip_card', position });
|
||||||
@@ -1703,7 +1756,8 @@ class GolfGame {
|
|||||||
|
|
||||||
// Badge
|
// Badge
|
||||||
let badge = '';
|
let badge = '';
|
||||||
if (isKnocker) badge = '<span class="ss-badge ss-badge-knock">KNOCKED</span>';
|
if (isKnocker && isLowScore) badge = '<span class="ss-badge ss-badge-knock">KNOCKED</span><span class="ss-badge ss-badge-low">LOW SCORE</span>';
|
||||||
|
else if (isKnocker) badge = '<span class="ss-badge ss-badge-knock">KNOCKED</span>';
|
||||||
else if (isLowScore) badge = '<span class="ss-badge ss-badge-low">LOW SCORE</span>';
|
else if (isLowScore) badge = '<span class="ss-badge ss-badge-low">LOW SCORE</span>';
|
||||||
|
|
||||||
// Build columns
|
// Build columns
|
||||||
@@ -1773,6 +1827,10 @@ class GolfGame {
|
|||||||
document.body.appendChild(modal);
|
document.body.appendChild(modal);
|
||||||
this.setStatus('Hole complete');
|
this.setStatus('Hole complete');
|
||||||
|
|
||||||
|
// Hide bottom bar so it doesn't overlay the modal
|
||||||
|
const bottomBar = document.getElementById('mobile-bottom-bar');
|
||||||
|
if (bottomBar) bottomBar.classList.add('hidden');
|
||||||
|
|
||||||
// Bind next button
|
// Bind next button
|
||||||
const nextBtn = document.getElementById('ss-next-btn');
|
const nextBtn = document.getElementById('ss-next-btn');
|
||||||
nextBtn.addEventListener('click', () => {
|
nextBtn.addEventListener('click', () => {
|
||||||
@@ -1902,6 +1960,10 @@ class GolfGame {
|
|||||||
this.clearScoresheetCountdown();
|
this.clearScoresheetCountdown();
|
||||||
const modal = document.getElementById('scoresheet-modal');
|
const modal = document.getElementById('scoresheet-modal');
|
||||||
if (modal) modal.remove();
|
if (modal) modal.remove();
|
||||||
|
|
||||||
|
// Restore bottom bar
|
||||||
|
const bottomBar = document.getElementById('mobile-bottom-bar');
|
||||||
|
if (bottomBar) bottomBar.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- V3_02: Dealing Animation ---
|
// --- V3_02: Dealing Animation ---
|
||||||
@@ -2037,6 +2099,16 @@ class GolfGame {
|
|||||||
|
|
||||||
async runRoundEndReveal(scores, rankings) {
|
async runRoundEndReveal(scores, rankings) {
|
||||||
const T = window.TIMING?.reveal || {};
|
const T = window.TIMING?.reveal || {};
|
||||||
|
|
||||||
|
// preRevealState may not be set yet if the game_state was deferred
|
||||||
|
// (e.g., local swap animation was in progress). Wait briefly for it.
|
||||||
|
if (!this.preRevealState) {
|
||||||
|
const waitStart = Date.now();
|
||||||
|
while (!this.preRevealState && Date.now() - waitStart < 3000) {
|
||||||
|
await this.delay(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const oldState = this.preRevealState;
|
const oldState = this.preRevealState;
|
||||||
const newState = this.postRevealState || this.gameState;
|
const newState = this.postRevealState || this.gameState;
|
||||||
|
|
||||||
@@ -2046,22 +2118,35 @@ class GolfGame {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// First, render the game with the OLD state (pre-reveal) so cards show face-down
|
// Compute what needs revealing (before renderGame changes the DOM)
|
||||||
this.gameState = newState;
|
|
||||||
// But render with pre-reveal card visuals
|
|
||||||
this.revealAnimationInProgress = true;
|
|
||||||
|
|
||||||
// Render game to show current layout (opponents, etc)
|
|
||||||
this.renderGame();
|
|
||||||
|
|
||||||
// Compute what needs revealing
|
|
||||||
const revealsByPlayer = this.getCardsToReveal(oldState, newState);
|
const revealsByPlayer = this.getCardsToReveal(oldState, newState);
|
||||||
|
|
||||||
// Get reveal order: knocker first, then clockwise
|
// Get reveal order: knocker first, then clockwise
|
||||||
const knockerId = newState.finisher_id;
|
const knockerId = newState.finisher_id;
|
||||||
const revealOrder = this.getRevealOrder(newState.players, knockerId);
|
const revealOrder = this.getRevealOrder(newState.players, knockerId);
|
||||||
|
|
||||||
// Initial pause
|
// Wait for the last player's animation (swap/discard/draw) to finish
|
||||||
|
// so the final play is visible before the reveal sequence starts
|
||||||
|
const maxWait = 3000;
|
||||||
|
const start = Date.now();
|
||||||
|
while (Date.now() - start < maxWait) {
|
||||||
|
if (!this.isDrawAnimating && !this.opponentSwapAnimation &&
|
||||||
|
!this.opponentDiscardAnimating && !this.localDiscardAnimating &&
|
||||||
|
!this.swapAnimationInProgress) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await this.delay(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extra pause so the final play registers visually before we
|
||||||
|
// re-render the board (renderGame below resets card positions)
|
||||||
|
await this.delay(T.lastPlayPause || 2500);
|
||||||
|
|
||||||
|
// Now render with pre-reveal state (face-down cards) for the reveal sequence
|
||||||
|
this.gameState = newState;
|
||||||
|
this.revealAnimationInProgress = true;
|
||||||
|
this.renderGame();
|
||||||
|
|
||||||
this.setStatus('Revealing cards...', 'reveal');
|
this.setStatus('Revealing cards...', 'reveal');
|
||||||
await this.delay(T.initialPause || 500);
|
await this.delay(T.initialPause || 500);
|
||||||
|
|
||||||
@@ -2388,8 +2473,13 @@ class GolfGame {
|
|||||||
this.opponentDiscardAnimating = false;
|
this.opponentDiscardAnimating = false;
|
||||||
// Set isDrawAnimating to block renderGame from updating discard pile
|
// Set isDrawAnimating to block renderGame from updating discard pile
|
||||||
this.isDrawAnimating = true;
|
this.isDrawAnimating = true;
|
||||||
|
// Force discard DOM to show the card being drawn before animation starts
|
||||||
|
// (previous animation may have blocked renderGame from updating it)
|
||||||
|
if (oldDiscard) {
|
||||||
|
this.updateDiscardPileDisplay(oldDiscard);
|
||||||
|
}
|
||||||
console.log('[DEBUG] Opponent draw from discard - setting isDrawAnimating=true');
|
console.log('[DEBUG] Opponent draw from discard - setting isDrawAnimating=true');
|
||||||
window.drawAnimations.animateDrawDiscard(drawnCard, () => {
|
window.drawAnimations.animateDrawDiscard(oldDiscard || drawnCard, () => {
|
||||||
console.log('[DEBUG] Opponent draw from discard complete - clearing isDrawAnimating');
|
console.log('[DEBUG] Opponent draw from discard complete - clearing isDrawAnimating');
|
||||||
this.isDrawAnimating = false;
|
this.isDrawAnimating = false;
|
||||||
onAnimComplete();
|
onAnimComplete();
|
||||||
@@ -2399,7 +2489,7 @@ class GolfGame {
|
|||||||
this.opponentSwapAnimation = null;
|
this.opponentSwapAnimation = null;
|
||||||
this.opponentDiscardAnimating = false;
|
this.opponentDiscardAnimating = false;
|
||||||
this.isDrawAnimating = true;
|
this.isDrawAnimating = true;
|
||||||
console.log('[DEBUG] Opponent draw from deck - setting isDrawAnimating=true');
|
console.log('[DEBUG] Opponent draw from deck - setting isDrawAnimating=true, drawnCard:', drawnCard ? `${drawnCard.rank} of ${drawnCard.suit}` : 'NULL', 'discardTop:', newDiscard ? `${newDiscard.rank} of ${newDiscard.suit}` : 'EMPTY');
|
||||||
window.drawAnimations.animateDrawDeck(drawnCard, () => {
|
window.drawAnimations.animateDrawDeck(drawnCard, () => {
|
||||||
console.log('[DEBUG] Opponent draw from deck complete - clearing isDrawAnimating');
|
console.log('[DEBUG] Opponent draw from deck complete - clearing isDrawAnimating');
|
||||||
this.isDrawAnimating = false;
|
this.isDrawAnimating = false;
|
||||||
@@ -2480,6 +2570,7 @@ class GolfGame {
|
|||||||
const cardsIdentical = wasOtherPlayer && JSON.stringify(oldPlayer.cards) === JSON.stringify(newPlayer.cards);
|
const cardsIdentical = wasOtherPlayer && JSON.stringify(oldPlayer.cards) === JSON.stringify(newPlayer.cards);
|
||||||
|
|
||||||
if (swappedPosition >= 0 && wasOtherPlayer) {
|
if (swappedPosition >= 0 && wasOtherPlayer) {
|
||||||
|
console.log('[DEBUG] Swap detected:', { playerId: previousPlayerId, position: swappedPosition, wasFaceUp, newDiscard: newDiscard?.rank });
|
||||||
// Opponent swapped - animate from the actual position that changed
|
// Opponent swapped - animate from the actual position that changed
|
||||||
this.fireSwapAnimation(previousPlayerId, newDiscard, swappedPosition, wasFaceUp);
|
this.fireSwapAnimation(previousPlayerId, newDiscard, swappedPosition, wasFaceUp);
|
||||||
// Show CPU swap announcement
|
// Show CPU swap announcement
|
||||||
@@ -2583,6 +2674,7 @@ class GolfGame {
|
|||||||
}
|
}
|
||||||
|
|
||||||
firePairCelebration(playerId, pos1, pos2) {
|
firePairCelebration(playerId, pos1, pos2) {
|
||||||
|
this.playSound('pair');
|
||||||
const elements = this.getCardElements(playerId, pos1, pos2);
|
const elements = this.getCardElements(playerId, pos1, pos2);
|
||||||
if (elements.length < 2) return;
|
if (elements.length < 2) return;
|
||||||
|
|
||||||
@@ -2780,16 +2872,7 @@ class GolfGame {
|
|||||||
|
|
||||||
// Use unified swap animation
|
// Use unified swap animation
|
||||||
if (window.cardAnimations) {
|
if (window.cardAnimations) {
|
||||||
// For opponent swaps, size the held card to match the opponent card
|
const heldRect = window.cardAnimations.getHoldingRect();
|
||||||
// rather than the deck size (default holding rect uses deck dimensions,
|
|
||||||
// which looks oversized next to small opponent cards on mobile)
|
|
||||||
const holdingRect = window.cardAnimations.getHoldingRect();
|
|
||||||
const heldRect = holdingRect ? {
|
|
||||||
left: holdingRect.left,
|
|
||||||
top: holdingRect.top,
|
|
||||||
width: sourceRect.width,
|
|
||||||
height: sourceRect.height
|
|
||||||
} : null;
|
|
||||||
|
|
||||||
window.cardAnimations.animateUnifiedSwap(
|
window.cardAnimations.animateUnifiedSwap(
|
||||||
discardCard, // handCardData - card going to discard
|
discardCard, // handCardData - card going to discard
|
||||||
@@ -2800,22 +2883,28 @@ class GolfGame {
|
|||||||
rotation: sourceRotation,
|
rotation: sourceRotation,
|
||||||
wasHandFaceDown: !wasFaceUp,
|
wasHandFaceDown: !wasFaceUp,
|
||||||
onComplete: () => {
|
onComplete: () => {
|
||||||
sourceCardEl.classList.remove('swap-out');
|
if (sourceCardEl) sourceCardEl.classList.remove('swap-out');
|
||||||
this.opponentSwapAnimation = null;
|
this.opponentSwapAnimation = null;
|
||||||
this.opponentDiscardAnimating = false;
|
this.opponentDiscardAnimating = false;
|
||||||
console.log('[DEBUG] Swap animation complete - clearing opponentSwapAnimation and opponentDiscardAnimating');
|
console.log('[DEBUG] Swap animation complete - clearing opponentSwapAnimation and opponentDiscardAnimating');
|
||||||
|
// Don't re-render during reveal animation - it handles its own rendering
|
||||||
|
if (!this.revealAnimationInProgress) {
|
||||||
this.renderGame();
|
this.renderGame();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// Fallback
|
// Fallback
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
sourceCardEl.classList.remove('swap-out');
|
if (sourceCardEl) sourceCardEl.classList.remove('swap-out');
|
||||||
this.opponentSwapAnimation = null;
|
this.opponentSwapAnimation = null;
|
||||||
this.opponentDiscardAnimating = false;
|
this.opponentDiscardAnimating = false;
|
||||||
console.log('[DEBUG] Swap animation fallback complete - clearing flags');
|
console.log('[DEBUG] Swap animation fallback complete - clearing flags');
|
||||||
|
// Don't re-render during reveal animation - it handles its own rendering
|
||||||
|
if (!this.revealAnimationInProgress) {
|
||||||
this.renderGame();
|
this.renderGame();
|
||||||
|
}
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2837,6 +2926,11 @@ class GolfGame {
|
|||||||
if (window.cardAnimations) {
|
if (window.cardAnimations) {
|
||||||
window.cardAnimations.animateInitialFlip(cardEl, cardData, () => {
|
window.cardAnimations.animateInitialFlip(cardEl, cardData, () => {
|
||||||
this.animatingPositions.delete(key);
|
this.animatingPositions.delete(key);
|
||||||
|
// Unhide the current card element (may have been rebuilt by renderGame)
|
||||||
|
const currentCards = this.playerCards.querySelectorAll('.card');
|
||||||
|
if (currentCards[position]) {
|
||||||
|
currentCards[position].style.visibility = '';
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Fallback if card animations not available
|
// Fallback if card animations not available
|
||||||
@@ -2941,7 +3035,7 @@ class GolfGame {
|
|||||||
this.hideToast();
|
this.hideToast();
|
||||||
} else {
|
} else {
|
||||||
const remaining = requiredFlips - uniquePositions.length;
|
const remaining = requiredFlips - uniquePositions.length;
|
||||||
this.showToast(`Select ${remaining} more card${remaining > 1 ? 's' : ''} to flip`, '', 5000);
|
this.showToast(`Select ${remaining} more card${remaining > 1 ? 's' : ''} to flip`, 'your-turn', 5000);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -3039,6 +3133,14 @@ class GolfGame {
|
|||||||
}
|
}
|
||||||
|
|
||||||
showLobby() {
|
showLobby() {
|
||||||
|
if (window.cardAnimations) {
|
||||||
|
window.cardAnimations.cancelAll();
|
||||||
|
}
|
||||||
|
this.dealAnimationInProgress = false;
|
||||||
|
this.isDrawAnimating = false;
|
||||||
|
this.localDiscardAnimating = false;
|
||||||
|
this.opponentDiscardAnimating = false;
|
||||||
|
this.opponentSwapAnimation = false;
|
||||||
this.showScreen(this.lobbyScreen);
|
this.showScreen(this.lobbyScreen);
|
||||||
this.lobbyError.textContent = '';
|
this.lobbyError.textContent = '';
|
||||||
this.roomCode = null;
|
this.roomCode = null;
|
||||||
@@ -3073,7 +3175,10 @@ class GolfGame {
|
|||||||
this.waitingForFlip = false;
|
this.waitingForFlip = false;
|
||||||
this.previousState = null;
|
this.previousState = null;
|
||||||
// Update leave button text based on role
|
// Update leave button text based on role
|
||||||
this.leaveGameBtn.textContent = this.isHost ? 'End Game' : 'Leave';
|
const leaveText = this.isHost ? 'End Game' : 'Leave';
|
||||||
|
this.leaveGameBtn.textContent = leaveText;
|
||||||
|
const mobileLeave = document.getElementById('mobile-leave-btn');
|
||||||
|
if (mobileLeave) mobileLeave.textContent = leaveText;
|
||||||
// Update active rules bar
|
// Update active rules bar
|
||||||
this.updateActiveRulesBar();
|
this.updateActiveRulesBar();
|
||||||
}
|
}
|
||||||
@@ -3108,6 +3213,24 @@ class GolfGame {
|
|||||||
`<span class="rule-tag rule-more" title="${tooltip}">+${moreCount} more</span>`;
|
`<span class="rule-tag rule-more" title="${tooltip}">+${moreCount} more</span>`;
|
||||||
}
|
}
|
||||||
this.activeRulesBar.classList.remove('hidden');
|
this.activeRulesBar.classList.remove('hidden');
|
||||||
|
|
||||||
|
// Update mobile rules indicator
|
||||||
|
const mobileRulesBtn = document.getElementById('mobile-rules-btn');
|
||||||
|
const mobileRulesIcon = document.getElementById('mobile-rules-icon');
|
||||||
|
const mobileRulesContent = document.getElementById('mobile-rules-content');
|
||||||
|
if (mobileRulesBtn && mobileRulesIcon && mobileRulesContent) {
|
||||||
|
const isHouseRules = rules.length > 0;
|
||||||
|
mobileRulesIcon.textContent = isHouseRules ? '!' : 'RULES';
|
||||||
|
mobileRulesBtn.classList.toggle('house-rules', isHouseRules);
|
||||||
|
|
||||||
|
if (!isHouseRules) {
|
||||||
|
mobileRulesContent.innerHTML = '<div class="mobile-rules-content-list"><span class="rule-tag standard">Standard Rules</span></div>';
|
||||||
|
} else {
|
||||||
|
const tagHtml = (unrankedTag ? '<span class="rule-tag unranked">Unranked</span>' : '') +
|
||||||
|
rules.map(renderTag).join('');
|
||||||
|
mobileRulesContent.innerHTML = `<div class="mobile-rules-content-list">${tagHtml}</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// V3_14: Map display names to rule keys
|
// V3_14: Map display names to rule keys
|
||||||
@@ -3419,15 +3542,6 @@ class GolfGame {
|
|||||||
// Toggle game area class for border pulse
|
// Toggle game area class for border pulse
|
||||||
this.gameScreen.classList.add('final-turn-active');
|
this.gameScreen.classList.add('final-turn-active');
|
||||||
|
|
||||||
// Calculate remaining turns
|
|
||||||
const remaining = this.countRemainingTurns();
|
|
||||||
|
|
||||||
// Update badge content
|
|
||||||
const remainingEl = this.finalTurnBadge.querySelector('.final-turn-remaining');
|
|
||||||
if (remainingEl) {
|
|
||||||
remainingEl.textContent = remaining === 1 ? '1 turn left' : `${remaining} turns left`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show badge
|
// Show badge
|
||||||
this.finalTurnBadge.classList.remove('hidden');
|
this.finalTurnBadge.classList.remove('hidden');
|
||||||
|
|
||||||
@@ -3523,7 +3637,9 @@ class GolfGame {
|
|||||||
const cardHeight = deckRect.height;
|
const cardHeight = deckRect.height;
|
||||||
|
|
||||||
// Position card centered, overlapping both piles (lower than before)
|
// Position card centered, overlapping both piles (lower than before)
|
||||||
const overlapOffset = cardHeight * 0.35; // More overlap = lower position
|
// On mobile portrait, place held card fully above the deck/discard area
|
||||||
|
const isMobilePortrait = document.body.classList.contains('mobile-portrait');
|
||||||
|
const overlapOffset = cardHeight * (isMobilePortrait ? 0.48 : 0.35);
|
||||||
const cardLeft = centerX - cardWidth / 2;
|
const cardLeft = centerX - cardWidth / 2;
|
||||||
const cardTop = deckRect.top - overlapOffset;
|
const cardTop = deckRect.top - overlapOffset;
|
||||||
this.heldCardFloating.style.left = `${cardLeft}px`;
|
this.heldCardFloating.style.left = `${cardLeft}px`;
|
||||||
@@ -3535,11 +3651,21 @@ class GolfGame {
|
|||||||
this.heldCardFloating.style.fontSize = `${cardWidth * 0.35}px`;
|
this.heldCardFloating.style.fontSize = `${cardWidth * 0.35}px`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Position discard button attached to right side of held card
|
// Position discard button
|
||||||
const buttonLeft = cardLeft + cardWidth; // Right edge of card (no gap)
|
if (isMobilePortrait) {
|
||||||
const buttonTop = cardTop + cardHeight * 0.3; // Vertically centered on card
|
// Below the held card, centered
|
||||||
|
const btnRect = this.discardBtn.getBoundingClientRect();
|
||||||
|
const buttonLeft = cardLeft + (cardWidth - (btnRect.width || 70)) / 2;
|
||||||
|
const buttonTop = cardTop + cardHeight + 4;
|
||||||
this.discardBtn.style.left = `${buttonLeft}px`;
|
this.discardBtn.style.left = `${buttonLeft}px`;
|
||||||
this.discardBtn.style.top = `${buttonTop}px`;
|
this.discardBtn.style.top = `${buttonTop}px`;
|
||||||
|
} else {
|
||||||
|
// Right side of held card (desktop)
|
||||||
|
const buttonLeft = cardLeft + cardWidth;
|
||||||
|
const buttonTop = cardTop + cardHeight * 0.3;
|
||||||
|
this.discardBtn.style.left = `${buttonLeft}px`;
|
||||||
|
this.discardBtn.style.top = `${buttonTop}px`;
|
||||||
|
}
|
||||||
|
|
||||||
if (card.rank === '★') {
|
if (card.rank === '★') {
|
||||||
this.heldCardFloating.classList.add('joker');
|
this.heldCardFloating.classList.add('joker');
|
||||||
@@ -3585,7 +3711,8 @@ class GolfGame {
|
|||||||
const centerX = (deckRect.left + deckRect.right + discardRect.left + discardRect.right) / 4;
|
const centerX = (deckRect.left + deckRect.right + discardRect.left + discardRect.right) / 4;
|
||||||
const cardWidth = deckRect.width;
|
const cardWidth = deckRect.width;
|
||||||
const cardHeight = deckRect.height;
|
const cardHeight = deckRect.height;
|
||||||
const overlapOffset = cardHeight * 0.35;
|
const isMobilePortrait = document.body.classList.contains('mobile-portrait');
|
||||||
|
const overlapOffset = cardHeight * (isMobilePortrait ? 0.48 : 0.35);
|
||||||
const cardLeft = centerX - cardWidth / 2;
|
const cardLeft = centerX - cardWidth / 2;
|
||||||
const cardTop = deckRect.top - overlapOffset;
|
const cardTop = deckRect.top - overlapOffset;
|
||||||
|
|
||||||
@@ -3750,15 +3877,26 @@ class GolfGame {
|
|||||||
this.currentRoundSpan.textContent = this.gameState.current_round;
|
this.currentRoundSpan.textContent = this.gameState.current_round;
|
||||||
this.totalRoundsSpan.textContent = this.gameState.total_rounds;
|
this.totalRoundsSpan.textContent = this.gameState.total_rounds;
|
||||||
|
|
||||||
|
// Sync mobile bottom bar round info
|
||||||
|
const mobileRound = document.getElementById('mobile-current-round');
|
||||||
|
const mobileTotal = document.getElementById('mobile-total-rounds');
|
||||||
|
if (mobileRound) mobileRound.textContent = this.gameState.current_round;
|
||||||
|
if (mobileTotal) mobileTotal.textContent = this.gameState.total_rounds;
|
||||||
|
|
||||||
// Show/hide final turn badge with enhanced urgency
|
// Show/hide final turn badge with enhanced urgency
|
||||||
|
// Note: markKnocker() is deferred until after opponent areas are rebuilt below
|
||||||
const isFinalTurn = this.gameState.phase === 'final_turn';
|
const isFinalTurn = this.gameState.phase === 'final_turn';
|
||||||
if (isFinalTurn) {
|
if (isFinalTurn) {
|
||||||
this.updateFinalTurnDisplay();
|
this.gameScreen.classList.add('final-turn-active');
|
||||||
|
this.finalTurnBadge.classList.remove('hidden');
|
||||||
|
if (!this.finalTurnAnnounced) {
|
||||||
|
this.playSound('alert');
|
||||||
|
this.finalTurnAnnounced = true;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
this.finalTurnBadge.classList.add('hidden');
|
this.finalTurnBadge.classList.add('hidden');
|
||||||
this.gameScreen.classList.remove('final-turn-active');
|
this.gameScreen.classList.remove('final-turn-active');
|
||||||
this.finalTurnAnnounced = false;
|
this.finalTurnAnnounced = false;
|
||||||
this.clearKnockerMark();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Toggle not-my-turn class to disable hover effects when it's not player's turn
|
// Toggle not-my-turn class to disable hover effects when it's not player's turn
|
||||||
@@ -3780,7 +3918,7 @@ class GolfGame {
|
|||||||
: this.gameState.current_player_id;
|
: this.gameState.current_player_id;
|
||||||
const displayedPlayer = this.gameState.players.find(p => p.id === displayedPlayerId);
|
const displayedPlayer = this.gameState.players.find(p => p.id === displayedPlayerId);
|
||||||
if (displayedPlayer && displayedPlayerId !== this.playerId) {
|
if (displayedPlayer && displayedPlayerId !== this.playerId) {
|
||||||
this.setStatus(`${displayedPlayer.name}'s turn`);
|
this.setStatus(`${displayedPlayer.name}'s turn`, 'opponent-turn');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update player header (name + score like opponents)
|
// Update player header (name + score like opponents)
|
||||||
@@ -4067,7 +4205,13 @@ class GolfGame {
|
|||||||
cardEl.firstChild.addEventListener('click', () => this.handleCardClick(index));
|
cardEl.firstChild.addEventListener('click', () => this.handleCardClick(index));
|
||||||
// V3_13: Bind tooltip events for face-up cards
|
// V3_13: Bind tooltip events for face-up cards
|
||||||
this.bindCardTooltipEvents(cardEl.firstChild, displayCard);
|
this.bindCardTooltipEvents(cardEl.firstChild, displayCard);
|
||||||
this.playerCards.appendChild(cardEl.firstChild);
|
const appendedCard = cardEl.firstChild;
|
||||||
|
this.playerCards.appendChild(appendedCard);
|
||||||
|
|
||||||
|
// Hide card if flip animation overlay is active on this position
|
||||||
|
if (this.animatingPositions.has(`local-${index}`)) {
|
||||||
|
appendedCard.style.visibility = 'hidden';
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4124,6 +4268,13 @@ class GolfGame {
|
|||||||
// Update scoreboard panel
|
// Update scoreboard panel
|
||||||
this.updateScorePanel();
|
this.updateScorePanel();
|
||||||
|
|
||||||
|
// Mark knocker AFTER opponent areas are rebuilt (otherwise innerHTML='' wipes it)
|
||||||
|
if (this.gameState.phase === 'final_turn') {
|
||||||
|
this.markKnocker(this.gameState.finisher_id);
|
||||||
|
} else {
|
||||||
|
this.clearKnockerMark();
|
||||||
|
}
|
||||||
|
|
||||||
// Initialize anime.js hover listeners on newly created cards
|
// Initialize anime.js hover listeners on newly created cards
|
||||||
if (window.cardAnimations) {
|
if (window.cardAnimations) {
|
||||||
window.cardAnimations.initHoverListeners(this.playerCards);
|
window.cardAnimations.initHoverListeners(this.playerCards);
|
||||||
@@ -4617,6 +4768,19 @@ class AuthManager {
|
|||||||
this.signupError = document.getElementById('signup-error');
|
this.signupError = document.getElementById('signup-error');
|
||||||
this.showSignupLink = document.getElementById('show-signup');
|
this.showSignupLink = document.getElementById('show-signup');
|
||||||
this.showLoginLink = document.getElementById('show-login');
|
this.showLoginLink = document.getElementById('show-login');
|
||||||
|
this.showForgotLink = document.getElementById('show-forgot');
|
||||||
|
this.forgotFormContainer = document.getElementById('forgot-form-container');
|
||||||
|
this.forgotForm = document.getElementById('forgot-form');
|
||||||
|
this.forgotEmail = document.getElementById('forgot-email');
|
||||||
|
this.forgotError = document.getElementById('forgot-error');
|
||||||
|
this.forgotSuccess = document.getElementById('forgot-success');
|
||||||
|
this.forgotBackLogin = document.getElementById('forgot-back-login');
|
||||||
|
this.resetFormContainer = document.getElementById('reset-form-container');
|
||||||
|
this.resetForm = document.getElementById('reset-form');
|
||||||
|
this.resetPassword = document.getElementById('reset-password');
|
||||||
|
this.resetPasswordConfirm = document.getElementById('reset-password-confirm');
|
||||||
|
this.resetError = document.getElementById('reset-error');
|
||||||
|
this.resetSuccess = document.getElementById('reset-success');
|
||||||
}
|
}
|
||||||
|
|
||||||
bindEvents() {
|
bindEvents() {
|
||||||
@@ -4637,6 +4801,20 @@ class AuthManager {
|
|||||||
this.loginForm?.addEventListener('submit', (e) => this.handleLogin(e));
|
this.loginForm?.addEventListener('submit', (e) => this.handleLogin(e));
|
||||||
this.signupForm?.addEventListener('submit', (e) => this.handleSignup(e));
|
this.signupForm?.addEventListener('submit', (e) => this.handleSignup(e));
|
||||||
this.logoutBtn?.addEventListener('click', () => this.logout());
|
this.logoutBtn?.addEventListener('click', () => this.logout());
|
||||||
|
this.showForgotLink?.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.showForm('forgot');
|
||||||
|
});
|
||||||
|
this.forgotBackLogin?.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.showForm('login');
|
||||||
|
});
|
||||||
|
this.forgotForm?.addEventListener('submit', (e) => this.handleForgotPassword(e));
|
||||||
|
this.resetForm?.addEventListener('submit', (e) => this.handleResetPassword(e));
|
||||||
|
|
||||||
|
// Check URL for reset token or invite code on page load
|
||||||
|
this.checkResetToken();
|
||||||
|
this.checkInviteCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
showModal(form = 'login') {
|
showModal(form = 'login') {
|
||||||
@@ -4651,14 +4829,24 @@ class AuthManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
showForm(form) {
|
showForm(form) {
|
||||||
|
this.loginFormContainer.classList.add('hidden');
|
||||||
|
this.signupFormContainer.classList.add('hidden');
|
||||||
|
this.forgotFormContainer?.classList.add('hidden');
|
||||||
|
this.resetFormContainer?.classList.add('hidden');
|
||||||
|
this.clearErrors();
|
||||||
|
|
||||||
if (form === 'login') {
|
if (form === 'login') {
|
||||||
this.loginFormContainer.classList.remove('hidden');
|
this.loginFormContainer.classList.remove('hidden');
|
||||||
this.signupFormContainer.classList.add('hidden');
|
|
||||||
this.loginUsername.focus();
|
this.loginUsername.focus();
|
||||||
} else {
|
} else if (form === 'signup') {
|
||||||
this.loginFormContainer.classList.add('hidden');
|
|
||||||
this.signupFormContainer.classList.remove('hidden');
|
this.signupFormContainer.classList.remove('hidden');
|
||||||
this.signupUsername.focus();
|
this.signupUsername.focus();
|
||||||
|
} else if (form === 'forgot') {
|
||||||
|
this.forgotFormContainer?.classList.remove('hidden');
|
||||||
|
this.forgotEmail?.focus();
|
||||||
|
} else if (form === 'reset') {
|
||||||
|
this.resetFormContainer?.classList.remove('hidden');
|
||||||
|
this.resetPassword?.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4671,6 +4859,10 @@ class AuthManager {
|
|||||||
clearErrors() {
|
clearErrors() {
|
||||||
this.loginError.textContent = '';
|
this.loginError.textContent = '';
|
||||||
this.signupError.textContent = '';
|
this.signupError.textContent = '';
|
||||||
|
if (this.forgotError) this.forgotError.textContent = '';
|
||||||
|
if (this.forgotSuccess) this.forgotSuccess.textContent = '';
|
||||||
|
if (this.resetError) this.resetError.textContent = '';
|
||||||
|
if (this.resetSuccess) this.resetSuccess.textContent = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleLogin(e) {
|
async handleLogin(e) {
|
||||||
@@ -4761,4 +4953,89 @@ class AuthManager {
|
|||||||
this.lobbyGameControls?.classList.add('hidden');
|
this.lobbyGameControls?.classList.add('hidden');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
checkResetToken() {
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const token = params.get('token');
|
||||||
|
const path = window.location.pathname;
|
||||||
|
|
||||||
|
if (token && path.includes('reset-password')) {
|
||||||
|
this._resetToken = token;
|
||||||
|
this.showModal('reset');
|
||||||
|
// Clean URL
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkInviteCode() {
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const invite = params.get('invite');
|
||||||
|
|
||||||
|
if (invite) {
|
||||||
|
this.signupInviteCode.value = invite;
|
||||||
|
this.showModal('signup');
|
||||||
|
// Clean URL
|
||||||
|
window.history.replaceState({}, '', '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleForgotPassword(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.clearErrors();
|
||||||
|
|
||||||
|
const email = this.forgotEmail.value.trim();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/auth/forgot-password', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
this.forgotError.textContent = data.detail || 'Request failed';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.forgotSuccess.textContent = 'If an account exists with that email, a reset link has been sent.';
|
||||||
|
this.forgotForm.reset();
|
||||||
|
} catch (err) {
|
||||||
|
this.forgotError.textContent = 'Connection error';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleResetPassword(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.clearErrors();
|
||||||
|
|
||||||
|
const password = this.resetPassword.value;
|
||||||
|
const confirm = this.resetPasswordConfirm.value;
|
||||||
|
|
||||||
|
if (password !== confirm) {
|
||||||
|
this.resetError.textContent = 'Passwords do not match';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/auth/reset-password', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ token: this._resetToken, new_password: password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
this.resetError.textContent = data.detail || 'Reset failed';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.resetSuccess.textContent = 'Password reset! You can now log in.';
|
||||||
|
this.resetForm.reset();
|
||||||
|
setTimeout(() => this.showForm('login'), 2000);
|
||||||
|
} catch (err) {
|
||||||
|
this.resetError.textContent = 'Connection error';
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,7 +46,8 @@ class CardAnimations {
|
|||||||
const centerX = (deckRect.left + deckRect.right + discardRect.left + discardRect.right) / 4;
|
const centerX = (deckRect.left + deckRect.right + discardRect.left + discardRect.right) / 4;
|
||||||
const cardWidth = deckRect.width;
|
const cardWidth = deckRect.width;
|
||||||
const cardHeight = deckRect.height;
|
const cardHeight = deckRect.height;
|
||||||
const overlapOffset = cardHeight * 0.35;
|
const isMobilePortrait = document.body.classList.contains('mobile-portrait');
|
||||||
|
const overlapOffset = cardHeight * (isMobilePortrait ? 0.48 : 0.35);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
left: centerX - cardWidth / 2,
|
left: centerX - cardWidth / 2,
|
||||||
@@ -155,12 +156,20 @@ class CardAnimations {
|
|||||||
}
|
}
|
||||||
this.activeAnimations.clear();
|
this.activeAnimations.clear();
|
||||||
|
|
||||||
// Remove all animation card elements (including those marked as animating)
|
// Remove all animation overlay elements
|
||||||
document.querySelectorAll('.draw-anim-card').forEach(el => {
|
document.querySelectorAll('.draw-anim-card, .traveling-card, .deal-anim-container').forEach(el => {
|
||||||
delete el.dataset.animating;
|
delete el.dataset.animating;
|
||||||
el.remove();
|
el.remove();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore visibility on any cards hidden during animations
|
||||||
|
document.querySelectorAll('.card[style*="opacity: 0"], .card[style*="opacity:0"]').forEach(el => {
|
||||||
|
el.style.opacity = '';
|
||||||
|
});
|
||||||
|
document.querySelectorAll('.card[style*="visibility: hidden"], .card[style*="visibility:hidden"]').forEach(el => {
|
||||||
|
el.style.visibility = '';
|
||||||
|
});
|
||||||
|
|
||||||
// Restore discard pile visibility if it was hidden during animation
|
// Restore discard pile visibility if it was hidden during animation
|
||||||
const discardPile = document.getElementById('discard');
|
const discardPile = document.getElementById('discard');
|
||||||
if (discardPile && discardPile.style.opacity === '0') {
|
if (discardPile && discardPile.style.opacity === '0') {
|
||||||
@@ -211,6 +220,7 @@ class CardAnimations {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_animateDrawDeckCard(cardData, deckRect, holdingRect, onComplete) {
|
_animateDrawDeckCard(cardData, deckRect, holdingRect, onComplete) {
|
||||||
|
console.log('[DEBUG] _animateDrawDeckCard called with cardData:', cardData ? `${cardData.rank} of ${cardData.suit}` : 'NULL');
|
||||||
const deckColor = this.getDeckColor();
|
const deckColor = this.getDeckColor();
|
||||||
const animCard = this.createAnimCard(deckRect, true, deckColor);
|
const animCard = this.createAnimCard(deckRect, true, deckColor);
|
||||||
animCard.dataset.animating = 'true'; // Mark as actively animating
|
animCard.dataset.animating = 'true'; // Mark as actively animating
|
||||||
@@ -219,6 +229,9 @@ class CardAnimations {
|
|||||||
|
|
||||||
if (cardData) {
|
if (cardData) {
|
||||||
this.setCardContent(animCard, cardData);
|
this.setCardContent(animCard, cardData);
|
||||||
|
// Debug: verify what was actually set on the front face
|
||||||
|
const front = animCard.querySelector('.draw-anim-front');
|
||||||
|
console.log('[DEBUG] Draw anim card front content:', front?.innerHTML);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.playSound('draw-deck');
|
this.playSound('draw-deck');
|
||||||
@@ -407,6 +420,7 @@ class CardAnimations {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Animate initial flip at game start - smooth flip only, no lift
|
// Animate initial flip at game start - smooth flip only, no lift
|
||||||
|
// Uses overlay sized to match the source card exactly
|
||||||
animateInitialFlip(cardElement, cardData, onComplete) {
|
animateInitialFlip(cardElement, cardData, onComplete) {
|
||||||
if (!cardElement) {
|
if (!cardElement) {
|
||||||
if (onComplete) onComplete();
|
if (onComplete) onComplete();
|
||||||
@@ -420,8 +434,16 @@ class CardAnimations {
|
|||||||
const animCard = this.createAnimCard(rect, true, deckColor);
|
const animCard = this.createAnimCard(rect, true, deckColor);
|
||||||
this.setCardContent(animCard, cardData);
|
this.setCardContent(animCard, cardData);
|
||||||
|
|
||||||
// Hide original card during animation
|
// Match the front face styling to player hand cards (not deck/discard cards)
|
||||||
cardElement.style.opacity = '0';
|
const front = animCard.querySelector('.draw-anim-front');
|
||||||
|
if (front) {
|
||||||
|
front.style.background = 'linear-gradient(145deg, #fff 0%, #f5f5f5 100%)';
|
||||||
|
front.style.border = '2px solid #ddd';
|
||||||
|
front.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.3)';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide original card during animation (overlay covers it)
|
||||||
|
cardElement.style.visibility = 'hidden';
|
||||||
|
|
||||||
const inner = animCard.querySelector('.draw-anim-inner');
|
const inner = animCard.querySelector('.draw-anim-inner');
|
||||||
const duration = window.TIMING?.card?.flip || 320;
|
const duration = window.TIMING?.card?.flip || 320;
|
||||||
@@ -436,7 +458,7 @@ class CardAnimations {
|
|||||||
begin: () => this.playSound('flip'),
|
begin: () => this.playSound('flip'),
|
||||||
complete: () => {
|
complete: () => {
|
||||||
animCard.remove();
|
animCard.remove();
|
||||||
cardElement.style.opacity = '1';
|
cardElement.style.visibility = '';
|
||||||
if (onComplete) onComplete();
|
if (onComplete) onComplete();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -445,7 +467,7 @@ class CardAnimations {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Initial flip animation error:', e);
|
console.error('Initial flip animation error:', e);
|
||||||
animCard.remove();
|
animCard.remove();
|
||||||
cardElement.style.opacity = '1';
|
cardElement.style.visibility = '';
|
||||||
if (onComplete) onComplete();
|
if (onComplete) onComplete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -750,28 +772,36 @@ class CardAnimations {
|
|||||||
const id = 'turnPulse';
|
const id = 'turnPulse';
|
||||||
this.stopTurnPulse(element);
|
this.stopTurnPulse(element);
|
||||||
|
|
||||||
// Quick shake animation
|
// Quick shake animation - target cards only, not labels
|
||||||
|
const T = window.TIMING?.turnPulse || {};
|
||||||
|
const cards = element.querySelectorAll(':scope > .pile-wrapper > .card, :scope > .pile-wrapper > .discard-stack > #discard');
|
||||||
const doShake = () => {
|
const doShake = () => {
|
||||||
if (!this.activeAnimations.has(id)) return;
|
if (!this.activeAnimations.has(id)) return;
|
||||||
|
|
||||||
anime({
|
anime({
|
||||||
targets: element,
|
targets: cards.length ? cards : element,
|
||||||
translateX: [0, -8, 8, -6, 4, 0],
|
translateX: [0, -6, 6, -4, 3, 0],
|
||||||
duration: 400,
|
duration: T.duration || 300,
|
||||||
easing: 'easeInOutQuad'
|
easing: 'easeInOutQuad'
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Do initial shake, then repeat every 3 seconds
|
// Delay first shake, then repeat at interval
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
if (!this.activeAnimations.has(id)) return;
|
||||||
doShake();
|
doShake();
|
||||||
const interval = setInterval(doShake, 3000);
|
const interval = setInterval(doShake, T.interval || 3000);
|
||||||
this.activeAnimations.set(id, { interval });
|
const entry = this.activeAnimations.get(id);
|
||||||
|
if (entry) entry.interval = interval;
|
||||||
|
}, T.initialDelay || 5000);
|
||||||
|
this.activeAnimations.set(id, { timeout });
|
||||||
}
|
}
|
||||||
|
|
||||||
stopTurnPulse(element) {
|
stopTurnPulse(element) {
|
||||||
const id = 'turnPulse';
|
const id = 'turnPulse';
|
||||||
const existing = this.activeAnimations.get(id);
|
const existing = this.activeAnimations.get(id);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
|
if (existing.timeout) clearTimeout(existing.timeout);
|
||||||
if (existing.interval) clearInterval(existing.interval);
|
if (existing.interval) clearInterval(existing.interval);
|
||||||
if (existing.pause) existing.pause();
|
if (existing.pause) existing.pause();
|
||||||
this.activeAnimations.delete(id);
|
this.activeAnimations.delete(id);
|
||||||
@@ -1097,7 +1127,7 @@ class CardAnimations {
|
|||||||
});
|
});
|
||||||
// Now run the swap animation
|
// Now run the swap animation
|
||||||
this._runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete);
|
this._runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete);
|
||||||
}, 100);
|
}, 350);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1515,6 +1545,7 @@ class CardAnimations {
|
|||||||
|
|
||||||
// Create container for animation cards
|
// Create container for animation cards
|
||||||
const container = document.createElement('div');
|
const container = document.createElement('div');
|
||||||
|
container.className = 'deal-anim-container';
|
||||||
container.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;pointer-events:none;z-index:1000;';
|
container.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;pointer-events:none;z-index:1000;';
|
||||||
document.body.appendChild(container);
|
document.body.appendChild(container);
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,8 @@
|
|||||||
<h1><img src="golfball-logo.svg" alt="" class="golfball-logo"><span class="golfer-swing">🏌️</span><span class="kicked-ball">⚪</span> <span class="golf-title">Golf</span></h1>
|
<h1><img src="golfball-logo.svg" alt="" class="golfball-logo"><span class="golfer-swing">🏌️</span><span class="kicked-ball">⚪</span> <span class="golf-title">Golf</span></h1>
|
||||||
<p class="subtitle">6-Card Golf Card Game <button id="rules-btn" class="btn btn-small btn-rules">Rules</button> <button id="leaderboard-btn" class="btn btn-small leaderboard-btn">Leaderboard</button></p>
|
<p class="subtitle">6-Card Golf Card Game <button id="rules-btn" class="btn btn-small btn-rules">Rules</button> <button id="leaderboard-btn" class="btn btn-small leaderboard-btn">Leaderboard</button></p>
|
||||||
|
|
||||||
|
<div class="alpha-banner">Beta Testing - Bear with us while, stuff.</div>
|
||||||
|
|
||||||
<!-- Auth prompt for unauthenticated users -->
|
<!-- Auth prompt for unauthenticated users -->
|
||||||
<div id="auth-prompt" class="auth-prompt">
|
<div id="auth-prompt" class="auth-prompt">
|
||||||
<p>Log in or sign up to play.</p>
|
<p>Log in or sign up to play.</p>
|
||||||
@@ -51,6 +53,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p id="lobby-error" class="error"></p>
|
<p id="lobby-error" class="error"></p>
|
||||||
|
|
||||||
|
<footer class="app-footer">v3.1.5 © Aaron D. Lee</footer>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Matchmaking Screen -->
|
<!-- Matchmaking Screen -->
|
||||||
@@ -78,16 +82,16 @@
|
|||||||
<div class="waiting-layout">
|
<div class="waiting-layout">
|
||||||
<div class="waiting-left-col">
|
<div class="waiting-left-col">
|
||||||
<div class="players-list">
|
<div class="players-list">
|
||||||
|
<div class="players-list-header">
|
||||||
<h3>Players</h3>
|
<h3>Players</h3>
|
||||||
|
<div id="cpu-controls-section" class="cpu-controls hidden">
|
||||||
|
<span class="cpu-controls-label">CPU:</span>
|
||||||
|
<button id="remove-cpu-btn" class="cpu-ctrl-btn btn-danger" title="Remove CPU">−</button>
|
||||||
|
<button id="add-cpu-btn" class="cpu-ctrl-btn btn-success" title="Add CPU">+</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<ul id="players-list"></ul>
|
<ul id="players-list"></ul>
|
||||||
</div>
|
</div>
|
||||||
<div id="cpu-controls-section" class="cpu-controls-section hidden">
|
|
||||||
<h4>Add CPU Opponents</h4>
|
|
||||||
<div class="cpu-controls">
|
|
||||||
<button id="remove-cpu-btn" class="btn btn-small btn-danger" title="Remove last CPU">−</button>
|
|
||||||
<button id="add-cpu-btn" class="btn btn-small btn-success" title="Add CPU player">+</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button id="leave-room-btn" class="btn btn-danger">Leave Room</button>
|
<button id="leave-room-btn" class="btn btn-danger">Leave Room</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -282,6 +286,8 @@
|
|||||||
|
|
||||||
<p id="waiting-message" class="info">Waiting for host to start the game...</p>
|
<p id="waiting-message" class="info">Waiting for host to start the game...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<footer class="app-footer">v3.1.5 © Aaron D. Lee</footer>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Game Screen -->
|
<!-- Game Screen -->
|
||||||
@@ -303,7 +309,6 @@
|
|||||||
<div id="final-turn-badge" class="final-turn-badge hidden">
|
<div id="final-turn-badge" class="final-turn-badge hidden">
|
||||||
<span class="final-turn-icon">⚡</span>
|
<span class="final-turn-icon">⚡</span>
|
||||||
<span class="final-turn-text">FINAL TURN</span>
|
<span class="final-turn-text">FINAL TURN</span>
|
||||||
<span class="final-turn-remaining"></span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-col header-col-right">
|
<div class="header-col header-col-right">
|
||||||
@@ -327,7 +332,12 @@
|
|||||||
</div>
|
</div>
|
||||||
<span class="held-label">Holding</span>
|
<span class="held-label">Holding</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="pile-wrapper">
|
||||||
|
<span class="pile-label">DRAW</span>
|
||||||
<div id="deck" class="card card-back"></div>
|
<div id="deck" class="card card-back"></div>
|
||||||
|
</div>
|
||||||
|
<div class="pile-wrapper">
|
||||||
|
<span class="pile-label">DISCARD</span>
|
||||||
<div class="discard-stack">
|
<div class="discard-stack">
|
||||||
<div id="discard" class="card">
|
<div id="discard" class="card">
|
||||||
<span id="discard-content"></span>
|
<span id="discard-content"></span>
|
||||||
@@ -342,6 +352,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="player-section">
|
<div class="player-section">
|
||||||
<div class="player-area">
|
<div class="player-area">
|
||||||
@@ -397,12 +408,21 @@
|
|||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Mobile bottom bar (hidden on desktop) -->
|
<!-- Mobile bottom bar (hidden on desktop) -->
|
||||||
<div id="mobile-bottom-bar">
|
<div id="mobile-bottom-bar">
|
||||||
<button class="mobile-bar-btn" data-drawer="standings-panel">Standings</button>
|
<div class="mobile-round-info">Hole <span id="mobile-current-round">1</span>/<span id="mobile-total-rounds">9</span></div>
|
||||||
<button class="mobile-bar-btn" data-drawer="scoreboard">Scores</button>
|
<button class="mobile-bar-btn mobile-rules-btn" id="mobile-rules-btn" data-drawer="rules-drawer"><span id="mobile-rules-icon">RULES</span></button>
|
||||||
|
<button class="mobile-bar-btn" data-drawer="standings-panel">Scorecard</button>
|
||||||
|
<button id="mobile-leave-btn" class="mobile-bar-btn mobile-leave-btn">End Game</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Mobile rules drawer -->
|
||||||
|
<div id="rules-drawer" class="side-panel rules-drawer-panel">
|
||||||
|
<h4>Active Rules</h4>
|
||||||
|
<div id="mobile-rules-content"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Drawer backdrop for mobile -->
|
<!-- Drawer backdrop for mobile -->
|
||||||
@@ -412,9 +432,8 @@
|
|||||||
<!-- Rules Screen -->
|
<!-- Rules Screen -->
|
||||||
<div id="rules-screen" class="screen">
|
<div id="rules-screen" class="screen">
|
||||||
<div class="rules-container">
|
<div class="rules-container">
|
||||||
<button id="rules-back-btn" class="btn rules-back-btn">« Back</button>
|
|
||||||
|
|
||||||
<div class="rules-header">
|
<div class="rules-header">
|
||||||
|
<button id="rules-back-btn" class="btn rules-back-btn">« Back</button>
|
||||||
<h1><span class="golfer-logo">🏌️</span> <span class="golf-title">Golf Rules</span></h1>
|
<h1><span class="golfer-logo">🏌️</span> <span class="golf-title">Golf Rules</span></h1>
|
||||||
<p class="rules-subtitle">6-Card Golf Card Game - Complete Guide</p>
|
<p class="rules-subtitle">6-Card Golf Card Game - Complete Guide</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -730,9 +749,8 @@ TOTAL: 0 + 8 + 16 = 24 points</pre>
|
|||||||
<!-- Leaderboard Screen -->
|
<!-- Leaderboard Screen -->
|
||||||
<div id="leaderboard-screen" class="screen">
|
<div id="leaderboard-screen" class="screen">
|
||||||
<div class="leaderboard-container">
|
<div class="leaderboard-container">
|
||||||
<button id="leaderboard-back-btn" class="btn leaderboard-back-btn">« Back</button>
|
|
||||||
|
|
||||||
<div class="leaderboard-header">
|
<div class="leaderboard-header">
|
||||||
|
<button id="leaderboard-back-btn" class="btn leaderboard-back-btn">« Back</button>
|
||||||
<h1>Leaderboard</h1>
|
<h1>Leaderboard</h1>
|
||||||
<p class="leaderboard-subtitle">Top players ranked by performance</p>
|
<p class="leaderboard-subtitle">Top players ranked by performance</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -837,6 +855,38 @@ TOTAL: 0 + 8 + 16 = 24 points</pre>
|
|||||||
<button type="submit" class="btn btn-primary btn-full">Login</button>
|
<button type="submit" class="btn btn-primary btn-full">Login</button>
|
||||||
</form>
|
</form>
|
||||||
<p class="auth-switch">Don't have an account? <a href="#" id="show-signup">Sign up</a></p>
|
<p class="auth-switch">Don't have an account? <a href="#" id="show-signup">Sign up</a></p>
|
||||||
|
<p class="auth-switch"><a href="#" id="show-forgot">Forgot password?</a></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Forgot Password Form -->
|
||||||
|
<div id="forgot-form-container" class="hidden">
|
||||||
|
<h3>Reset Password</h3>
|
||||||
|
<p class="auth-hint">Enter your email and we'll send you a reset link.</p>
|
||||||
|
<form id="forgot-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<input type="email" id="forgot-email" placeholder="Email" required>
|
||||||
|
</div>
|
||||||
|
<p id="forgot-error" class="error"></p>
|
||||||
|
<p id="forgot-success" class="success"></p>
|
||||||
|
<button type="submit" class="btn btn-primary btn-full">Send Reset Link</button>
|
||||||
|
</form>
|
||||||
|
<p class="auth-switch"><a href="#" id="forgot-back-login">Back to login</a></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Reset Password Form (from email link) -->
|
||||||
|
<div id="reset-form-container" class="hidden">
|
||||||
|
<h3>Set New Password</h3>
|
||||||
|
<form id="reset-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<input type="password" id="reset-password" placeholder="New password" required minlength="8">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<input type="password" id="reset-password-confirm" placeholder="Confirm password" required minlength="8">
|
||||||
|
</div>
|
||||||
|
<p id="reset-error" class="error"></p>
|
||||||
|
<p id="reset-success" class="success"></p>
|
||||||
|
<button type="submit" class="btn btn-primary btn-full">Reset Password</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Signup Form -->
|
<!-- Signup Form -->
|
||||||
|
|||||||
675
client/style.css
675
client/style.css
File diff suppressed because it is too large
Load Diff
@@ -77,6 +77,7 @@ const TIMING = {
|
|||||||
|
|
||||||
// V3_03: Round end reveal timing
|
// V3_03: Round end reveal timing
|
||||||
reveal: {
|
reveal: {
|
||||||
|
lastPlayPause: 2000, // Pause after last play animation before reveals
|
||||||
voluntaryWindow: 2000, // Time for players to flip their own cards
|
voluntaryWindow: 2000, // Time for players to flip their own cards
|
||||||
initialPause: 250, // Pause before auto-reveals start
|
initialPause: 250, // Pause before auto-reveals start
|
||||||
cardStagger: 50, // Between cards in same hand
|
cardStagger: 50, // Between cards in same hand
|
||||||
@@ -128,6 +129,13 @@ const TIMING = {
|
|||||||
pulseDelay: 200, // Delay before card appears (pulse visible first)
|
pulseDelay: 200, // Delay before card appears (pulse visible first)
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Turn pulse (deck shake)
|
||||||
|
turnPulse: {
|
||||||
|
initialDelay: 5000, // Delay before first shake
|
||||||
|
interval: 5400, // Time between shakes
|
||||||
|
duration: 300, // Shake animation duration
|
||||||
|
},
|
||||||
|
|
||||||
// V3_17: Knock notification
|
// V3_17: Knock notification
|
||||||
knock: {
|
knock: {
|
||||||
statusDuration: 2500, // How long the knock status message persists
|
statusDuration: 2500, // How long the knock status message persists
|
||||||
|
|||||||
@@ -26,9 +26,16 @@ services:
|
|||||||
- REDIS_URL=redis://redis:6379
|
- REDIS_URL=redis://redis:6379
|
||||||
- SECRET_KEY=${SECRET_KEY}
|
- SECRET_KEY=${SECRET_KEY}
|
||||||
- RESEND_API_KEY=${RESEND_API_KEY:-}
|
- RESEND_API_KEY=${RESEND_API_KEY:-}
|
||||||
|
- EMAIL_FROM=${EMAIL_FROM:-Golf Cards <noreply@contact.golfcards.club>}
|
||||||
- SENTRY_DSN=${SENTRY_DSN:-}
|
- SENTRY_DSN=${SENTRY_DSN:-}
|
||||||
- ENVIRONMENT=production
|
- ENVIRONMENT=${ENVIRONMENT:-production}
|
||||||
- LOG_LEVEL=INFO
|
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||||
|
- LOG_LEVEL_GAME=${LOG_LEVEL_GAME:-}
|
||||||
|
- LOG_LEVEL_AI=${LOG_LEVEL_AI:-}
|
||||||
|
- LOG_LEVEL_HANDLERS=${LOG_LEVEL_HANDLERS:-}
|
||||||
|
- LOG_LEVEL_ROOM=${LOG_LEVEL_ROOM:-}
|
||||||
|
- LOG_LEVEL_AUTH=${LOG_LEVEL_AUTH:-}
|
||||||
|
- LOG_LEVEL_STORES=${LOG_LEVEL_STORES:-}
|
||||||
- BASE_URL=${BASE_URL:-https://golf.example.com}
|
- BASE_URL=${BASE_URL:-https://golf.example.com}
|
||||||
- RATE_LIMIT_ENABLED=true
|
- RATE_LIMIT_ENABLED=true
|
||||||
- INVITE_ONLY=true
|
- INVITE_ONLY=true
|
||||||
@@ -60,6 +67,15 @@ services:
|
|||||||
- "traefik.http.routers.golf.entrypoints=websecure"
|
- "traefik.http.routers.golf.entrypoints=websecure"
|
||||||
- "traefik.http.routers.golf.tls=true"
|
- "traefik.http.routers.golf.tls=true"
|
||||||
- "traefik.http.routers.golf.tls.certresolver=letsencrypt"
|
- "traefik.http.routers.golf.tls.certresolver=letsencrypt"
|
||||||
|
# www -> bare domain redirect
|
||||||
|
- "traefik.http.routers.golf-www.rule=Host(`www.${DOMAIN:-golf.example.com}`)"
|
||||||
|
- "traefik.http.routers.golf-www.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.golf-www.tls=true"
|
||||||
|
- "traefik.http.routers.golf-www.tls.certresolver=letsencrypt"
|
||||||
|
- "traefik.http.routers.golf-www.middlewares=www-redirect"
|
||||||
|
- "traefik.http.middlewares.www-redirect.redirectregex.regex=^https://www\\.(.+)"
|
||||||
|
- "traefik.http.middlewares.www-redirect.redirectregex.replacement=https://$${1}"
|
||||||
|
- "traefik.http.middlewares.www-redirect.redirectregex.permanent=true"
|
||||||
- "traefik.http.services.golf.loadbalancer.server.port=8000"
|
- "traefik.http.services.golf.loadbalancer.server.port=8000"
|
||||||
# WebSocket sticky sessions
|
# WebSocket sticky sessions
|
||||||
- "traefik.http.services.golf.loadbalancer.sticky.cookie=true"
|
- "traefik.http.services.golf.loadbalancer.sticky.cookie=true"
|
||||||
|
|||||||
146
docker-compose.staging.yml
Normal file
146
docker-compose.staging.yml
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
# Staging Docker Compose for Golf Card Game
|
||||||
|
#
|
||||||
|
# Mirrors production but with reduced memory limits for 512MB droplet.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# docker compose -f docker-compose.staging.yml up -d --build
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
environment:
|
||||||
|
- POSTGRES_URL=postgresql://golf:${DB_PASSWORD}@postgres:5432/golf
|
||||||
|
- DATABASE_URL=postgresql://golf:${DB_PASSWORD}@postgres:5432/golf
|
||||||
|
- REDIS_URL=redis://redis:6379
|
||||||
|
- SECRET_KEY=${SECRET_KEY}
|
||||||
|
- RESEND_API_KEY=${RESEND_API_KEY:-}
|
||||||
|
- EMAIL_FROM=${EMAIL_FROM:-Golf Cards <noreply@contact.golfcards.club>}
|
||||||
|
- SENTRY_DSN=${SENTRY_DSN:-}
|
||||||
|
- ENVIRONMENT=${ENVIRONMENT:-staging}
|
||||||
|
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||||
|
- LOG_LEVEL_GAME=${LOG_LEVEL_GAME:-}
|
||||||
|
- LOG_LEVEL_AI=${LOG_LEVEL_AI:-}
|
||||||
|
- LOG_LEVEL_HANDLERS=${LOG_LEVEL_HANDLERS:-}
|
||||||
|
- LOG_LEVEL_ROOM=${LOG_LEVEL_ROOM:-}
|
||||||
|
- LOG_LEVEL_AUTH=${LOG_LEVEL_AUTH:-}
|
||||||
|
- LOG_LEVEL_STORES=${LOG_LEVEL_STORES:-}
|
||||||
|
- BASE_URL=${BASE_URL:-https://staging.golfcards.club}
|
||||||
|
- RATE_LIMIT_ENABLED=false
|
||||||
|
- INVITE_ONLY=true
|
||||||
|
- BOOTSTRAP_ADMIN_USERNAME=${BOOTSTRAP_ADMIN_USERNAME:-}
|
||||||
|
- BOOTSTRAP_ADMIN_PASSWORD=${BOOTSTRAP_ADMIN_PASSWORD:-}
|
||||||
|
- MATCHMAKING_ENABLED=true
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
deploy:
|
||||||
|
replicas: 1
|
||||||
|
restart_policy:
|
||||||
|
condition: on-failure
|
||||||
|
max_attempts: 3
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 128M
|
||||||
|
reservations:
|
||||||
|
memory: 48M
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
- web
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
- "traefik.docker.network=golfgame_web"
|
||||||
|
- "traefik.http.routers.golf.rule=Host(`${DOMAIN:-staging.golfcards.club}`)"
|
||||||
|
- "traefik.http.routers.golf.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.golf.tls=true"
|
||||||
|
- "traefik.http.routers.golf.tls.certresolver=letsencrypt"
|
||||||
|
- "traefik.http.services.golf.loadbalancer.server.port=8000"
|
||||||
|
- "traefik.http.services.golf.loadbalancer.sticky.cookie=true"
|
||||||
|
- "traefik.http.services.golf.loadbalancer.sticky.cookie.name=golf_server"
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: golf
|
||||||
|
POSTGRES_USER: golf
|
||||||
|
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U golf -d golf"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 96M
|
||||||
|
reservations:
|
||||||
|
memory: 48M
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
command: redis-server --appendonly yes --maxmemory 16mb --maxmemory-policy allkeys-lru
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 32M
|
||||||
|
reservations:
|
||||||
|
memory: 16M
|
||||||
|
|
||||||
|
traefik:
|
||||||
|
image: traefik:v3.6
|
||||||
|
environment:
|
||||||
|
- DOCKER_API_VERSION=1.44
|
||||||
|
command:
|
||||||
|
- "--api.dashboard=true"
|
||||||
|
- "--api.insecure=true"
|
||||||
|
- "--accesslog=true"
|
||||||
|
- "--log.level=WARN"
|
||||||
|
- "--providers.docker=true"
|
||||||
|
- "--providers.docker.exposedbydefault=false"
|
||||||
|
- "--entrypoints.web.address=:80"
|
||||||
|
- "--entrypoints.web.http.redirections.entryPoint.to=websecure"
|
||||||
|
- "--entrypoints.web.http.redirections.entryPoint.scheme=https"
|
||||||
|
- "--entrypoints.websecure.address=:443"
|
||||||
|
- "--certificatesresolvers.letsencrypt.acme.httpchallenge=true"
|
||||||
|
- "--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web"
|
||||||
|
- "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
|
||||||
|
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
- letsencrypt:/letsencrypt
|
||||||
|
networks:
|
||||||
|
- web
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 48M
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
|
letsencrypt:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
internal:
|
||||||
|
driver: bridge
|
||||||
|
web:
|
||||||
|
driver: bridge
|
||||||
57
docs/v3/V3_18_POSTGRES_STORAGE_EFFICIENCY.md
Normal file
57
docs/v3/V3_18_POSTGRES_STORAGE_EFFICIENCY.md
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
# V3.18: PostgreSQL Game Data Storage Efficiency
|
||||||
|
|
||||||
|
**Status:** Planning
|
||||||
|
**Priority:** Medium
|
||||||
|
**Category:** Infrastructure / Performance
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
Per-move game logging stores full `hand_state` and `visible_opponents` JSONB on every move. For a typical 6-player, 9-hole game this generates significant redundant data since most of each player's hand doesn't change between moves.
|
||||||
|
|
||||||
|
## Areas to Investigate
|
||||||
|
|
||||||
|
### 1. Delta Encoding for Move Data
|
||||||
|
|
||||||
|
Store only what changed from the previous move instead of full state snapshots.
|
||||||
|
|
||||||
|
- First move of each round stores full state (baseline)
|
||||||
|
- Subsequent moves store only changed positions (e.g., `{"player_0": {"pos_2": "5H"}}`)
|
||||||
|
- Replay reconstruction applies deltas sequentially
|
||||||
|
- Trade-off: simpler queries vs. storage savings
|
||||||
|
|
||||||
|
### 2. PostgreSQL TOAST and Compression
|
||||||
|
|
||||||
|
- TOAST already compresses large JSONB values automatically
|
||||||
|
- Measure actual on-disk size vs. logical size for typical game data
|
||||||
|
- Consider whether explicit compression (e.g., storing gzipped blobs) adds meaningful savings over TOAST
|
||||||
|
|
||||||
|
### 3. Retention Policy
|
||||||
|
|
||||||
|
- Archive completed games older than N days to a separate table or cold storage
|
||||||
|
- Configurable retention period via env var (e.g., `GAME_LOG_RETENTION_DAYS`)
|
||||||
|
- Keep aggregate stats even after pruning raw move data
|
||||||
|
|
||||||
|
### 4. Move Logging Toggle
|
||||||
|
|
||||||
|
- Env var `GAME_LOGGING_ENABLED=true|false` to disable move-level logging entirely
|
||||||
|
- Useful for non-analysis environments (dev, load testing)
|
||||||
|
- Game outcomes and stats would still be recorded
|
||||||
|
|
||||||
|
### 5. Batch Inserts
|
||||||
|
|
||||||
|
- Buffer moves in memory and flush periodically instead of per-move INSERT
|
||||||
|
- Reduces database round-trips during active games
|
||||||
|
- Risk: data loss if server crashes mid-game (acceptable for non-critical move logs)
|
||||||
|
|
||||||
|
## Measurements Needed
|
||||||
|
|
||||||
|
Before optimizing, measure current impact:
|
||||||
|
|
||||||
|
- Average JSONB size per move (bytes)
|
||||||
|
- Average moves per game
|
||||||
|
- Total storage per game (moves + overhead)
|
||||||
|
- Query patterns: how often is per-move data actually read?
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- None (independent infrastructure improvement)
|
||||||
23
scripts/deploy-staging.sh
Executable file
23
scripts/deploy-staging.sh
Executable file
@@ -0,0 +1,23 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
DROPLET="root@129.212.150.189"
|
||||||
|
REMOTE_DIR="/opt/golfgame"
|
||||||
|
|
||||||
|
echo "Syncing to staging ($DROPLET)..."
|
||||||
|
rsync -az --delete \
|
||||||
|
--exclude='.git' \
|
||||||
|
--exclude='__pycache__' \
|
||||||
|
--exclude='node_modules' \
|
||||||
|
--exclude='.env' \
|
||||||
|
--exclude='internal/' \
|
||||||
|
server/ "$DROPLET:$REMOTE_DIR/server/"
|
||||||
|
rsync -az --delete \
|
||||||
|
--exclude='.git' \
|
||||||
|
--exclude='__pycache__' \
|
||||||
|
--exclude='node_modules' \
|
||||||
|
client/ "$DROPLET:$REMOTE_DIR/client/"
|
||||||
|
|
||||||
|
echo "Rebuilding app container..."
|
||||||
|
ssh $DROPLET "cd $REMOTE_DIR && docker compose -f docker-compose.staging.yml up -d --build app"
|
||||||
|
echo "Staging deploy complete."
|
||||||
9
scripts/deploy.sh
Executable file
9
scripts/deploy.sh
Executable file
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
DROPLET="root@165.245.152.51"
|
||||||
|
REMOTE_DIR="/opt/golfgame"
|
||||||
|
|
||||||
|
echo "Deploying to $DROPLET..."
|
||||||
|
ssh $DROPLET "cd $REMOTE_DIR && git pull origin main && docker compose -f docker-compose.prod.yml up -d --build app"
|
||||||
|
echo "Deploy complete."
|
||||||
@@ -7,6 +7,24 @@ PORT=8000
|
|||||||
DEBUG=true
|
DEBUG=true
|
||||||
LOG_LEVEL=DEBUG
|
LOG_LEVEL=DEBUG
|
||||||
|
|
||||||
|
# Per-module log level overrides (optional)
|
||||||
|
# These override LOG_LEVEL for specific modules.
|
||||||
|
# LOG_LEVEL_GAME=DEBUG # Core game logic
|
||||||
|
# LOG_LEVEL_AI=DEBUG # AI decisions (very verbose at DEBUG)
|
||||||
|
# LOG_LEVEL_HANDLERS=DEBUG # WebSocket message handlers
|
||||||
|
# LOG_LEVEL_ROOM=DEBUG # Room/lobby management
|
||||||
|
# LOG_LEVEL_AUTH=DEBUG # Auth stack (auth, routers.auth, services.auth_service)
|
||||||
|
# LOG_LEVEL_STORES=DEBUG # Database/Redis operations
|
||||||
|
|
||||||
|
# --- Preset examples ---
|
||||||
|
# Staging (debug game logic, quiet everything else):
|
||||||
|
# LOG_LEVEL=INFO
|
||||||
|
# LOG_LEVEL_GAME=DEBUG
|
||||||
|
# LOG_LEVEL_AI=DEBUG
|
||||||
|
#
|
||||||
|
# Production (minimal logging):
|
||||||
|
# LOG_LEVEL=WARNING
|
||||||
|
|
||||||
# Environment (development, staging, production)
|
# Environment (development, staging, production)
|
||||||
# Affects logging format, security headers (HSTS), etc.
|
# Affects logging format, security headers (HSTS), etc.
|
||||||
ENVIRONMENT=development
|
ENVIRONMENT=development
|
||||||
|
|||||||
63
server/ai.py
63
server/ai.py
@@ -43,8 +43,9 @@ CPU_TIMING = {
|
|||||||
# Delay before CPU "looks at" the discard pile
|
# Delay before CPU "looks at" the discard pile
|
||||||
"initial_look": (0.3, 0.5),
|
"initial_look": (0.3, 0.5),
|
||||||
# Brief pause after draw broadcast - let draw animation complete
|
# Brief pause after draw broadcast - let draw animation complete
|
||||||
# Must be >= client draw animation duration (~1s for deck, ~0.4s for discard)
|
# Must be >= client draw animation duration (~1.09s for deck, ~0.4s for discard)
|
||||||
"post_draw_settle": 1.1,
|
# Extra margin prevents swap message from arriving before draw flip completes
|
||||||
|
"post_draw_settle": 1.3,
|
||||||
# Consideration time after drawing (before swap/discard decision)
|
# Consideration time after drawing (before swap/discard decision)
|
||||||
"post_draw_consider": (0.2, 0.4),
|
"post_draw_consider": (0.2, 0.4),
|
||||||
# Variance multiplier range for chaotic personality players
|
# Variance multiplier range for chaotic personality players
|
||||||
@@ -1301,12 +1302,28 @@ class GolfAI:
|
|||||||
|
|
||||||
max_acceptable_go_out = 14 + int(profile.aggression * 4)
|
max_acceptable_go_out = 14 + int(profile.aggression * 4)
|
||||||
|
|
||||||
|
# Check opponent scores - don't go out if we'd lose badly
|
||||||
|
opponent_min = estimate_opponent_min_score(player, game, optimistic=False)
|
||||||
|
# Aggressive players tolerate a bigger gap; conservative ones less
|
||||||
|
opponent_margin = 4 + int(profile.aggression * 4) # 4-8 points
|
||||||
|
opponent_cap = opponent_min + opponent_margin
|
||||||
|
|
||||||
|
# Use the more restrictive of the two thresholds
|
||||||
|
effective_max = min(max_acceptable_go_out, opponent_cap)
|
||||||
|
|
||||||
ai_log(f" Go-out safety check: visible_base={visible_score}, "
|
ai_log(f" Go-out safety check: visible_base={visible_score}, "
|
||||||
f"score_if_swap={score_if_swap}, score_if_flip={score_if_flip}, "
|
f"score_if_swap={score_if_swap}, score_if_flip={score_if_flip}, "
|
||||||
f"max_acceptable={max_acceptable_go_out}")
|
f"max_acceptable={max_acceptable_go_out}, opponent_min={opponent_min}, "
|
||||||
|
f"opponent_cap={opponent_cap}, effective_max={effective_max}")
|
||||||
|
|
||||||
|
# High-card safety: don't swap 8+ into hidden position unless it makes a pair
|
||||||
|
creates_pair = (last_partner.face_up and last_partner.rank == drawn_card.rank)
|
||||||
|
if drawn_value >= HIGH_CARD_THRESHOLD and not creates_pair:
|
||||||
|
ai_log(f" >> GO-OUT: high card ({drawn_value}) into hidden, preferring flip")
|
||||||
|
return None # Fall through to normal scoring (will flip)
|
||||||
|
|
||||||
# If BOTH options are bad, choose the better one
|
# If BOTH options are bad, choose the better one
|
||||||
if score_if_swap > max_acceptable_go_out and score_if_flip > max_acceptable_go_out:
|
if score_if_swap > effective_max and score_if_flip > effective_max:
|
||||||
if score_if_swap <= score_if_flip:
|
if score_if_swap <= score_if_flip:
|
||||||
ai_log(f" >> SAFETY: both options bad, but swap ({score_if_swap}) "
|
ai_log(f" >> SAFETY: both options bad, but swap ({score_if_swap}) "
|
||||||
f"<= flip ({score_if_flip}), forcing swap")
|
f"<= flip ({score_if_flip}), forcing swap")
|
||||||
@@ -1322,7 +1339,7 @@ class GolfAI:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
# If swap is good, prefer it (known outcome vs unknown flip)
|
# If swap is good, prefer it (known outcome vs unknown flip)
|
||||||
elif score_if_swap <= max_acceptable_go_out and score_if_swap <= score_if_flip:
|
elif score_if_swap <= effective_max and score_if_swap <= score_if_flip:
|
||||||
ai_log(f" >> SAFETY: swap gives acceptable score {score_if_swap}")
|
ai_log(f" >> SAFETY: swap gives acceptable score {score_if_swap}")
|
||||||
return last_pos
|
return last_pos
|
||||||
|
|
||||||
@@ -1739,9 +1756,23 @@ class GolfAI:
|
|||||||
expected_hidden_total = len(face_down) * EXPECTED_HIDDEN_VALUE
|
expected_hidden_total = len(face_down) * EXPECTED_HIDDEN_VALUE
|
||||||
projected_score = visible_score + expected_hidden_total
|
projected_score = visible_score + expected_hidden_total
|
||||||
|
|
||||||
|
# Hard cap: never knock with projected score > 10
|
||||||
|
if projected_score > 10:
|
||||||
|
ai_log(f" Knock rejected: projected score {projected_score:.1f} > 10 hard cap")
|
||||||
|
return False
|
||||||
|
|
||||||
# Tighter threshold: range 5 to 9 based on aggression
|
# Tighter threshold: range 5 to 9 based on aggression
|
||||||
max_acceptable = 5 + int(profile.aggression * 4)
|
max_acceptable = 5 + int(profile.aggression * 4)
|
||||||
|
|
||||||
|
# Check opponent threat - don't knock if an opponent likely beats us
|
||||||
|
opponent_min = estimate_opponent_min_score(player, game, optimistic=False)
|
||||||
|
if opponent_min < projected_score:
|
||||||
|
# Opponent is likely beating us - penalize threshold
|
||||||
|
threat_margin = projected_score - opponent_min
|
||||||
|
max_acceptable -= int(threat_margin * 0.75)
|
||||||
|
ai_log(f" Knock threat penalty: opponent est {opponent_min}, "
|
||||||
|
f"margin {threat_margin:.1f}, threshold now {max_acceptable}")
|
||||||
|
|
||||||
# Exception: if all opponents are showing terrible scores, relax threshold
|
# Exception: if all opponents are showing terrible scores, relax threshold
|
||||||
all_opponents_bad = all(
|
all_opponents_bad = all(
|
||||||
sum(get_ai_card_value(c, game.options) for c in p.cards if c.face_up) >= 25
|
sum(get_ai_card_value(c, game.options) for c in p.cards if c.face_up) >= 25
|
||||||
@@ -1752,12 +1783,14 @@ class GolfAI:
|
|||||||
|
|
||||||
if projected_score <= max_acceptable:
|
if projected_score <= max_acceptable:
|
||||||
# Scale knock chance by how good the projected score is
|
# Scale knock chance by how good the projected score is
|
||||||
if projected_score <= 5:
|
if projected_score <= 4:
|
||||||
knock_chance = profile.aggression * 0.3 # Max 30%
|
knock_chance = profile.aggression * 0.35 # Max 35%
|
||||||
elif projected_score <= 7:
|
elif projected_score <= 6:
|
||||||
knock_chance = profile.aggression * 0.15 # Max 15%
|
knock_chance = profile.aggression * 0.15 # Max 15%
|
||||||
else:
|
elif projected_score <= 8:
|
||||||
knock_chance = profile.aggression * 0.05 # Max 5% (very rare)
|
knock_chance = profile.aggression * 0.06 # Max 6%
|
||||||
|
else: # 9-10
|
||||||
|
knock_chance = profile.aggression * 0.02 # Max 2% (very rare)
|
||||||
|
|
||||||
if random.random() < knock_chance:
|
if random.random() < knock_chance:
|
||||||
ai_log(f" Knock early: taking the gamble! (projected {projected_score:.1f})")
|
ai_log(f" Knock early: taking the gamble! (projected {projected_score:.1f})")
|
||||||
@@ -1934,7 +1967,11 @@ def _log_cpu_action(logger, game_id: Optional[str], cpu_player: Player, game: Ga
|
|||||||
async def process_cpu_turn(
|
async def process_cpu_turn(
|
||||||
game: Game, cpu_player: Player, broadcast_callback, game_id: Optional[str] = None
|
game: Game, cpu_player: Player, broadcast_callback, game_id: Optional[str] = None
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Process a complete turn for a CPU player."""
|
"""Process a complete turn for a CPU player.
|
||||||
|
|
||||||
|
May raise asyncio.CancelledError if the game is ended mid-turn.
|
||||||
|
The caller (check_and_run_cpu_turn) handles cancellation.
|
||||||
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
from services.game_logger import get_logger
|
from services.game_logger import get_logger
|
||||||
|
|
||||||
@@ -1962,10 +1999,8 @@ async def process_cpu_turn(
|
|||||||
await asyncio.sleep(thinking_time)
|
await asyncio.sleep(thinking_time)
|
||||||
ai_log(f"{cpu_player.name} done thinking, making decision")
|
ai_log(f"{cpu_player.name} done thinking, making decision")
|
||||||
|
|
||||||
# Check if we should try to go out early
|
|
||||||
GolfAI.should_go_out_early(cpu_player, game, profile)
|
|
||||||
|
|
||||||
# Check if we should knock early (flip all remaining cards at once)
|
# Check if we should knock early (flip all remaining cards at once)
|
||||||
|
# (Opponent threat logic consolidated into should_knock_early)
|
||||||
if GolfAI.should_knock_early(game, cpu_player, profile):
|
if GolfAI.should_knock_early(game, cpu_player, profile):
|
||||||
if game.knock_early(cpu_player.id):
|
if game.knock_early(cpu_player.id):
|
||||||
_log_cpu_action(logger, game_id, cpu_player, game,
|
_log_cpu_action(logger, game_id, cpu_player, game,
|
||||||
|
|||||||
@@ -229,7 +229,7 @@ async def handle_start_game(data: dict, ctx: ConnectionContext, *, broadcast_gam
|
|||||||
"game_state": game_state,
|
"game_state": game_state,
|
||||||
})
|
})
|
||||||
|
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_flip_initial(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
async def handle_flip_initial(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
||||||
@@ -240,7 +240,7 @@ async def handle_flip_initial(data: dict, ctx: ConnectionContext, *, broadcast_g
|
|||||||
async with ctx.current_room.game_lock:
|
async with ctx.current_room.game_lock:
|
||||||
if ctx.current_room.game.flip_initial_cards(ctx.player_id, positions):
|
if ctx.current_room.game.flip_initial_cards(ctx.player_id, positions):
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -297,7 +297,7 @@ async def handle_swap(data: dict, ctx: ConnectionContext, *, broadcast_game_stat
|
|||||||
|
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
await asyncio.sleep(1.0)
|
await asyncio.sleep(1.0)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_discard(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
async def handle_discard(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
||||||
@@ -329,12 +329,12 @@ async def handle_discard(data: dict, ctx: ConnectionContext, *, broadcast_game_s
|
|||||||
})
|
})
|
||||||
else:
|
else:
|
||||||
await asyncio.sleep(0.5)
|
await asyncio.sleep(0.5)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
else:
|
else:
|
||||||
logger.debug("Player discarded, waiting 0.5s before CPU turn")
|
logger.debug("Player discarded, waiting 0.5s before CPU turn")
|
||||||
await asyncio.sleep(0.5)
|
await asyncio.sleep(0.5)
|
||||||
logger.debug("Post-discard delay complete, checking for CPU turn")
|
logger.debug("Post-discard delay complete, checking for CPU turn")
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_cancel_draw(data: dict, ctx: ConnectionContext, *, broadcast_game_state, **kw) -> None:
|
async def handle_cancel_draw(data: dict, ctx: ConnectionContext, *, broadcast_game_state, **kw) -> None:
|
||||||
@@ -364,7 +364,7 @@ async def handle_flip_card(data: dict, ctx: ConnectionContext, *, broadcast_game
|
|||||||
)
|
)
|
||||||
|
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_skip_flip(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
async def handle_skip_flip(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
||||||
@@ -380,7 +380,7 @@ async def handle_skip_flip(data: dict, ctx: ConnectionContext, *, broadcast_game
|
|||||||
)
|
)
|
||||||
|
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_flip_as_action(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
async def handle_flip_as_action(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
||||||
@@ -400,7 +400,7 @@ async def handle_flip_as_action(data: dict, ctx: ConnectionContext, *, broadcast
|
|||||||
)
|
)
|
||||||
|
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_knock_early(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
async def handle_knock_early(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
||||||
@@ -418,7 +418,7 @@ async def handle_knock_early(data: dict, ctx: ConnectionContext, *, broadcast_ga
|
|||||||
)
|
)
|
||||||
|
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
|
|
||||||
|
|
||||||
async def handle_next_round(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
async def handle_next_round(data: dict, ctx: ConnectionContext, *, broadcast_game_state, check_and_run_cpu_turn, **kw) -> None:
|
||||||
@@ -443,7 +443,7 @@ async def handle_next_round(data: dict, ctx: ConnectionContext, *, broadcast_gam
|
|||||||
"game_state": game_state,
|
"game_state": game_state,
|
||||||
})
|
})
|
||||||
|
|
||||||
await check_and_run_cpu_turn(ctx.current_room)
|
check_and_run_cpu_turn(ctx.current_room)
|
||||||
else:
|
else:
|
||||||
await broadcast_game_state(ctx.current_room)
|
await broadcast_game_state(ctx.current_room)
|
||||||
|
|
||||||
@@ -473,6 +473,15 @@ async def handle_end_game(data: dict, ctx: ConnectionContext, *, room_manager, c
|
|||||||
await ctx.websocket.send_json({"type": "error", "message": "Only the host can end the game"})
|
await ctx.websocket.send_json({"type": "error", "message": "Only the host can end the game"})
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Cancel any running CPU turn task so the game ends immediately
|
||||||
|
if ctx.current_room.cpu_turn_task:
|
||||||
|
ctx.current_room.cpu_turn_task.cancel()
|
||||||
|
try:
|
||||||
|
await ctx.current_room.cpu_turn_task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
ctx.current_room.cpu_turn_task = None
|
||||||
|
|
||||||
await ctx.current_room.broadcast({
|
await ctx.current_room.broadcast({
|
||||||
"type": "game_ended",
|
"type": "game_ended",
|
||||||
"reason": "Host ended the game",
|
"reason": "Host ended the game",
|
||||||
|
|||||||
@@ -148,6 +148,39 @@ class DevelopmentFormatter(logging.Formatter):
|
|||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
# Per-module log level overrides via env vars.
|
||||||
|
# Key: env var suffix, Value: list of Python logger names to apply to.
|
||||||
|
MODULE_LOGGER_MAP = {
|
||||||
|
"GAME": ["game"],
|
||||||
|
"AI": ["ai"],
|
||||||
|
"HANDLERS": ["handlers"],
|
||||||
|
"ROOM": ["room"],
|
||||||
|
"AUTH": ["auth", "routers.auth", "services.auth_service"],
|
||||||
|
"STORES": ["stores"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_module_overrides() -> dict[str, str]:
|
||||||
|
"""
|
||||||
|
Apply per-module log level overrides from LOG_LEVEL_{MODULE} env vars.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict of module name -> level for any overrides that were applied.
|
||||||
|
"""
|
||||||
|
active = {}
|
||||||
|
for module, logger_names in MODULE_LOGGER_MAP.items():
|
||||||
|
env_val = os.environ.get(f"LOG_LEVEL_{module}", "").upper()
|
||||||
|
if not env_val:
|
||||||
|
continue
|
||||||
|
level = getattr(logging, env_val, None)
|
||||||
|
if level is None:
|
||||||
|
continue
|
||||||
|
active[module] = env_val
|
||||||
|
for name in logger_names:
|
||||||
|
logging.getLogger(name).setLevel(level)
|
||||||
|
return active
|
||||||
|
|
||||||
|
|
||||||
def setup_logging(
|
def setup_logging(
|
||||||
level: str = "INFO",
|
level: str = "INFO",
|
||||||
environment: str = "development",
|
environment: str = "development",
|
||||||
@@ -182,12 +215,19 @@ def setup_logging(
|
|||||||
logging.getLogger("websockets").setLevel(logging.WARNING)
|
logging.getLogger("websockets").setLevel(logging.WARNING)
|
||||||
logging.getLogger("asyncio").setLevel(logging.WARNING)
|
logging.getLogger("asyncio").setLevel(logging.WARNING)
|
||||||
|
|
||||||
|
# Apply per-module overrides from env vars
|
||||||
|
overrides = _apply_module_overrides()
|
||||||
|
|
||||||
# Log startup
|
# Log startup
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Logging configured: level={level}, environment={environment}",
|
f"Logging configured: level={level}, environment={environment}",
|
||||||
extra={"level": level, "environment": environment},
|
extra={"level": level, "environment": environment},
|
||||||
)
|
)
|
||||||
|
if overrides:
|
||||||
|
logger.info(
|
||||||
|
f"Per-module log level overrides: {', '.join(f'{m}={l}' for m, l in overrides.items())}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ContextLogger(logging.LoggerAdapter):
|
class ContextLogger(logging.LoggerAdapter):
|
||||||
|
|||||||
@@ -705,8 +705,40 @@ async def broadcast_game_state(room: Room):
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
async def check_and_run_cpu_turn(room: Room):
|
def check_and_run_cpu_turn(room: Room):
|
||||||
"""Check if current player is CPU and run their turn."""
|
"""Check if current player is CPU and start their turn as a background task.
|
||||||
|
|
||||||
|
The CPU turn chain runs as a fire-and-forget asyncio.Task stored on
|
||||||
|
room.cpu_turn_task. This allows the WebSocket message loop to remain
|
||||||
|
responsive so that end_game/leave messages can cancel the task immediately.
|
||||||
|
"""
|
||||||
|
if room.game.phase not in (GamePhase.PLAYING, GamePhase.FINAL_TURN):
|
||||||
|
return
|
||||||
|
|
||||||
|
current = room.game.current_player()
|
||||||
|
if not current:
|
||||||
|
return
|
||||||
|
|
||||||
|
room_player = room.get_player(current.id)
|
||||||
|
if not room_player or not room_player.is_cpu:
|
||||||
|
return
|
||||||
|
|
||||||
|
task = asyncio.create_task(_run_cpu_chain(room))
|
||||||
|
room.cpu_turn_task = task
|
||||||
|
|
||||||
|
def _on_done(t: asyncio.Task):
|
||||||
|
# Clear the reference when the task finishes (success, cancel, or error)
|
||||||
|
if room.cpu_turn_task is t:
|
||||||
|
room.cpu_turn_task = None
|
||||||
|
if not t.cancelled() and t.exception():
|
||||||
|
logger.error(f"CPU turn task error in room {room.code}: {t.exception()}")
|
||||||
|
|
||||||
|
task.add_done_callback(_on_done)
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_cpu_chain(room: Room):
|
||||||
|
"""Run consecutive CPU turns until a human player's turn or game ends."""
|
||||||
|
while True:
|
||||||
if room.game.phase not in (GamePhase.PLAYING, GamePhase.FINAL_TURN):
|
if room.game.phase not in (GamePhase.PLAYING, GamePhase.FINAL_TURN):
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -727,12 +759,18 @@ async def check_and_run_cpu_turn(room: Room):
|
|||||||
|
|
||||||
await process_cpu_turn(room.game, current, broadcast_cb, game_id=room.game_log_id)
|
await process_cpu_turn(room.game, current, broadcast_cb, game_id=room.game_log_id)
|
||||||
|
|
||||||
# Check if next player is also CPU (chain CPU turns)
|
|
||||||
await check_and_run_cpu_turn(room)
|
|
||||||
|
|
||||||
|
|
||||||
async def handle_player_leave(room: Room, player_id: str):
|
async def handle_player_leave(room: Room, player_id: str):
|
||||||
"""Handle a player leaving a room."""
|
"""Handle a player leaving a room."""
|
||||||
|
# Cancel any running CPU turn task before cleanup
|
||||||
|
if room.cpu_turn_task:
|
||||||
|
room.cpu_turn_task.cancel()
|
||||||
|
try:
|
||||||
|
await room.cpu_turn_task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
room.cpu_turn_task = None
|
||||||
|
|
||||||
room_code = room.code
|
room_code = room.code
|
||||||
room_player = room.remove_player(player_id)
|
room_player = room.remove_player(player_id)
|
||||||
|
|
||||||
@@ -768,6 +806,10 @@ if os.path.exists(client_path):
|
|||||||
async def serve_replay_page(share_code: str):
|
async def serve_replay_page(share_code: str):
|
||||||
return FileResponse(os.path.join(client_path, "index.html"))
|
return FileResponse(os.path.join(client_path, "index.html"))
|
||||||
|
|
||||||
|
@app.get("/reset-password")
|
||||||
|
async def serve_reset_password_page():
|
||||||
|
return FileResponse(os.path.join(client_path, "index.html"))
|
||||||
|
|
||||||
# Mount static files for everything else (JS, CSS, SVG, etc.)
|
# Mount static files for everything else (JS, CSS, SVG, etc.)
|
||||||
app.mount("/", StaticFiles(directory=client_path), name="static")
|
app.mount("/", StaticFiles(directory=client_path), name="static")
|
||||||
|
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ class Room:
|
|||||||
settings: dict = field(default_factory=lambda: {"decks": 1, "rounds": 1})
|
settings: dict = field(default_factory=lambda: {"decks": 1, "rounds": 1})
|
||||||
game_log_id: Optional[str] = None
|
game_log_id: Optional[str] = None
|
||||||
game_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
game_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
||||||
|
cpu_turn_task: Optional[asyncio.Task] = None
|
||||||
|
|
||||||
def add_player(
|
def add_player(
|
||||||
self,
|
self,
|
||||||
|
|||||||
Reference in New Issue
Block a user