Skip to content

Instantly share code, notes, and snippets.

@slior

slior/drawing.js Secret

Created November 1, 2020 21:30
Show Gist options
  • Save slior/dbc6ba718b37af086e36f74db74daad5 to your computer and use it in GitHub Desktop.
Save slior/dbc6ba718b37af086e36f74db74daad5 to your computer and use it in GitHub Desktop.
Mancala (384fd01d7acda41e1611dc2f7f34104660bdfc81): keeping track of ui objects
function drawBoardState(cnvs,board)
{
...
board.forAllCells(boardCell => {
let stonesInCell = board.stonesIn(boardCell);
switch (true)
{
case board.isPlayer1Home(boardCell) : drawOrRemove(boardCell,stonesInCell,(_,stoneCount) => { drawPlayer1Home(stoneCount); }); break;
case board.isPlayer2Home(boardCell) : drawOrRemove(boardCell,stonesInCell,(_,stoneCount) => { drawPlayer2Home(stoneCount); }); break;
case board.isPlayer1Cell(boardCell) || board.isPlayer2Cell(boardCell):
drawOrRemove(boardCell,stonesInCell,(boardCell,stoneCount) => { drawCell(boardCell,stoneCount); });
break;
default : ERR ("Invalid board cell when drawing state: " + boardCell); break;
}
})
function drawPlayer1Home(stoneCount)
{
rememberUIObj(board.player1Home(),
drawStones(stoneCount,
TOP_LEFT.x + CELL_SIZE / 2 - FONT_SIZE/2-MARGIN,
TOP_LEFT.y + CELL_SIZE * 1.5 - FONT_SIZE/2-MARGIN));
}
function drawPlayer2Home(stoneCount)
{
rememberUIObj(board.player2Home(),
drawStones(stoneCount,
/* left = */TOP_LEFT.x + boardWidthInCells(board.totalCellCount()) * CELL_SIZE - CELL_SIZE/2 - FONT_SIZE/2-MARGIN,
/* top = */TOP_LEFT.y + CELL_SIZE*1.5-FONT_SIZE/2-MARGIN));
}
function drawCell(boardCell,stoneCount)
{
switch (true)
{
case board.isPlayer1Cell(boardCell) :
... //calculating top,left
break;
case board.isPlayer2Cell(boardCell) :
... //calculating top,left
break;
default : ERR("Invalid board cell: must be either player 1 or player 2 cell");
}
rememberUIObj(boardCell,drawStones(stoneCount,TOP_LEFT.x + left,TOP_LEFT.y + top));
}
function drawOrRemove(boardCell,stoneCount,drawFunc)
{
if (stoneCount > 0)
{
drawFunc(boardCell,stoneCount);
uiObjAt(boardCell).ifPresent(uiObj => {uiObj.on('mousedown', _ => {dbg('Clicked cell: ' + boardCell + '!')})})
}
else removeDrawingAt(boardCell);
}
function removeDrawingAt(boardCell)
{
uiObjAt(boardCell).ifPresent(uiObj => {
cnvs.remove(uiObj);
forgetUIObj(boardCell);
});
}
function drawStones(stoneCount,left,top)
{
... //create canvas objects and add them to the canvas
//return the created canvas object
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment