testing
1,808 bytes View directory
1
import { fail } from '@sveltejs/kit';2
import type { Actions, PageServerLoad } from './$types';3
import { Game } from './game.ts';5
export const load = (({ cookies }) => {6
const game = new Game(cookies.get('sverdle'));8
return {9
/**10
* The player's guessed words so far11
*/12
guesses: game.guesses,14
/**15
* An array of strings like '__x_c' corresponding to the guesses, where 'x' means16
* an exact match, and 'c' means a close match (right letter, wrong place)17
*/18
answers: game.answers,20
/**21
* The correct answer, revealed if the game is over22
*/23
answer: game.answers.length >= 6 ? game.answer : null24
};25
}) satisfies PageServerLoad;27
export const actions = {28
/**29
* Modify game state in reaction to a keypress. If client-side JavaScript30
* is available, this will happen in the browser instead of here31
*/32
update: async ({ request, cookies }) => {33
const game = new Game(cookies.get('sverdle'));35
const data = await request.formData();36
const key = data.get('key');38
const i = game.answers.length;40
if (key === 'backspace') {41
game.guesses[i] = game.guesses[i].slice(0, -1);42
} else {43
game.guesses[i] += key;44
}46
cookies.set('sverdle', game.toString(), { path: '/' });47
},49
/**50
* Modify game state in reaction to a guessed word. This logic always runs on51
* the server, so that people can't cheat by peeking at the JavaScript52
*/53
enter: async ({ request, cookies }) => {54
const game = new Game(cookies.get('sverdle'));56
const data = await request.formData();57
const guess = data.getAll('guess') as string[];59
if (!game.enter(guess)) {60
return fail(400, { badGuess: true });61
}63
cookies.set('sverdle', game.toString(), { path: '/' });64
},66
restart: async ({ cookies }) => {67
cookies.delete('sverdle', { path: '/' });68
}69
} satisfies Actions;