The project-level docs described the pre-caro-port architecture (TCP on
9999, JSON {data:base64} wire format, web/ + core/ + api/ + bot/ dirs,
server flags -w/-t/-s, state strings like '1'/'2'/'7,7') and referenced
files that no longer exist. The README also described an owner-controlled
Start button, 5-second heartbeat, 'database/' directory, AuthRequest
handshake, and linked to now-deleted plan files.
CLAUDE.md
- Rewritten for the current architecture: single WS endpoint at
:1999/gomoku, protobuf binary frames, server/{consts,game,lobby,
network,state,pkg/log}, client/src/{config,scenes,services,ui,
objects,generated}, auto-start PVP semantics, heartbeat 50s/deadline
90s, ClientExit self-vs-peer helper, enum serialization notes, Hard
AI description, and a "When editing" section covering proto regen,
state flow tests, and scene cleanup patterns.
README.md
- Features: owner-controlled start → auto-start on 2nd join.
- Heartbeat: 5s → 50s; add server deadline + reconnect back-off.
- Project structure: database/ → lobby/; services list corrected.
- Protocol: replace AuthRequest story with real SetNickname handshake.
- Credits: trimmed from a multi-bullet block to a single attribution
line ("Based on ratel-online by ainilili"). Removed caro references
and the link to the deleted plans/ implementation history.
docs/system-architecture.md
- Fully rewritten. Drops old TCP+JSON protocol tables, CLI client box,
obsolete state flow diagram. Adds: current state registry
(welcome/setNickname/home/waiting/gamePvp/gamePve/gameover/watching),
cross-goroutine sync channels (StartCh/GameOverCh/RematchCh), typed
enum list, kickStaleRoomPeers note, ClientExit self-vs-peer semantics,
and client module table.
docs/deployment-guide.md
- Remove stale pointer to deleted plans/ directory.
Code comment cleanup (user: "don't mention too much"):
- server/network/handlers_stateless.go handleHeartbeat: drop caro
reference, explain behavior in terms of the reader loop.
- server/game/ai_eval.go: "ported from caro's GomokuAI scoring" →
generic "threat-pattern weights used by the Hard AI".
- server/game/ai.go positionScore: drop caro attribution, describe
the heuristic directly.
- server/lobby/room.go: drop "caro Java domain" annotation, describe
what Room actually embeds.
- client/src/services/game-state-service.js WATCH_GAME_SUCCESS: drop
historical rename comment.
go vet + go test ./... + npm run build all green.
Fixes the server log "gameover player N: unexpected Request_CreateRoom".
Root cause: when ANY player leaves a room, leaveRoom broadcasts
ClientExitResponse to ALL players in room.Players (so peers see who
left). The broadcast fired CLIENT_EXIT on both the exiting client AND
its peer. But the client's handlers treated every CLIENT_EXIT as "I
exited" — transitioning to lobby, clearing gameState.roomId, hiding the
HUD. Meanwhile the peer's server-side state machine was still in
gameoverState. The peer then clicked Create Room from the (now wrongly
shown) lobby, and the request arrived at gameoverState's default case.
Client:
- New services/client-exit-helpers.js with isSelfExit(data, clientId).
exitClientId === 0 or missing → bare self-ack (home.ClientExit /
watching.ClientExit / room-closed eject). exitClientId === clientId
→ our own leaveRoom broadcast loopback. Anything else → a peer left;
stay in state.
- game-state-service CLIENT_EXIT handler: only reset() when isSelfExit.
- game-scene._onClientExit: only transition to MenuScene when isSelfExit;
peer exits render a toast "<nickname> left the room" instead.
- menu-ui.js module CLIENT_EXIT handler: only showLobby() when isSelfExit.
Server: the client fix alone leaves a new hole — after a peer leaves a
finished PVP room, the remaining player sits in gameoverState with a
game-over modal and two buttons. "Play Again" would try to restart a
PVP game with only one human; "Leave" still works. To close this hole
cleanly:
- state/waiting.go: add kickStaleRoomPeers helper. After a leaveRoom
in gameoverState, if the room is a PVP room with < 2 remaining human
players it's unplayable — push a synthetic Request_ClientExit onto
each remaining peer's CmdCh. Their gameoverState goroutine wakes up,
processes the synthetic exit, and returns StateHome in lockstep.
- state/gameover.go: call kickStaleRoomPeers after leaveRoom in the
ClientExit case.
Tests:
- Rename TestFlow_CreateRoomAfterOpponentForfeit →
TestFlow_OpponentExit_KicksPeerFromGameover and rewrite to assert
the auto-kick behavior: black leaves → white's gameoverState must
return StateHome WITHOUT any test-driven CmdCh push. Then both
players can create fresh rooms.
Full suite + client build green.
Defensive cleanup to address the reported symptom "can not play PVE
after PVP". Server-side flow tests pass in every permutation, so the
residue must be in the client scene lifecycle.
game-state-service:
- Reset isSpectating on GAME_STARTING, not just on CLIENT_EXIT. If a
prior watch session ever left the flag set (e.g., the user left via
a path that didn't emit CLIENT_EXIT), a fresh game-starting signal
would incorrectly treat the new player as a spectator and block
clicks via isMyTurn() returning false.
game-scene._cleanup:
- Explicitly drop Phaser input listeners (pointerdown, pointermove).
Phaser's scene shutdown is supposed to tear down the input plugin,
but an explicit off() makes the cleanup obvious and robust against
any lifecycle quirk in scene restart.
- Null out this.board / this.stones / this.lastMarker / this.hoverGraphic
/ this.hoverPos so the next create() starts from a known-clean state,
and late-firing events can't accidentally dereference stale Phaser
game objects that the scene already destroyed.
No functional change to the happy path — just defensive teardown that
makes a scene restart observably idempotent.
npm run build green.
The "Start Game" button in the waiting room is gone — as soon as a
second player joins a PVP room, the server flips to Playing and both
clients transition into the game in lockstep.
Server:
- Proto: remove GameStartingRequest message + oneof field (now unused).
- state/home.go handleJoinRoom: after a successful join that fills the
room, call assignColors, set Status=Playing + CurrentTurn=Black,
close StartCh, broadcast GameStartingResponse, return StateGamePvp
for the joining player. If still only one player, return StateWaiting
as before.
- state/waiting.go: collapse ownerWait + joinerWait into a single
unified loop. Both roles just select on StartCh (auto-start signal)
and CmdCh (for ClientExit). No more GameStartingRequest handling or
PlayerCount checks.
- network/dispatch.go: drop Request_GameStarting from the stateful
routing list.
Client:
- connection-service.js: remove sendGameStarting() helper.
- menu-ui-rooms.js showWaiting: drop the isOwner parameter + Start Game
button + owner/joiner branching. Both views show the same passive
'Waiting for opponent...' message that flips to 'Opponent joined:
<name> - starting game...' when the second player arrives.
- menu-scene.js: update _onRoomCreateSuccess + _onRoomJoinSuccess to
call the simpler showWaiting(ownerNickname, playerCount, onLeave)
signature.
Tests:
- Remove TestWaitingOwnerGameStartingRequiresFullRoom (obsolete).
- Rewrite TestWaitingOwnerStartsWhenFull into TestWaitingOwner
TransitionsOnStartCh: simulate handleJoinRoom closing StartCh,
verify owner transitions to StateGamePvp.
- Add TestFlow_JoinAutoStartsGame: end-to-end drive where owner is in
waitingState, joiner sends JoinRoomRequest from home, and both
goroutines must land in StateGamePvp with colors assigned and
GameStartingResponse broadcast.
Regen Go + JS proto stubs. go vet + go test ./... green.
npm --prefix client run build green.
Two stacked bugs in the client's room-creation path:
1. menu-scene._onRoomCreateSuccess read `data.ownerNickname` but the
proto field is `room_owner` (pbjs camelCase: `roomOwner`). The
waiting room showed an empty owner name after clicking Create Room.
2. game-state-service had no handler at all for ROOM_CREATE_SUCCESS.
After creating a room, gameState.roomId stayed at whatever value
the previous CLIENT_EXIT left (null). The waiting room panel
displayed "Room ID: " (empty) until another player joined and
triggered ROOM_JOIN_SUCCESS. Also broke any code path that relies
on roomId between Create and Join.
Fix:
- menu-scene: read data.roomOwner (the actual proto field name);
updated JSDoc to document all three proto fields (id, roomOwner,
roomType).
- game-state-service: add a ROOM_CREATE_SUCCESS listener that sets
roomId from data.id (the proto field is `id`, not `roomId`, for
RoomCreateSuccessResponse).
Server-side flow tests added in a separate commit (a350636) prove
the server correctly allows create-after-pvp in every permutation
(direct leave, rematch→leave, opponent forfeit). The reported "can
not create room after pvp" symptom matches the field-name bug above:
the waiting room did render, but with blank identifying info, so it
was easy to mistake for "nothing happened".
npm run build green.
Bug: after clicking "Leave" on the game-over modal, the client landed
on the nickname entry screen and got stuck — typing a nickname produced
no response for up to 90 seconds.
Root cause chain:
1. Server handleClientExit (stateless) closed SendCh and nilled it but
did not close the WS connection. Writer goroutine drained + exited
without closing the conn; reader stayed blocked on ReadMessage; state
machine stayed blocked on CmdCh. Zombie session.
2. Any subsequent player.Send() returned nil (SendCh was nil), silently
dropping responses. The setNickname reply never reached the client.
3. Client only unstuck when reader's 90 s readDeadline fired, finally
closing the WS and triggering the auto-reconnect path.
4. Client MenuScene.create() always called showNicknameScreen() without
checking gameState.nickname, so even after the reconnect the user
had to re-type their name.
Fix: "exit" now means "leave current room, return to home lobby" —
not "terminate WS session".
Server:
- dispatch.go: move Request_ClientExit from stateless to stateful path.
- handlers_stateless.go: delete handleClientExit entirely.
- waiting.go leaveRoom: broadcast ClientExitResponse via broadcastResponse
BEFORE removing the player, so the exiting player also receives their
own exit confirmation. Removes duplicated self-notification logic.
- waiting/gamePvp/gamePve/gameover/watching: on ClientExitRequest, call
leaveRoom + return consts.StateHome (was return 0, ErrClientExit).
- home.go: on ClientExitRequest, send bare ClientExitResponse and stay
in home (no room to leave).
- Update 4 state tests that asserted ErrClientExit → now assert StateHome.
- Rename TestWatching_ClientExitReturnsErrClientExit → ReturnsHome.
Client:
- menu-scene.js create(): if gameState.nickname is set, skip nickname
screen and call showLobby() directly. Otherwise showNicknameScreen().
- game-scene.js _onClientExit: drop the explicit showLobby() call; let
MenuScene.create() decide the panel based on nickname state. Remove
now-unused menu-ui showLobby import.
Result: click Leave → server sends ClientExitResponse, state machine
transitions to StateHome, WS stays open, client transitions to
MenuScene → sees gameState.nickname is set → goes straight to lobby.
No reconnect, no re-typing, no 90-second stall.
go vet + go test ./... green. npm run build green.
Protocol type safety
- Add Piece, GameResult, RoomType, RoomStatus proto3 enums; replace
unsafe string fields in GameMoveSuccessResponse, GameOverResponse,
RoomCreateSuccessResponse, RoomSummary, WatchGameSuccessResponse.
- Go compiler now rejects typos like "PVP" or "BLACK". protobufjs
toJSON() serializes enums as UPPERCASE names, so existing client
comparisons keep working.
- Fixes turn-change bug where lowercase "black"/"white" server strings
never matched client 'BLACK'/'WHITE' checks, freezing currentTurn
and blocking the non-starting player's clicks.
- Regenerate Go + JS stubs.
Room-join bug fix
- home.go handleJoinRoom now broadcasts RoomJoinSuccessResponse to all
players in the room (owner + joiner), not just the joiner. Owner
can see the player count flip to 2/2 and the Start Game button
enables. Remove superseded broadcastJoined + GameReadyResponse path.
- client menu-scene _onRoomJoinSuccess: read correct proto camelCase
field names (roomOwner, roomClientCount, clientNickname).
Dead code removal
- Delete GameReadyRequest/Response proto messages entirely; leaveRoom
notifies via ClientExitResponse.
- Delete server/network/{network,wss}.go empty stubs.
- Delete server/pkg/consts/ unused re-export package.
- Slim server/consts/const.go from 117 LOC to 24: drop legacy TCP
constants, duplicated RoomType/RoomStatus enums, Error/NewErr types,
StateJoin/StateCreate=0 type-unsafe aliases, unused GameTypes maps.
- database/player.go: remove unused IP, Mode, Type, Amount, legacy
private state field.
- Fix gopls findings: unused forPlayer, gameOverOnce, runAIMove player,
handleGameReset player params.
go vet + go test ./... green, npm run build green.
menu-ui.js exceeded 200-line limit. Extract room-list, PVE difficulty panel,
and waiting-room into menu-ui-rooms.js. menu-ui.js re-exports showRoomList
and showWaiting so menu-scene.js import paths are unchanged.
menu-ui.js: nickname screen, lobby, PVP/PVE submenus, room list table,
role-aware showWaiting() — owner gets Start Game button (disabled until
playerCount=2); joiner gets passive wait message. Returns update() handle
for live ROOM_JOIN_SUCCESS pushes from menu-scene. All user strings set
via textContent for XSS safety.
game-ui.js: game HUD with turn indicator dots, scrollable move history,
showGameOver modal with Play Again (sendGameReset) and Leave buttons,
showToast auto-dismissing after 2s into #toast-container. Error toasts
wired for all GAME_MOVE_* and spectator-cannot-act events.
Replace phase-09 stubs with real Phaser.GameObjects.Graphics implementations.
Board draws wood-textured 15x15 grid with star points and coordinate labels.
Stone renders gradient black/white circle with 180ms Back.easeOut drop tween.
createLastMoveMarker draws a red filled circle at the last-played intersection.
menu-scene.js wired for live waiting-room updates and role-aware showWaiting.
- index.html: dark shell with #game-container (Phaser canvas parent),
#ui-overlay containing #menu-root, #game-hud-root, #toast-container
- vite.config.js: port 5173, strictPort, sourcemap build, no GitHub Pages base
- src/main.js: instantiates Phaser.Game from gameConfig
- src/config/game-config.js: 800x800 FIT canvas, parent=game-container, scene list
- src/config/protocol-constants.js: ClientEventCode enum aligned to response.proto
oneofs; adds SPECTATOR_CANNOT_ACT, renames GAME_WATCH_SUCCESSFUL to
WATCH_GAME_SUCCESS, drops CLIENT_KICK (no proto case)
- src/scenes/boot-scene.js|menu-scene.js|game-scene.js: minimal stubs for Phaser
scene registry; phase-09 replaces them with real implementations
Adds Phaser+Vite+protobufjs package.json with proto:gen script, installs
dependencies, and commits generated protocol.js and protocol.d.ts so
builds work without requiring protoc or pbjs on every dev box.
Also adds node_modules/ to root .gitignore.
Import source files from ratel-online organization repos into monorepo
structure for gomoku game development. Update README with project
structure and credits for original authors.