Adds Direction enum and abstracts the slideUp, slideDown, slideLeft, and slideRight methods.

This commit is contained in:
2024-07-01 11:31:31 -07:00
parent cb914f53df
commit fa41124102

61
main.js
View File

@@ -1,3 +1,11 @@
const Direction = Object.freeze({
Up: { name: "up" },
Right: { name: "right" },
Down: { name: "down" },
Left: { name: "left" },
get values() { return Object.values(Direction); },
fromName(name) { return this.values.filter(i=>i.name == name)[0] || null; },
});
const globals = { const globals = {
grid: null, grid: null,
}; };
@@ -18,48 +26,45 @@ const btnRedraw_onClick = () => {
redraw(globals.grid); redraw(globals.grid);
} }
const btnUp_onClick = () => { const slideInDirection = (grid, direction) => {
const grid = globals.grid; switch(direction) {
if (slideUp(grid)) { case Direction.Up:
return slideUp(grid);
case Direction.Down:
return slideDown(grid);
case Direction.Left:
return slideLeft(grid);
case Direction.Right:
return slideRight(grid);
default:
return false;
}
}
const playMove = (grid, direction) => {
if (slideInDirection(grid, direction)) {
addRandomTile(); addRandomTile();
redraw(grid) redraw(grid)
} else { } else {
alert('Unable to slide Up.'); alert(`Unable to slide ${direction.name}.`);
} }
checkForEnd(grid); checkForEnd(grid);
} }
const btnUp_onClick = () => {
playMove(globals.grid, Direction.Up);
}
const btnDown_onClick = () => { const btnDown_onClick = () => {
const grid = globals.grid; playMove(globals.grid, Direction.Down);
if (slideDown(grid)) {
addRandomTile();
redraw(grid)
} else {
alert('Unable to slide Down.');
}
checkForEnd(grid);
} }
const btnLeft_onClick = () => { const btnLeft_onClick = () => {
const grid = globals.grid; playMove(globals.grid, Direction.Left);
if (slideLeft(grid)) {
addRandomTile();
redraw(grid)
} else {
alert('Unable to slide Left.');
}
checkForEnd(grid);
} }
const btnRight_onClick = () => { const btnRight_onClick = () => {
const grid = globals.grid; playMove(globals.grid, Direction.Right);
if (slideRight(grid)) {
addRandomTile();
redraw(grid)
} else {
alert('Unable to slide Right.');
}
checkForEnd(grid);
} }
const drawGrid = (grid, element) => { const drawGrid = (grid, element) => {