Skip to content

Instantly share code, notes, and snippets.

@slior

slior/board.js Secret

Created November 2, 2020 09:51
Show Gist options
  • Save slior/7b765c8149df4ae42b9015ed11f9c1b8 to your computer and use it in GitHub Desktop.
Save slior/7b765c8149df4ae42b9015ed11f9c1b8 to your computer and use it in GitHub Desktop.
Mancala (25763d3b47542b934ab303bd7aaf42b2d2efe7f2): connecting UI to changing board state
class Board
{
...
playCell(cell)
{
range(1,this.stonesIn(cell))
.map(steps => this.cellFrom(cell,steps))
.forEach(c => this.addStoneTo(c))
this.setCellStoneCount(cell,0);
}
/**
* Calculate a target cell, given a new cell, walking counter-clockwise a number of steps as given
* @param {number} cell The cell we're starting from
* @param {number} steps The number of steps to take from this cell, counter-clockwise, to reach the new cell
*/
cellFrom(cell,steps)
{
//walk backwards, and if we pass cell 0, add the number of cells again.
return cell - steps + (cell < steps ? this.totalCellCount() : 0);
}
addStoneTo(cell)
{
this.setCellStoneCount(cell,this.stonesIn(cell)+1)
}
}
function drawBoardState(cnvs,board,boardClickHandler)
{
...
function drawOrRemove(boardCell,stoneCount,drawFunc)
{
if (stoneCount > 0)
{
removeDrawingAt(boardCell);
drawFunc(boardCell,stoneCount);
uiObjAt(boardCell).ifPresent(uiObj => {uiObj.on('mousedown', _ => { boardClickHandler(boardCell); })})
}
else removeDrawingAt(boardCell);
}
}
var canvas = None;
function initGame(cnvsELID)
{
canvas = maybe(initCanvas(cnvsELID));
canvas.ifPresent(cnvs => {
initDrawingElements(board.totalCellCount());
drawBoard(cnvs,CELL_COUNT);
drawBoardState(cnvs,board,boardClickHandler);
})
}
function boardClickHandler(boardCell)
{
board.playCell(boardCell);
canvas.ifPresent(cnvs => {
drawBoardState(cnvs,board,boardClickHandler)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment