/** Updates the HTML user interface to match the given game state. */
function updateHtml(grid, game) {
…
}
/** Drops a piece in the given column and updates the game state accordingly. */
async function dropPiece(grid, column) {
// TODO: Check if move is valid.
handleFetch(grid, `set/${column}`)
}
/** Fetches a game URL and updates the HTML using the new game state. */
async function handleFetch(grid, url) {
let response = await fetch(url)
let game = await response.json()
// Update the HTML view.
updateHtml(grid, game)
// TODO: fetch game state until it's our turn again.
}
/* Connects the game state to the HTML user interface. */
async function init() {
// Find the HTML game grid.
let grid = document.getElementsByTagName('c4-grid')[0]
// Fetch initial game state.
await handleFetch(grid, `game`)
// Install button click handlers for each button.
let index = 0
for (let button of grid.getElementsByTagName("button")) {
const column = index % 7
button.addEventListener("click", () => dropPiece(grid, column))
index++
}
}
init()