Skip to content

Instantly share code, notes, and snippets.

@dmitryshelomanov
Created May 31, 2019 12:27
Show Gist options
  • Select an option

  • Save dmitryshelomanov/da1a032adae08d4b85f181f276dcecfe to your computer and use it in GitHub Desktop.

Select an option

Save dmitryshelomanov/da1a032adae08d4b85f181f276dcecfe to your computer and use it in GitHub Desktop.

Revisions

  1. Shelomanov Dmitry created this gist May 31, 2019.
    78 changes: 78 additions & 0 deletions test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    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);
    }
    });