libreinternet.club/www/tictactoe.js
2026-05-15 13:52:30 -06:00

74 lines
1.5 KiB
JavaScript

import { url } from "./editor.js";
const gameurl = `${url}ticktactoegamestate`;
const board = [
tictactoebutton0,
tictactoebutton1,
tictactoebutton2,
tictactoebutton3,
tictactoebutton4,
tictactoebutton5,
tictactoebutton6,
tictactoebutton7,
tictactoebutton8,
];
let state = "";
state = await reload();
function display_state(state) {
for (const cell of board) {
cell.innerText = "";
}
let x_to_move = true;
for (const action of state) {
board[Number(action)].innerText = x_to_move ? "X" : "O";
x_to_move = !x_to_move;
}
}
async function fetch_gamestate() {
const response = await fetch(new Request(gameurl));
if (response.status == 200) {
return response.text();
}
return "";
}
async function push_gamestate(state) {
const response = await fetch(
new Request(gameurl, { method: "PUT", body: state }),
);
if (response.status < 200 || response.status > 299) {
throw new Error(`Returned status code ${response.status}`);
}
}
async function play_move(cell) {
const index = board.indexOf(cell);
if (index == -1) {
return;
}
const next_state = state + index;
await push_gamestate(next_state);
state = next_state;
display_state(state);
}
async function reload() {
state = await fetch_gamestate();
display_state(state);
return state;
}
async function reset() {
await push_gamestate("");
state = "";
display_state(state);
}
globalThis.tictactoe = {
play_move: play_move,
reload: reload,
reset: reset,
};