feat(persist): salva stato su .segnapunti/state.json ad ogni azione
All'avvio il server carica lo stato dal file se esiste; ad ogni azione lo riscrive. Il riavvio del server riprende dall'ultimo punto salvato.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs'
|
||||
import { join, dirname } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { createInitialState } from './gameState.js'
|
||||
|
||||
const STATE_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '.segnapunti', 'state.json')
|
||||
|
||||
export function loadState() {
|
||||
try {
|
||||
if (existsSync(STATE_PATH)) {
|
||||
return JSON.parse(readFileSync(STATE_PATH, 'utf8'))
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Persist] Stato non leggibile, si riparte da zero:', err.message)
|
||||
}
|
||||
return createInitialState()
|
||||
}
|
||||
|
||||
export function saveState(state) {
|
||||
try {
|
||||
mkdirSync(dirname(STATE_PATH), { recursive: true })
|
||||
writeFileSync(STATE_PATH, JSON.stringify(state), 'utf8')
|
||||
} catch (err) {
|
||||
console.error('[Persist] Salvataggio fallito:', err.message)
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,9 @@ import { createInitialState, applyAction } from './gameState.js'
|
||||
* @param {WebSocketServer} wss - Istanza del server WebSocket.
|
||||
* @returns {Object} Oggetto con metodi di gestione dello stato.
|
||||
*/
|
||||
export function setupWebSocketHandler(wss) {
|
||||
export function setupWebSocketHandler(wss, options = {}) {
|
||||
// Stato globale della partita.
|
||||
let gameState = createInitialState()
|
||||
let gameState = options.initialState ?? createInitialState()
|
||||
|
||||
// Mappa dei ruoli associati ai client connessi.
|
||||
const clients = new Map() // ws -> { role: 'display' | 'controller' }
|
||||
@@ -100,6 +100,7 @@ export function setupWebSocketHandler(wss) {
|
||||
|
||||
// Propaga il nuovo stato a tutti i client connessi.
|
||||
broadcastState()
|
||||
options.onStateChange?.(gameState)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user