diff --git a/main.js b/main.js index 38a6b9a..0cd0e63 100644 --- a/main.js +++ b/main.js @@ -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 = { grid: null, }; @@ -18,48 +26,45 @@ const btnRedraw_onClick = () => { redraw(globals.grid); } -const btnUp_onClick = () => { - const grid = globals.grid; - if (slideUp(grid)) { +const slideInDirection = (grid, direction) => { + switch(direction) { + 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(); redraw(grid) } else { - alert('Unable to slide Up.'); + alert(`Unable to slide ${direction.name}.`); } checkForEnd(grid); } +const btnUp_onClick = () => { + playMove(globals.grid, Direction.Up); +} + const btnDown_onClick = () => { - const grid = globals.grid; - if (slideDown(grid)) { - addRandomTile(); - redraw(grid) - } else { - alert('Unable to slide Down.'); - } - checkForEnd(grid); + playMove(globals.grid, Direction.Down); } const btnLeft_onClick = () => { - const grid = globals.grid; - if (slideLeft(grid)) { - addRandomTile(); - redraw(grid) - } else { - alert('Unable to slide Left.'); - } - checkForEnd(grid); + playMove(globals.grid, Direction.Left); } const btnRight_onClick = () => { - const grid = globals.grid; - if (slideRight(grid)) { - addRandomTile(); - redraw(grid) - } else { - alert('Unable to slide Right.'); - } - checkForEnd(grid); + playMove(globals.grid, Direction.Right); } const drawGrid = (grid, element) => {