Skip to content

Instantly share code, notes, and snippets.

@sc0ttj
Forked from xem/JSGameFramework2020.html
Created February 28, 2021 21:28
Show Gist options
  • Select an option

  • Save sc0ttj/076eb9c6a39c964ee16dcb7ec65dcc73 to your computer and use it in GitHub Desktop.

Select an option

Save sc0ttj/076eb9c6a39c964ee16dcb7ec65dcc73 to your computer and use it in GitHub Desktop.

Revisions

  1. @xem xem revised this gist Aug 13, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion JSGameFramework2020.html
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@
    <script>
    // initialize 2D canvas (c)
    // initialize game state (s)
    // initialize keys states (u,r,d,l for directions, q for all the keyboard)
    // initialize keys states (u,r,d,l for directions, k for all the keyboard)
    c=a.getContext`2d`,k=[u=r=d=l=s=0]

    // (initialize your global variables here)
  2. @xem xem revised this gist Aug 13, 2020. No changes.
  3. @xem xem created this gist May 5, 2020.
    43 changes: 43 additions & 0 deletions JSGameFramework2020.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    <body style=margin:0>
    <canvas id=a>
    <script>
    // initialize 2D canvas (c)
    // initialize game state (s)
    // initialize keys states (u,r,d,l for directions, q for all the keyboard)
    c=a.getContext`2d`,k=[u=r=d=l=s=0]

    // (initialize your global variables here)

    // update u,l,d,r globals when an arrow key/wasd/zqsd is pressed or released
    // update k[keyCode] if any other key is pressed/released
    onkeydown=onkeyup=e=>k[e.which]=self['lld*rlurdu'[e.which%32%17]]=e.type[5]

    // start game loop (60fps)
    // the canvas is cleared and adjusted to fullscreen at each frame
    // draw each screen in the switch's cases
    // in each screen, you can make key presses update the game state
    // ex: "press enter to open the menu" => `if(k[13])s=1;`
    setInterval(e=>{
    a.width=innerWidth,a.height=innerHeight;
    switch(s){
    case 0: // ex: draw title screen
    case 1: // ex: draw menu screen
    case 2: // ex: draw game board
    case 3: // ex: draw game over screen
    }
    },16)

    // handle click/touch events
    // globals x and y contain the pointer's coordinates
    // in each screen, you can make a click update the game state
    // ex: "game over if we click on the bottom half of the screen" => `if(y>h/2)s=3;`
    onclick=e=>{
    x=e.pageX;y=e.pageY;
    switch(s){
    case 0: // react to clicks on screen 0
    case 1: // react to clicks on screen 1
    case 2: // react to clicks on screen 2
    case 3: // react to clicks on screen 3
    }
    }
    </script>