Skip to content

Instantly share code, notes, and snippets.

@dmitryshelomanov
Created May 31, 2019 12:27
Show Gist options
  • Save dmitryshelomanov/da1a032adae08d4b85f181f276dcecfe to your computer and use it in GitHub Desktop.
Save dmitryshelomanov/da1a032adae08d4b85f181f276dcecfe to your computer and use it in GitHub Desktop.
const LEFT = 65;
const RIGHT = 68;
function keyCodeToString(keyCode) {
const validSceme = [LEFT, RIGHT].includes(keyCode);
if (validSceme) {
const str = {
[LEFT]: "left",
[RIGHT]: "right"
};
return str[keyCode];
}
return undefined;
}
function drawCircle({ x, y }, ctx) {
ctx.arc(x, y, 100, 0, Math.PI * 2, false);
ctx.fillStyle = "red";
ctx.fill();
}
function main({ updater, renderer }) {
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const initialState = {
x: 0,
y: 0
};
let prevState = null;
const keyBoard = {};
function addListenersToKeyBoard() {
document.addEventListener("keydown", e => {
keyBoard[keyCodeToString(e.keyCode)] = true;
});
document.addEventListener("keyup", e => {
keyBoard[keyCodeToString(e.keyCode)] = false;
});
}
addListenersToKeyBoard();
function loop() {
prevState = updater(prevState || initialState, keyBoard);
renderer(prevState, ctx);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
}
main({
updater: (game, keyBoard) => {
if (keyBoard.left) {
return {
...game,
x: game.x - 1
};
}
if (keyBoard.right) {
return {
...game,
x: game.x + 1
};
}
return game;
},
renderer: ({ x, y }, ctx) => {
drawCircle({ x, y }, ctx);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment