Skip to content

Instantly share code, notes, and snippets.

@finnbar
Created March 11, 2014 19:23
Show Gist options
  • Save finnbar/9493106 to your computer and use it in GitHub Desktop.
Save finnbar/9493106 to your computer and use it in GitHub Desktop.
Moonscript Pascal's Triangle Shader
love.conf = (t) ->
t.window.height=850
t.window.width=1000
import insert from table
mid = love.window.getWidth!/2 --midpoint of triangle
sq = 1 --square size
floorSize = math.ceil love.window.getHeight!/sq
mod = 2 --number to divide by
--cool numbers to use!: 2 (original pattern, works with clock), 7 (crazy thing), 5 (also quite crazy), 10 (awesome, works with clock)
clock = true --do you want to use clock addition? see below.
-- NOTE TO SELF:
-- The system used to just add the numbers up and be happy.
-- However, Lua truncates the numbers, which causes a problem: once you get >10000000000, which is quite quickly in pixel terms, Lua just writes them as standard notation, so will always assume that x%2==0, so it will be coloured.
-- To avoid this, I'm using CLOCK ADDITION (as to work out whether a number is divisible by 2 you only need the last digit), which truncates the number to just ONE digit
class pascal
new: => --initialise the program
@x=1 --block in pyramid
@a=1 --floor
@t={} --table to store pyramid
for a=1,floorSize
insert @t,{} --insert a floor
for x=1,a --only insert a number of blocks equal to the floor number (makes a triangle)
insert @t[a],1
step: =>
if @x==1 or @x==#@t[@a] or @a==1 --if at the end of the row or the top of the pyramid
@t[@a][@x]=1 --just add one
else
if @x-1>0 --if there's one before it (DOUBLE CHECKING)
@t[@a][@x]=@t[@a-1][@x]+@t[@a-1][@x-1] --block = two aboves added together
if clock and @t[@a][@x]>9 --clock addition!
@t[@a][@x]=@t[@a][@x]%10
else
@t[@a][@x]=1
--increment
@x+=1
if @a<@x
if @a==floorSize --if we've reached the end
@a=1 --go back to the start
else
@a+=1 --else go down one
@x=1 --and have another...uh...lark?
love.load = ->
export ins = pascal! --create a new instance of class pascal
love.draw = ->
import rectangle from love.graphics
t=ins.t
for a=1,floorSize
for x=1,a
if t[a][x]%mod==0
rectangle "fill",mid+(x*sq)-(a*0.5*sq),a*sq,sq,sq --draw a pixel!
love.update = ->
for i=1,1000
ins\step! --go forward i steps
love.keypressed = (key, isrepeat) ->
if key=="]" --if ] pressed, double square size (halving overall size)
sq*=2
floorSize = math.ceil love.window.getHeight!/sq
love.load!
elseif key=="[" --if [ do the opposite
sq/=2
floorSize = math.ceil love.window.getHeight!/sq
love.load!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment