Skip to content

Instantly share code, notes, and snippets.

@danprince
Last active March 17, 2020 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danprince/1b2b349b33286143154f289d8e761231 to your computer and use it in GitHub Desktop.
Save danprince/1b2b349b33286143154f289d8e761231 to your computer and use it in GitHub Desktop.
Game of Life Golf
<canvas id="$"></canvas><script>
// alias -1 (writing m is shorter than -1)
m=-1
// resize canvas to screen through its global variable (created from its id)
w=$.width=innerWidth,h=$.height=innerHeight
// create image data for rendering
d=new ImageData(w,h)
// two arrays to hold two generations of cells
a=[],b=[]
// return the state of the neighbour at p, q (coordinates relative to
// global x,y variables) taking 0 as default parameter allows us to shrink
// some calls to s
s=(p,q=0)=>a[x+p+(y+q)*w]|0
// give first generation of cells random states
for(i=0;i<w*h;i++)a[i]=Math.random()>.5
setInterval(_=>{
// loop over all cells
for(i=0;i<w*h;i++){
// set x, y from index
x=i%w,y=i/w|0
// count the living neighbours
n=s(m,m)+s(0,m)+s(1,m)+s(m)+s(1)+s(m,1)+s(0,1)+s(1,1)
// apply the life rules and store the new cell state in b
// then set the opacity in imagedata to 0 or 255
d.data[i*4+3]=(b[i]=a[i]?n==2||n==3:n==3)*255
}
// put the image data into the canvas
$.getContext`2d`.putImageData(d,0,0)
// swap the generations
_=a,a=b,b=_})</script>
<canvas id="$"></canvas><script>
m=-1,w=$.width=innerWidth,h=$.height=innerHeight
d=new ImageData(w,h)
a=[],b=[]
s=(p,q=0)=>a[x+p+(y+q)*w]|0
for(i=0;i<w*h;i++)a[i]=Math.random()>.5
setInterval(_=>{
for(i=0;i<w*h;i++){
x=i%w,y=i/w|0
n=s(m,m)+s(0,m)+s(1,m)+s(m)+s(1)+s(m,1)+s(0,1)+s(1,1)
d.data[i*4+3]=(b[i]=a[i]?n==2||n==3:n==3)*255}
$.getContext`2d`.putImageData(d,0,0)
_=a,a=b,b=_})</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment