Add refresh reconnect and live rename
Browse files- app.py +13 -0
- static/index.html +108 -5
- tests/test_websocket.py +46 -0
app.py
CHANGED
|
@@ -458,6 +458,16 @@ class Room:
|
|
| 458 |
player.said_uno = True
|
| 459 |
return {"type": "uno_called", "playerId": player_id, "playerName": player.name}
|
| 460 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
def mark_finished_if_needed(self, player: Player) -> None:
|
| 462 |
if player.hand or player.finished:
|
| 463 |
return
|
|
@@ -752,6 +762,9 @@ async def handle_command(room: Room, player_id: str, data: dict[str, Any]) -> No
|
|
| 752 |
elif command == "call_uno":
|
| 753 |
event = room.call_uno(player_id)
|
| 754 |
changed = True
|
|
|
|
|
|
|
|
|
|
| 755 |
elif command == "restart":
|
| 756 |
event = room.start_game(player_id)
|
| 757 |
changed = True
|
|
|
|
| 458 |
player.said_uno = True
|
| 459 |
return {"type": "uno_called", "playerId": player_id, "playerName": player.name}
|
| 460 |
|
| 461 |
+
def rename_player(self, player_id: str, name: str) -> dict[str, Any]:
|
| 462 |
+
player = self.get_player(player_id)
|
| 463 |
+
if player.is_bot:
|
| 464 |
+
raise GameError("bot_rename", "Bots cannot be renamed from a socket.")
|
| 465 |
+
new_name = normalize_name(name)
|
| 466 |
+
if player.name == new_name:
|
| 467 |
+
return {"type": "player_renamed", "playerId": player_id, "playerName": player.name}
|
| 468 |
+
player.name = new_name
|
| 469 |
+
return {"type": "player_renamed", "playerId": player_id, "playerName": player.name}
|
| 470 |
+
|
| 471 |
def mark_finished_if_needed(self, player: Player) -> None:
|
| 472 |
if player.hand or player.finished:
|
| 473 |
return
|
|
|
|
| 762 |
elif command == "call_uno":
|
| 763 |
event = room.call_uno(player_id)
|
| 764 |
changed = True
|
| 765 |
+
elif command == "rename":
|
| 766 |
+
event = room.rename_player(player_id, str(payload.get("name", "")))
|
| 767 |
+
changed = True
|
| 768 |
elif command == "restart":
|
| 769 |
event = room.start_game(player_id)
|
| 770 |
changed = True
|
static/index.html
CHANGED
|
@@ -218,10 +218,14 @@ const DRAW_STACK_MAX_VISIBLE = 8;
|
|
| 218 |
let state = null;
|
| 219 |
let ws = null;
|
| 220 |
let credentials = null;
|
|
|
|
| 221 |
let previousPhase = null;
|
| 222 |
let previousColor = null;
|
| 223 |
let pendingDeal = false;
|
| 224 |
let selectedDifficulty = 'hard';
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
const $ = (id) => document.getElementById(id);
|
| 227 |
|
|
@@ -233,6 +237,33 @@ function setConnection(online){
|
|
| 233 |
}
|
| 234 |
function sanitizeRoomCode(value){ return (value || '').trim().toUpperCase().replace(/[^A-Z0-9]/g,'').slice(0,5); }
|
| 235 |
function getName(){ return ($('name-input').value || 'Player').trim() || 'Player'; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
async function createRoom(){
|
| 238 |
setStatus('Creating room...');
|
|
@@ -249,6 +280,8 @@ async function createRoom(){
|
|
| 249 |
});
|
| 250 |
if(!res.ok){ setStatus(await responseText(res)); return; }
|
| 251 |
credentials = await res.json();
|
|
|
|
|
|
|
| 252 |
$('room-input').value = credentials.roomCode;
|
| 253 |
connectSocket();
|
| 254 |
}
|
|
@@ -264,6 +297,8 @@ async function joinRoom(){
|
|
| 264 |
});
|
| 265 |
if(!res.ok){ setStatus(await responseText(res)); return; }
|
| 266 |
credentials = await res.json();
|
|
|
|
|
|
|
| 267 |
connectSocket();
|
| 268 |
}
|
| 269 |
|
|
@@ -277,26 +312,64 @@ async function responseText(res){
|
|
| 277 |
}
|
| 278 |
|
| 279 |
function connectSocket(){
|
|
|
|
| 280 |
if(ws) ws.close();
|
|
|
|
| 281 |
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
| 282 |
const url = `${proto}://${location.host}/ws/${credentials.roomCode}?playerId=${encodeURIComponent(credentials.playerId)}&token=${encodeURIComponent(credentials.token)}`;
|
| 283 |
ws = new WebSocket(url);
|
| 284 |
-
ws.onopen = () => {
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
ws.onerror = () => setStatus('Connection error.');
|
| 287 |
ws.onmessage = (message) => {
|
| 288 |
const payload = JSON.parse(message.data);
|
| 289 |
if(payload.type === 'snapshot') handleSnapshot(payload.state);
|
| 290 |
if(payload.type === 'event') handleEvent(payload.event);
|
| 291 |
-
if(payload.type === 'error')
|
| 292 |
};
|
| 293 |
}
|
| 294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
function send(type,payload={}){
|
| 296 |
if(!ws || ws.readyState !== WebSocket.OPEN){ setStatus('Socket is not connected.'); return; }
|
| 297 |
ws.send(JSON.stringify({type,payload}));
|
| 298 |
}
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
function handleEvent(event){
|
| 301 |
if(!event) return;
|
| 302 |
if(event.type === 'card_played'){
|
|
@@ -321,7 +394,10 @@ function handleEvent(event){
|
|
| 321 |
if(event.type === 'game_started'){
|
| 322 |
pendingDeal = true;
|
| 323 |
}
|
| 324 |
-
if(
|
|
|
|
|
|
|
|
|
|
| 325 |
setStatus('');
|
| 326 |
}
|
| 327 |
}
|
|
@@ -329,6 +405,7 @@ function handleEvent(event){
|
|
| 329 |
function handleSnapshot(nextState){
|
| 330 |
previousPhase = state ? state.phase : null;
|
| 331 |
state = nextState;
|
|
|
|
| 332 |
renderApp();
|
| 333 |
if((previousPhase === 'lobby' && state.phase === 'playing') || pendingDeal){
|
| 334 |
pendingDeal = false;
|
|
@@ -336,6 +413,22 @@ function handleSnapshot(nextState){
|
|
| 336 |
}
|
| 337 |
}
|
| 338 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
function renderApp(){
|
| 340 |
if(!state) return;
|
| 341 |
if(state.phase === 'lobby'){
|
|
@@ -842,6 +935,7 @@ function cssEscape(value){
|
|
| 842 |
return window.CSS && CSS.escape ? CSS.escape(value) : String(value).replace(/"/g,'\\"');
|
| 843 |
}
|
| 844 |
|
|
|
|
| 845 |
$('create-room-btn').addEventListener('click',createRoom);
|
| 846 |
$('join-room-btn').addEventListener('click',joinRoom);
|
| 847 |
$('room-input').addEventListener('input',e=>{ e.target.value = sanitizeRoomCode(e.target.value); });
|
|
@@ -914,8 +1008,17 @@ window.render_game_to_text = () => JSON.stringify({
|
|
| 914 |
});
|
| 915 |
window.advanceTime = () => { if(state) renderAll(); };
|
| 916 |
|
| 917 |
-
$('name-input').value = `Player ${Math.floor(100 + Math.random()*900)}`;
|
| 918 |
setConnection(false);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 919 |
</script>
|
| 920 |
</body>
|
| 921 |
</html>
|
|
|
|
| 218 |
let state = null;
|
| 219 |
let ws = null;
|
| 220 |
let credentials = null;
|
| 221 |
+
let reconnectingFromStorage = false;
|
| 222 |
let previousPhase = null;
|
| 223 |
let previousColor = null;
|
| 224 |
let pendingDeal = false;
|
| 225 |
let selectedDifficulty = 'hard';
|
| 226 |
+
let renameTimer = null;
|
| 227 |
+
let lastRenameSent = '';
|
| 228 |
+
const STORAGE_KEY = 'uno_multiplayer_session_v1';
|
| 229 |
|
| 230 |
const $ = (id) => document.getElementById(id);
|
| 231 |
|
|
|
|
| 237 |
}
|
| 238 |
function sanitizeRoomCode(value){ return (value || '').trim().toUpperCase().replace(/[^A-Z0-9]/g,'').slice(0,5); }
|
| 239 |
function getName(){ return ($('name-input').value || 'Player').trim() || 'Player'; }
|
| 240 |
+
function loadSavedSession(){
|
| 241 |
+
try{
|
| 242 |
+
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null');
|
| 243 |
+
if(saved && saved.roomCode && saved.playerId && saved.token) return saved;
|
| 244 |
+
}catch{}
|
| 245 |
+
return null;
|
| 246 |
+
}
|
| 247 |
+
function saveSession(extra={}){
|
| 248 |
+
if(!credentials) return;
|
| 249 |
+
const payload = {
|
| 250 |
+
roomCode: credentials.roomCode,
|
| 251 |
+
playerId: credentials.playerId,
|
| 252 |
+
token: credentials.token,
|
| 253 |
+
name: getName(),
|
| 254 |
+
savedAt: Date.now(),
|
| 255 |
+
...extra
|
| 256 |
+
};
|
| 257 |
+
try{ localStorage.setItem(STORAGE_KEY, JSON.stringify(payload)); }catch{}
|
| 258 |
+
}
|
| 259 |
+
function clearSavedSession(){
|
| 260 |
+
try{ localStorage.removeItem(STORAGE_KEY); }catch{}
|
| 261 |
+
}
|
| 262 |
+
function restoreEntryUi(session){
|
| 263 |
+
if(!session) return;
|
| 264 |
+
$('room-input').value = session.roomCode || '';
|
| 265 |
+
if(session.name) $('name-input').value = session.name;
|
| 266 |
+
}
|
| 267 |
|
| 268 |
async function createRoom(){
|
| 269 |
setStatus('Creating room...');
|
|
|
|
| 280 |
});
|
| 281 |
if(!res.ok){ setStatus(await responseText(res)); return; }
|
| 282 |
credentials = await res.json();
|
| 283 |
+
credentials.name = getName();
|
| 284 |
+
saveSession();
|
| 285 |
$('room-input').value = credentials.roomCode;
|
| 286 |
connectSocket();
|
| 287 |
}
|
|
|
|
| 297 |
});
|
| 298 |
if(!res.ok){ setStatus(await responseText(res)); return; }
|
| 299 |
credentials = await res.json();
|
| 300 |
+
credentials.name = getName();
|
| 301 |
+
saveSession();
|
| 302 |
connectSocket();
|
| 303 |
}
|
| 304 |
|
|
|
|
| 312 |
}
|
| 313 |
|
| 314 |
function connectSocket(){
|
| 315 |
+
if(!credentials) return;
|
| 316 |
if(ws) ws.close();
|
| 317 |
+
restoreEntryUi(credentials);
|
| 318 |
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
| 319 |
const url = `${proto}://${location.host}/ws/${credentials.roomCode}?playerId=${encodeURIComponent(credentials.playerId)}&token=${encodeURIComponent(credentials.token)}`;
|
| 320 |
ws = new WebSocket(url);
|
| 321 |
+
ws.onopen = () => {
|
| 322 |
+
setConnection(true);
|
| 323 |
+
setStatus(reconnectingFromStorage ? 'Reconnected to your room.' : 'Connected.');
|
| 324 |
+
reconnectingFromStorage = false;
|
| 325 |
+
if(credentials.name) scheduleRename({immediate:true});
|
| 326 |
+
};
|
| 327 |
+
ws.onclose = () => { setConnection(false); setStatus(credentials ? 'Connection closed. Refresh or rejoin with your room code.' : 'Not connected.'); };
|
| 328 |
ws.onerror = () => setStatus('Connection error.');
|
| 329 |
ws.onmessage = (message) => {
|
| 330 |
const payload = JSON.parse(message.data);
|
| 331 |
if(payload.type === 'snapshot') handleSnapshot(payload.state);
|
| 332 |
if(payload.type === 'event') handleEvent(payload.event);
|
| 333 |
+
if(payload.type === 'error') handleSocketError(payload);
|
| 334 |
};
|
| 335 |
}
|
| 336 |
|
| 337 |
+
function handleSocketError(payload){
|
| 338 |
+
setStatus(payload.message || payload.code || 'Error');
|
| 339 |
+
if(['room_not_found','bad_token','player_not_found','bot_socket'].includes(payload.code)){
|
| 340 |
+
clearSavedSession();
|
| 341 |
+
credentials = null;
|
| 342 |
+
state = null;
|
| 343 |
+
if(ws) ws.close();
|
| 344 |
+
$('start-screen').style.display = 'flex';
|
| 345 |
+
$('start-screen').style.opacity = '1';
|
| 346 |
+
$('start-screen').classList.remove('connected');
|
| 347 |
+
$('connected-panel').classList.add('hidden');
|
| 348 |
+
$('game-board').classList.remove('active');
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
function send(type,payload={}){
|
| 353 |
if(!ws || ws.readyState !== WebSocket.OPEN){ setStatus('Socket is not connected.'); return; }
|
| 354 |
ws.send(JSON.stringify({type,payload}));
|
| 355 |
}
|
| 356 |
|
| 357 |
+
function scheduleRename({immediate=false}={}){
|
| 358 |
+
const name = getName();
|
| 359 |
+
if(credentials) credentials.name = name;
|
| 360 |
+
saveSession({name});
|
| 361 |
+
clearTimeout(renameTimer);
|
| 362 |
+
const run = () => {
|
| 363 |
+
const currentName = getName();
|
| 364 |
+
if(!credentials || !ws || ws.readyState !== WebSocket.OPEN) return;
|
| 365 |
+
if(!currentName || currentName === lastRenameSent) return;
|
| 366 |
+
lastRenameSent = currentName;
|
| 367 |
+
send('rename',{name:currentName});
|
| 368 |
+
};
|
| 369 |
+
if(immediate) run();
|
| 370 |
+
else renameTimer = setTimeout(run,350);
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
function handleEvent(event){
|
| 374 |
if(!event) return;
|
| 375 |
if(event.type === 'card_played'){
|
|
|
|
| 394 |
if(event.type === 'game_started'){
|
| 395 |
pendingDeal = true;
|
| 396 |
}
|
| 397 |
+
if(event.type === 'player_renamed'){
|
| 398 |
+
showToast(`${event.playerName || 'Player'} renamed`,'player-turn');
|
| 399 |
+
}
|
| 400 |
+
if(['bot_added','bot_removed','player_joined','player_connected','player_disconnected','room_options_changed','player_renamed'].includes(event.type)){
|
| 401 |
setStatus('');
|
| 402 |
}
|
| 403 |
}
|
|
|
|
| 405 |
function handleSnapshot(nextState){
|
| 406 |
previousPhase = state ? state.phase : null;
|
| 407 |
state = nextState;
|
| 408 |
+
syncLocalSessionFromState();
|
| 409 |
renderApp();
|
| 410 |
if((previousPhase === 'lobby' && state.phase === 'playing') || pendingDeal){
|
| 411 |
pendingDeal = false;
|
|
|
|
| 413 |
}
|
| 414 |
}
|
| 415 |
|
| 416 |
+
function syncLocalSessionFromState(){
|
| 417 |
+
const me = state?.players?.find(player=>player.id === state.myPlayerId);
|
| 418 |
+
if(!me || !credentials) return;
|
| 419 |
+
credentials.roomCode = state.roomCode;
|
| 420 |
+
credentials.playerId = state.myPlayerId;
|
| 421 |
+
if(document.activeElement !== $('name-input')){
|
| 422 |
+
$('name-input').value = me.name;
|
| 423 |
+
credentials.name = me.name;
|
| 424 |
+
lastRenameSent = me.name;
|
| 425 |
+
saveSession({name:me.name});
|
| 426 |
+
} else {
|
| 427 |
+
credentials.name = getName();
|
| 428 |
+
saveSession({name:getName()});
|
| 429 |
+
}
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
function renderApp(){
|
| 433 |
if(!state) return;
|
| 434 |
if(state.phase === 'lobby'){
|
|
|
|
| 935 |
return window.CSS && CSS.escape ? CSS.escape(value) : String(value).replace(/"/g,'\\"');
|
| 936 |
}
|
| 937 |
|
| 938 |
+
$('name-input').addEventListener('input',()=>scheduleRename());
|
| 939 |
$('create-room-btn').addEventListener('click',createRoom);
|
| 940 |
$('join-room-btn').addEventListener('click',joinRoom);
|
| 941 |
$('room-input').addEventListener('input',e=>{ e.target.value = sanitizeRoomCode(e.target.value); });
|
|
|
|
| 1008 |
});
|
| 1009 |
window.advanceTime = () => { if(state) renderAll(); };
|
| 1010 |
|
|
|
|
| 1011 |
setConnection(false);
|
| 1012 |
+
const savedSession = loadSavedSession();
|
| 1013 |
+
if(savedSession){
|
| 1014 |
+
credentials = savedSession;
|
| 1015 |
+
restoreEntryUi(savedSession);
|
| 1016 |
+
reconnectingFromStorage = true;
|
| 1017 |
+
setStatus('Reconnecting to your room...');
|
| 1018 |
+
connectSocket();
|
| 1019 |
+
}else{
|
| 1020 |
+
$('name-input').value = `Player ${Math.floor(100 + Math.random()*900)}`;
|
| 1021 |
+
}
|
| 1022 |
</script>
|
| 1023 |
</body>
|
| 1024 |
</html>
|
tests/test_websocket.py
CHANGED
|
@@ -112,6 +112,52 @@ def test_room_full_and_started_errors():
|
|
| 112 |
assert late.status_code == 409
|
| 113 |
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
def test_bad_room_and_bad_token_errors():
|
| 116 |
with TestClient(app) as client:
|
| 117 |
missing = client.post("/api/rooms/ZZZZZ/join", json={"name": "Nope"})
|
|
|
|
| 112 |
assert late.status_code == 409
|
| 113 |
|
| 114 |
|
| 115 |
+
def test_rename_broadcasts_and_reconnect_restores_playing_seat():
|
| 116 |
+
with TestClient(app) as client:
|
| 117 |
+
host = create_room(client, total=3)
|
| 118 |
+
p2 = join_room(client, host["roomCode"], "P2")
|
| 119 |
+
p3 = join_room(client, host["roomCode"], "P3")
|
| 120 |
+
|
| 121 |
+
with (
|
| 122 |
+
client.websocket_connect(ws_url(host)) as ws_host,
|
| 123 |
+
client.websocket_connect(ws_url(p2)) as ws_p2,
|
| 124 |
+
client.websocket_connect(ws_url(p3)),
|
| 125 |
+
):
|
| 126 |
+
read_until_snapshot(ws_host)
|
| 127 |
+
read_until_snapshot(ws_p2)
|
| 128 |
+
|
| 129 |
+
ws_host.send_json({"type": "rename", "payload": {"name": "Renamed Host"}})
|
| 130 |
+
host_view = read_until_snapshot_matching(
|
| 131 |
+
ws_host,
|
| 132 |
+
lambda state: next(p for p in state["players"] if p["id"] == host["playerId"])["name"]
|
| 133 |
+
== "Renamed Host",
|
| 134 |
+
)
|
| 135 |
+
p2_view = read_until_snapshot_matching(
|
| 136 |
+
ws_p2,
|
| 137 |
+
lambda state: next(p for p in state["players"] if p["id"] == host["playerId"])["name"]
|
| 138 |
+
== "Renamed Host",
|
| 139 |
+
)
|
| 140 |
+
assert host_view["players"][0]["name"] == "Renamed Host"
|
| 141 |
+
assert any(p["name"] == "Renamed Host" for p in p2_view["players"])
|
| 142 |
+
|
| 143 |
+
ws_host.send_json({"type": "start_game", "payload": {}})
|
| 144 |
+
playing = read_until_snapshot_matching(ws_host, lambda state: state["phase"] == "playing")
|
| 145 |
+
host_hand_before = [
|
| 146 |
+
card["id"]
|
| 147 |
+
for card in next(p for p in playing["players"] if p["id"] == host["playerId"])["hand"]
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
with client.websocket_connect(ws_url(host)) as ws_reconnected:
|
| 151 |
+
restored = read_until_snapshot_matching(
|
| 152 |
+
ws_reconnected,
|
| 153 |
+
lambda state: state["phase"] == "playing"
|
| 154 |
+
and next(p for p in state["players"] if p["id"] == host["playerId"])["name"]
|
| 155 |
+
== "Renamed Host",
|
| 156 |
+
)
|
| 157 |
+
host_after = next(p for p in restored["players"] if p["id"] == host["playerId"])
|
| 158 |
+
assert [card["id"] for card in host_after["hand"]] == host_hand_before
|
| 159 |
+
|
| 160 |
+
|
| 161 |
def test_bad_room_and_bad_token_errors():
|
| 162 |
with TestClient(app) as client:
|
| 163 |
missing = client.post("/api/rooms/ZZZZZ/join", json={"name": "Nope"})
|