Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flappy bird in 205 bytes (improved!)
<body onload=z=c.getContext`2d`,setInterval(`c.width=W=150,Y<W&&P<Y&Y<P+E|9<p?z.fillText(S++${Y=`,9,9|z.fillRect(p`}*0,Y-=--M${Y+Y},P+E,9,W),P))):p=M=Y=S=6,p=p-6||(P=S%E,W)`,E=49) onclick=M=9><canvas id=c>
@ParkerM
Copy link

ParkerM commented Nov 30, 2020

How does it know that c is canvas indeed?

Here's a succinct explanation that mentions this from the spec:

The HTML5 standard specifies that the window object must have a property key whose value is elem if...

  • there is exactly one DOM element elem whose property id has the value key.
  • there is exactly one DOM element elem whose property name has the value key. elem’s tag must be one of: a, applet, area, embed, form, frame, frameset, iframe, img, object.

So by the first bullet there, <canvas id=c> creates a property window.c referencing the canvas element, which places it in the global scope by default. You can verify this by replacing references to c with this.c since this === window at the top level.

@SylveonBottle
Copy link

SylveonBottle commented Nov 30, 2020

Making decoding this extra credit for my 201 Programming Languages class. Thanks for the great gist

"Decode this and tell us what it does"
Answer: It's flappy bird

@spawluk
Copy link

spawluk commented Nov 30, 2020

@ParkerM I was looking for that. Thank you a lot :)

@MDeiml
Copy link

MDeiml commented Nov 30, 2020

Maybe it would be possible to make this even shorter by using SVGs instead of canvas. For example this is enough to draw a whole example scene.

<svg><path d="M0 75H9M99 0V60M99 99V999" stroke=tan stroke-width=9>

This also has the added benifit, that we could use onload on the svg and don't need a body

@farhadnowzari
Copy link

farhadnowzari commented Nov 30, 2020

Thats amazing, I'm speechless

@kres0345
Copy link

kres0345 commented Nov 30, 2020

@ParkerM how come document.getElementById is a thing then?

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

I've managed to get a SVG solution at 227 characters:

<svg onload="Y=G=T=0;W=99;setInterval('T%W?p.setAttribute(`d`,`M${W-T%W} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0`):Y>G&&Y<G+75?G=75*Math.random():V=Y=T=0;Y-=V-=.03;t.innerHTML=T++',9)"onclick=V=2><path id=p /><text id=t y=11>

https://jsfiddle.net/7wz02hdr/2/

Among other things, I tried making the wall X coordinate time-based (W-T%W) to remove a variable. That might be useful in the other solution as well. This means the possible collision with the wall happens when T%W==0 which also shortens the ternary conditions. It also makes resetting after a loss trivial V=Y=T=0.

It is possible this may beat the canvas solution with some optimization.
Ideas for optimization:

  1. Drawing player/walls using the path stroke instead of enclosed shapes may save characters, but at the cost of including path attributes stroke=red stroke-width=9
  2. Re-arranging order of drawn shapes and/or coordinates within shapes (could perhaps make the two walls identical except starting Y and store in a variable)
  3. May be able to get away with bitwise and/or in places
  4. Getting rid of Math.random() (I had a hard time making new Date%75 appear random enough)
  5. Figuring out how to make a more concise acceleration be playable, currently 3 characters .03

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

Bitwise and does save a character (now 226):

<svg onload="Y=G=T=0;W=99;setInterval('T%W?p.setAttribute(`d`,`M${W-T%W} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0`):Y>G&Y<G+75?G=75*Math.random():V=Y=T=0;Y-=V-=.03;t.innerHTML=T++',9)"onclick=V=2><path id=p /><text id=t y=11>

https://jsfiddle.net/usgLxtcn/

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

Reached 212 characters on the SVG version by realizing I could set the innerHTML of this in the SVG to avoid needing to provide IDs for the inner path and text, as well as avoiding having to call setAttribute:

<svg id=c onload="Y=G=T=0;W=99;setInterval('T%W?0:Y>G&Y<G+75?G=75*Math.random():V=Y=T=0;Y-=V-=.03;c.innerHTML=`<path d=\'M${W-T%W} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0\' /><text y=11>${T++}`',9)"onclick=V=2>

https://jsfiddle.net/ek4g0rb2/1/

@uninhm
Copy link

uninhm commented Dec 1, 2020

do the mobile browsers even support data URI's? (e.g. data:text/html,)

Yes

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

Since the other solution does it, I guess I can change the SVG one to use new Date%N instead of N*Math.random() to save another 5 bytes.
This brings the SVG version so 207 bytes (2 bytes larger than the canvas version):

<svg id=c onload="Y=G=T=0;W=99;setInterval('T%W?0:Y>G&Y<G+75?G=new Date%75:V=Y=T=0;Y-=V-=.03;c.innerHTML=`<path d=\'M${W-T%W} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0\' /><text y=11>${T++}`',9)"onclick=V=2>

https://jsfiddle.net/nt12Lewp/

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

SVG version is now 205 bytes (tied with canvas version):

