Moves assigning event listeners into the js code.

This commit is contained in:
2024-07-03 00:49:47 -07:00
parent d2c8566f9c
commit 6e23a1358b
2 changed files with 91 additions and 38 deletions

117
main.js
View File

@@ -1,3 +1,5 @@
let gameBoard;
const Direction = Object.freeze({
Up: { name: "up" },
Right: { name: "right" },
@@ -7,24 +9,89 @@ const Direction = Object.freeze({
fromName(name) { return this.values.filter(i=>i.name == name)[0] || null; },
});
let gameBoard;
const setup = () => {
document.addEventListener('keydown', ev => {
switch (ev.key) {
case 'w':
case 'ArrowUp':
playMove(gameBoard, Direction.Up);
break;
case 'a':
case 'ArrowLeft':
playMove(gameBoard, Direction.Left);
break;
case 's':
case 'ArrowDown':
playMove(gameBoard, Direction.Down);
break;
case 'd':
case 'ArrowRight':
playMove(gameBoard, Direction.Right);
break;
default:
console.log(ev.key);
break;
}
});
const btnStart_onClick = () => {
gameBoard = new GameBoard(new Grid(4, 4));
// gameBoard = new GameBoard(
// makeDevGrid([ // can't slide down or left
// [2,1,3,4],
// [3,5,7,9],
// [1,2,1,2],
// [3,4,5,0],
// ])
// );
gameBoard.addRandomTile();
redraw(gameBoard);
binding = new Binding(['btnStart', 'btnUp', 'btnRight', 'btnDown', 'btnLeft', 'btnRedraw']);
const start = () => {
gameBoard = new GameBoard(new Grid(4, 4));
// gameBoard = new GameBoard(
// makeDevGrid([ // can't slide down or left
// [2,1,3,4],
// [3,5,7,9],
// [1,2,1,2],
// [3,4,5,0],
// ])
// );
gameBoard.addRandomTile();
redraw(gameBoard);
};
binding.btnStart.on('click', start);
binding.btnUp.on('click', () => {
playMove(gameBoard, Direction.Up);
});
binding.btnRight.on('click', () => {
playMove(gameBoard, Direction.Right);
});
binding.btnDown.on('click', () => {
playMove(gameBoard, Direction.Down);
});
binding.btnLeft.on('click', () => {
playMove(gameBoard, Direction.Left);
});
binding.btnRedraw.on('click', () => {
redraw(gameBoard);
});
start();
}
const btnRedraw_onClick = () => {
redraw(gameBoard);
class ElementBinding {
#element;
constructor (element) {
this.#element = element;
}
on(event, action) {
// TODO(tom): Test multiple bindings.
if (this.#element != null) {
this.#element.addEventListener(event, action);
}
}
}
class Binding {
constructor(elementIds) {
elementIds.forEach(i =>
this[i] = new ElementBinding(document.getElementById(i))
);
}
}
// TODO(tom): This should take GameBoard instead of Grid or be moved into GameBoard.
@@ -38,22 +105,6 @@ const playMove = (gameBoard, direction) => {
checkForEnd(gameBoard);
}
const btnUp_onClick = () => {
playMove(gameBoard, Direction.Up);
}
const btnDown_onClick = () => {
playMove(gameBoard, Direction.Down);
}
const btnLeft_onClick = () => {
playMove(gameBoard, Direction.Left);
}
const btnRight_onClick = () => {
playMove(gameBoard, Direction.Right);
}
const redraw = (gameBoard) => {
const element = document.getElementById('output');
@@ -414,4 +465,6 @@ class Settings {
getVector;
getLength;
swap;
};
};
setup();