Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

Commit

Permalink
Assign a colour to each player in multiplayer
Browse files Browse the repository at this point in the history
  • Loading branch information
Nixinova committed May 14, 2021
1 parent 1467311 commit cb626f7
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 38 deletions.
2 changes: 1 addition & 1 deletion .eleventy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = function (cfg) {
const passThruPaths = ['_redirects', 'assets', 'scripts', 'styles'];
const passThruPaths = ['_redirects/', 'assets/', 'scripts/', 'styles/', 'favicon.ico'];
passThruPaths.forEach(file => cfg.addPassthroughCopy(file));
return {
passthroughFileCopy: true,
Expand Down
Binary file modified favicon.ico
Binary file not shown.
14 changes: 7 additions & 7 deletions lambda/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
Database typing: {'id': string, 'fen': string, 'lastMove': string}
*/
const faunadb = require('faunadb');
const Q = faunadb.query;
const { FAUNA_CLIENT_KEY } = process.env;
const Q = faunadb.query;
const client = new faunadb.Client({ secret: FAUNA_CLIENT_KEY });
const COLLECTION = 'Games';
const MAX_AGE = 7 * 86.4e6;
const MAX_AGE = 3 * 86.4e6;

const resolve = ret => console.log('Success:', ret);
const rejection = err => console.error('Error:', err.message);
const randomID = () => +Math.random().toString().substr(2, 5);

async function getDocs() {
console.debug('Retrieving documents');
Expand Down Expand Up @@ -38,10 +37,12 @@ async function pruneDocs() {
const docs = await getDocs();
let deletedDocs = [];
for (const doc of docs) {
deletedDocs.push(doc.data)
const invalidID = !/^\d{5}$/.test(doc.data.id);
const oldSession = new Date() - doc.ts > MAX_AGE;
if (invalidID || oldSession) deleteDoc(doc);
if (invalidID || oldSession) {
deleteDoc(doc);
deletedDocs.push(doc.data);
}
}
return { success: docs.length > 1, data: { deleted: deletedDocs } };
}
Expand All @@ -54,7 +55,6 @@ async function readData({ gameId }) {
}

async function sendData({ gameId, fen, lastMove }) {
if (!+gameId) gameId = randomID();
const data = { id: gameId, fen, lastMove };
console.debug('Sending game data', fen, 'to ID', gameId);
let success, type;
Expand Down Expand Up @@ -90,7 +90,7 @@ exports.handler = async function (event, context, callback) {
prune: async () => await pruneDocs(),
read: async () => await readData(input),
send: async () => await sendData(input),
version: 0.14,
version: async () => await 0.15,
};
funcs.help = async () => ({ commands: Object.keys(funcs), version: funcs.version() });
if (!funcs[type]) {
Expand Down
29 changes: 13 additions & 16 deletions scripts/play/board.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,25 +124,22 @@ const resetCell = cell => getCell(cell).innerHTML = '<img src="/assets/transpare

function toggleRules(button) {
hasRules = !hasRules;
button.classList.toggle("enabled");
button.classList.toggle("disabled");
['enabled', 'disabled'].forEach(c => button.classList.toggle(c));
currentTurn = invertColour(currentTurn);
}

function flipBoard(force) {
const elem = $('body');
if (force) {
elem.classList.toggle('rotate');
elem.classList.toggle('norotate');
}
else {
if (currentTurn === 'black') {
elem.classList.add('rotate');
elem.classList.remove('norotate');
} else {
elem.classList.remove('rotate');
elem.classList.add('norotate');
}
function flipBoard() {
['rotate', 'norotate'].forEach(c => document.body.classList.toggle(c));
}

function alignBoard() {
const classes = document.body.classList;
if (currentTurn === 'black') {
classes.add('rotate');
classes.remove('norotate');
} else {
classes.remove('rotate');
classes.add('norotate');
}
}

Expand Down
7 changes: 4 additions & 3 deletions scripts/play/game-cycle.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
function hasClicked(cell) {
if (!ingame) return;
if (!window.ingame) return;
if (window.multiplayer && window.currentTurn !== window.playerTurn) return;

const $cell = $.id('piece' + cell);
const cellClasses = $cell ? Array.from($cell.classList) : [];
Expand Down Expand Up @@ -134,7 +135,7 @@ function hasClicked(cell) {
// switch turn
if (hasRules) {
currentTurn = invertColour(currentTurn);
if (autoFlip) flipBoard();
if (autoFlip) alignBoard();
}

// send to server
Expand Down Expand Up @@ -207,7 +208,7 @@ function undoLastMove() {
totalMoves--;
currentTurn = invertColour(currentTurn);
logPoints();
if (autoFlip) flipBoard();
if (autoFlip) alignBoard();
$$(`[data-move="${totalMoves}"]`).forEach(elem => {
if (elem.parentNode) elem.parentNode.innerHTML = '';
});
Expand Down
3 changes: 2 additions & 1 deletion scripts/play/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ function run() {
window.lastMove = { start: null, end: null };
window.selectedCell = null;
window.currentTurn = 'white';
window.playerTurn = 'white';
window.promotionPiece = 'queen';
window.kingCell = { w: 'E1', b: 'E8' };
window.castling = { w: { k: true, q: true }, b: { k: true, q: true } };
Expand All @@ -35,7 +36,7 @@ function run() {
window.hasRules = gameOptions.rules;
window.gameId = gameOptions.gamecode;

flipBoard(gameOptions.botColour === 'white');
alignBoard();

let urlFen = getFenFromURL();
if (urlFen) createBoardFromFen(urlFen);
Expand Down
34 changes: 24 additions & 10 deletions scripts/play/online.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,54 @@ const READ_INTERVAL = 2.5 * sec;
let lastReceivedFen, lastSentFen;
let idleTime = 0;

async function readDB() {
const resp = await fetch(`${apiUrl}?type=read&gameId=${gameId}`);
async function getGameData() {
const resp = await fetch(`${apiUrl}?type=read&gameId=${window.gameId}`);
const json = await resp.json();
const { fen = createFen(), lastMove } = json.output.data;
return json.output.data;
}

async function readDB() {
const { fen = createFen(), lastMove } = await getGameData();
if (fen === lastReceivedFen) return;
lastReceivedFen = fen;
console.debug(`Retrieved FEN data for game ID ${gameId}: ${fen}.`);
console.debug(`Retrieved FEN data for game ID ${window.gameId}: ${fen}.`);
createBoardFromFen(fen);
if (lastMove) {
lastMove.split('-').forEach(cell => $('#' + cell).classList.add('last-move'));
lastMove.split('-').forEach(cell => $.id(cell).classList.add('last-move'));
$('#log').innerHTML += lastMove.split('-')[1];
}
}

async function sendDB() {
console.debug(`Attempting to send data to game ID ${gameId}...`);
console.debug(`Attempting to send data to game ID ${window.gameId}...`);
const fen = createFen();
if (fen === lastSentFen) {
console.debug(`No new FEN data to send for game ID ${gameId}.`);
console.debug(`No new FEN data to send for game ID ${window.gameId}.`);
return;
}
lastSentFen = fen;
idleTime = 0;
let queryParams = [
'type=send',
`gameId=${encodeURIComponent(gameId)}`,
`gameId=${encodeURIComponent(window.gameId)}`,
`fen=${encodeURIComponent(fen)}`,
`lastMove=${window.lastMove.start}-${window.lastMove.end}`,
];
await fetch(`${apiUrl}?${queryParams.join('&')}`);
console.debug(`Sent FEN data for game ID ${gameId}: ${fen}.`);
console.debug(`Sent FEN data for game ID ${window.gameId}: ${fen}.`);
}

setInterval(() => {
async function init() {
if (!window.multiplayer) return;
const data = await getGameData();
// Assign colour to player: white if P1, black if P2
window.playerTurn = Object.is(data, {}) ? 'white' : 'black';
if (window.playerTurn === 'black') flipBoard();
}

document.addEventListener('DOMContentLoaded', init);

setInterval(function () {
if (!gameOptions.multiplayer) return;
if (idleTime > TIMEOUT_AGE) {
alert('Session timed out');
Expand Down

0 comments on commit cb626f7

Please sign in to comment.