<svg id=c onload="Y=G=T=0;setInterval('T%99?0:Y>G&Y<G+75?G=new Date%75:V=Y=T=0;Y-=V-=.03;c.innerHTML=`<path d=\'M${99-T%99} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0\' /><text y=11>${T++}`',9)"onclick=V=2>

https://jsfiddle.net/nt12Lewp/1/

I inlined the width variable W, saving 2 characters.

@liamstrilchuk
Copy link

liamstrilchuk commented Dec 1, 2020

@jmromrell It can get down to 198 if you change new Date%N to T%75, which makes it not completely random now, but close enough

Also set the text y position to 9, and remove a space that's not needed at the end of the path element

https://jsfiddle.net/3fjaL0k6/

@liamstrilchuk
Copy link

liamstrilchuk commented Dec 1, 2020

@jmromrell and 196 if you inline the W variable like you said.

https://jsfiddle.net/7qL2zd6x/

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

I don't like leaving the text obscured. I personally feel it is a buggy implementation of flappy bird if the score is off the screen, and is worth eating a character for. I think the other changes are great though.

197 bytes if the score is left on screen:

<svg id=c onload="Y=G=T=0;setInterval('T%99?0:Y>G&Y<G+75?G=T%75:V=Y=T=0;Y-=V-=.04;c.innerHTML=`<path d=\'M${99-T%99} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0\'/><text y=11>${T++}`',9)"onclick=V=2>

https://jsfiddle.net/z3bmtg5u/

@gullyn
Copy link
Author

gullyn commented Dec 1, 2020

@jmromrell might as well make the text y 13, so it is fully on the screen, unfortunately it's no longer dataurl safe now

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

Reached 195 bytes by concatenating the score to the string instead of templating:

<svg id=c onload="Y=G=T=0;setInterval('T%99?0:Y>G&Y<G+75?G=T%75:V=Y=T=0;Y-=V-=.04;c.innerHTML=`<path d=\'M${99-T%99} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0\'/><text y=11>`+T++',9)"onclick=V=2>

https://jsfiddle.net/z3bmtg5u/1/

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

I'm fine with text at y=13. Y=11 was on-screen for me. I guess default font is platform dependent. 😄
Didn't realize we lost dataurl compatibility along the way. Wonder what broke that. :/

@gullyn
Copy link
Author

gullyn commented Dec 1, 2020

@jmromrell I'm guessing either the slashes or the backslashes. The website I looked at said & is not dataurl safe and we need to encode it, not sure how we got away with that

@pratyushmittal
Copy link

pratyushmittal commented Dec 1, 2020

Can someone please post an unminified version too? Would love to read and understand the brilliant algorithm.

@jmromrell
Copy link

jmromrell commented Dec 1, 2020

@pratyushmittal Happy to explain!

The SVG solution actually fails to run if you put line breaks in it since most of it is a string, but I'll add them anyways for explanation purposes:

<svg id=c                             //Give the SVG an ID for reference later
     onload="Y=G=T=0;                 //Must initialize Y (player Y location), G (gap distance from top), and T (time) to 0, each assignment returns the new result (0) which is used for the next assignment
             setInterval('            //setInterval will repeatedly call the following function, acting as the game loop
                                      //The following is particularly ordered to avoid needing parens https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
               T%99                   //Zero is treated a "falsey", so this will be "false" whenever T is divisible by 99 (happens at the moment the walls and player are both at Y=0)
                 ? 0                  //Ternary operator X ? Y : Z will return Y when X is truthy or Z when X is falsey, I'm using it as a concise if statement and don't care about the true case, so just return zero
                 : (Y>G) & (Y<(G+75)) //If player is below the top of the gap and above the bottom of the gap (single & is bitwise and, which works fine here)
                     ? G=T%75         //If the player is in the gap, set a new gap height (not chosen randomly, instead is equal to the remainder of the current time/score divided by 75)
                     : V=Y=T=0;       //If the player hit a wall, reset V (player velocity), Y (player height), and T (time/score) to zeros to restart
               Y-=V-=.04;             //Set V (player velocity) to V-.04 (velocity changed by gravity), returning the new V, THEN set Y to Y-newV to make the player move by the current velocity
               c.innerHTML=`          //Set the children of element with ID c (the svg) to the following path and text elements:
                 <path d=\'           //Start path element, d (draw?) string quote must be escaped as we have already nested unescaped ", ', and `
                                      //Path commands used below documented here: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d#Path_commands
                   M ${99-T%99} ${G}  //Move to location X=(99-T%99) Y=G, X will count down from 99 to 0 over and over as time increments, G is the distance from top of screen to the gap in the wall
                   h 9                //Move right 9 pixels relative to current location
                   V 0                //Move vertically to Y=0
                   h -9               //Move left 9 pixels relative to current location
                   Z                  //Return to starting location (completed top wall rectangle, automatically fills the completed shape with black)
                   v 75               //Move 75 pixels down (height of gap) from current location, now at top left corner of bottom wall
                   h 9                //Move right 9 pixels relative to current location
                   V 150              //Move vertically to Y=150 (bottom of image)
                   h -9               //Move left 9 pixels
                   Z                  //Move to starting location (overshoots to top left of top wall, filling in the now-enclosed bottom wall)
                   M 0 ${Y}           //Move to location X=0 Y=Y (Y variable is the player's Y location)
                   v 9                //Move down 9 pixels
                   h 9                //Move right 9 pixels
                   v -9               //Move up 9 pixels
                   H 0                //Move horizontally to X=0, enclosing the player's 9x9 square (9 chosen for player and wall width due to being largest single-digit value)
                   \'/>               //End of path string/element
                 <text y=11>          //Start of text, y must be provided or text is off-screen, setting y=9 causes text to be partially off-screen but saves a byte
                 `+T++',              //Increment time and concat as body for text, end function string as first argument of setInterval
             9)"                      //Remainder of onload is the second argument to setInterval, setting an interval of 9ms (111 fps, chosen due to it being slowest one-digit rate)
     onclick=V=2>                     //When you click on the SVG it sets the current velocity to 2 pixels/frame upwards

Maybe this explanation might help you find more improvements. 😉

@pratyushmittal
Copy link

pratyushmittal commented Dec 1, 2020

@jmromrell Thanks a lot for the detailed explanation. It is very interesting.

@addyosmani
Copy link

addyosmani commented Dec 1, 2020

A small riff on @jmromrell's excellent version allows this to scale better for 'full-screen' play but takes us back closer to 240 bytes.

<svg height="100%" width="100%" viewBox="0 0 290 190" id=c onload="Y=G=T=0;setInterval('T%99?0:Y>G&Y<G+75?G=T%75:V=Y=T=0;Y-=V-=.04;c.innerHTML=`<path d=\'M${99-T%99} ${G}h9V0h-9Zv75h9V150h-9ZM0 ${Y}v9h9v-9H0\'/><text y=11>${T++}`',9)"onclick=V=2>

It may be possible to address viewport scaling in fewer bytes with transform: scale(X) (e.g #c { transform: scale(2);} if we could avoid needing to set height/width/viewBox.

@wibbuffey
Copy link

wibbuffey commented Dec 2, 2020

@kres0345 Mobile browsers do support Data URIs as shown on this Can I Use page.
Although another two bytes would be nice, I don't think that is enough of a reward for mobile compatibility.

@MDeiml
Copy link

MDeiml commented Dec 28, 2020

You can actually just remove the "Z" and the "H0" from the path:

<svg id=c onload="Y=G=T=0;setInterval('T%99?0:Y>G&Y<G+75?G=T%75:V=Y=T=0;Y-=V-=.04;c.innerHTML=`<path d=\'M${99-T%99} ${G}h9V0h-9Zv75h9V150h-9M0 ${Y}v9h9v-9\'/><text y=11>`+T++',9)"onclick=V=2>

which is 192 bytes. This means the path is no longer closed, but it displays the same way because it is closed implicitly when it gets filled. The downside is that this is not very well defined behavior - I think - so some browsers could display it differently.

@MDeiml
Copy link

MDeiml commented Mar 30, 2021

<svg id=c onload="Y=G=T=0;setInterval('T%99?Y-=V-=.1:Y>G&Y<G+60?G=T%75:V=Y=T=0;c.innerHTML=`<path d=\'M${99-T%99} ${G}h9V0h-9Zv60h9V150h-9M0 ${Y}v9h9v-9\'/><text y=11>`+T++',9)"onclick=V=3>

189 bytes. But a bit more difficult (like the real flappy bird)

@mwaitzman
Copy link

mwaitzman commented Mar 30, 2021

it's been so long that I forgot how to run this...

@MDeiml
Copy link

MDeiml commented Mar 30, 2021

You can try this URL:

data:text/html,%3Csvg id%3Dc onload%3D"Y%3DG%3DT%3D0%3BsetInterval('T%2599%3FY-%3DV-%3D.1%3AY%3EG%26Y%3CG%2B60%3FG%3DT%2575%3AV%3DY%3DT%3D0%3Bc.innerHTML%3D`%3Cpath d%3D%5C'M%24%7B99-T%2599%7D %24%7BG%7Dh9V0h-9Zv60h9V150h-9M0 %24%7BY%7Dv9h9v-9%5C'%2F%3E%3Ctext y%3D11%3E`%2BT%2B%2B'%2C9)"onclick%3DV%3D3%3E

@mwaitzman
Copy link

mwaitzman commented Mar 30, 2021

thanks

@bigoulours
Copy link

bigoulours commented Jun 21, 2021

Easier to read if you only replace % with %25 in the address bar:

data:text/html,<svg id=c onload="Y=G=T=0;setInterval('T%2599?Y-=V-=.1:Y>G&Y<G+60?G=T%2575:V=Y=T=0;c.innerHTML=`<path d=\'M${99-T%2599} ${G}h9V0h-9Zv60h9V150h-9M0 ${Y}v9h9v-9\'/><text y=11>`+T++',9)"onclick=V=3>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment