previndexinfonext

code guessing, round #81 (completed)

started at ; stage 2 at ; ended at

specification

hello AMAZING contestants! time for another PHYSICAL CHALLENGE. simulate collisions. submissions can be made in any language.

hello amazing contestants! time for another physical challenge. simulate collisions. submissions can be made in any language.

hands on your keyboards, folks! you are going to have some objects, and you have to figure out how they behave when they collide. you can reach for the stars and make it handle really complex objects, or stick to simpler shapes. at the end of the day the goal is to have fun. So relax and enjoy

now, a word from our sponsors.

word

since we are the best TV show, we allow any language and this challenge has no fixed API. Mike, start the round. (And get me a cup of coffee)

results

  1. 🅿️ kimapr +5 -3 = 2
    1. olive
    2. oleander
    3. rrebbbbeca
    4. Dolphy
    5. yeti
  2. oleander +2 -1 = 1
    1. rrebbbbeca (was olive)
    2. olive (was kimapr)
    3. kimapr (was rrebbbbeca)
    4. Dolphy
    5. yeti
  3. olive +2 -2 = 0
    1. kimapr
    2. yeti (was oleander)
    3. rrebbbbeca
    4. oleander (was Dolphy)
    5. Dolphy (was yeti)
  4. rrebbbbeca +2 -2 = 0
    1. olive
    2. kimapr
    3. yeti (was oleander)
    4. oleander (was Dolphy)
    5. Dolphy (was yeti)
  5. Dolphy +2 -2 = 0
    1. rrebbbbeca (was olive)
    2. kimapr
    3. olive (was oleander)
    4. oleander (was rrebbbbeca)
    5. yeti
  6. yeti +0 -3 = -3

    entries

    you can download all the entries

    entry #1

    written by olive
    submitted at
    0 likes

    guesses
    comments 0

    post a comment


    dir Tower Gate breaKtime CHOCOLATE CANYON CHUNKY BARS Ingrom: 45% Milk Chocolate (Dried Skimmed Milk, Dried Whey (Milk), Butter Oil (Milk), Emulsifier: Soya Lecithins), Wheat Flour (Wheat Flour), Oatmeal, Emulsifier: Soya Lecithins Suit
    main.lua Unicode text, UTF-8 text
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    -- local grav = 9.8
    local grav = 5
    
    local bodies = {}
    
    local tau = math.pi*2
    local vary = 6
    local function pointscircle(n,r, x,y)
    	local t = {}
    	for i = 1,n do
    		local a = i/n*tau
    		t[i] = {
    			x = math.sin(a)*r + x + (math.random()-0.5)*vary,
    			y = math.cos(a)*r + y + (math.random()-0.5)*vary,
    			vx=0,vy=0,
    			ax=0,ay=0,
    		}
    	end
    	return t
    end
    
    bodies[1] = {
    	colour={0.4,0.4,0.6},
    	circcol={0.5,0.5,0.7},
    	points=pointscircle(25, 60, 0,-60),
    	circrad=24,
    	holdiness=0.1,
    	attriness=0,
    	-- targinter=25,
    	targinter=60,
    }
    
    bodies[2] = {
    	colour={0.6,0.4,0.4},
    	circcol={0.7,0.5,0.5},
    	points=pointscircle(20, 60, 300,-300),
    	circrad=24,
    	holdiness=0.1,
    	attriness=0,
    	-- targinter=18,
    	targinter=60,
    }
    
    bodies[3] = {
    	colour={0.4,0.6,0.4},
    	circcol={0.5,0.7,0.5},
    	points=pointscircle(10, 20, -200,-400),
    	circrad=24,
    	holdiness=0.1,
    	attriness=0,
    	-- targinter=10,
    	targinter=20,
    }
    
    
    local lg = love.graphics
    lg.setColour = lg.setColor
    lg.setColor = nil
    local lk = love.keyboard
    
    local cx,cy = -lg.getWidth()/2, -lg.getHeight()*10/12
    local camspeed = 10
    
    local function cammed(t)
    	local nt = {}
    	for i,p in ipairs(t) do
    		nt[2*i-1] = p.x-cx
    		nt[2*i]   = p.y-cy
    	end
    	return nt
    end
    
    local cog, rog, tog
    function love.draw()
    	local w,h = lg.getDimensions()
    	lg.setColour(1,1,1)
    	lg.clear(1,1,1)
    	lg.setColour(0,0,0)
    	lg.rectangle("fill", 0,0-cy, w,h+cy)
    	local pok = 0
    	for i,🧦 in ipairs(bodies) do
    		local camgirl = cammed(🧦.points)
    		lg.setColour(🧦.colour)
    		lg.polygon("fill", camgirl)
    		lg.setColour(🧦.circcol)
    		lg.polygon("line", camgirl)
    		for j,p in ipairs(🧦.points) do
    			local tx,ty = p.x-cx,p.y-cy
    			if tx>=0 and ty>=0 and tx<w and ty<h then pok=pok+1 end
    			lg.circle("fill", tx,ty, 5)--🧦.circrad)
    		end
    	end
    	if pok < 12 then
    		lg.setColour(1,0.1,0.1)
    		lg.print("THIS WAS NOT THE INTENTION", w*1/4,h*3/4, 5, 3,3)
    	end
    end
    
    local step
    local go = true
    function love.update(dt)
    	if lk.isDown("right") then cx=cx+dt*camspeed end
    	if lk.isDown("left")  then cx=cx-dt*camspeed end
    	if lk.isDown("down")  then cy=cy+dt*camspeed end
    	if lk.isDown("up")    then cy=cy-dt*camspeed end
    	
    	if go then step(dt*3) end
    end
    
    function love.keypressed(key)
    	if key == "." then
    		step(0.1, true)
    	elseif key == "space" then go = not go
    	end
    end
    
    local repeltouch = 7
    local boign = 0.4
    local frick = 0.2
    -- local liftpull = 0
    local tt = 0
    step = function(dt)
    	tt=tt+dt
    	if tt%21>=30%20.000000000001 then print("yeitgotscrOMBLED GROMITS") tt=0 end
    	for i,🧦 in ipairs(bodies) do
    		🧦.newpoints = {}
    		for j,p in ipairs(🧦.points) do
    			local np = {}
    			🧦.newpoints[j] = np
    
    			np.ax = 0
    			np.ay = grav
    
    			-- if j==12 or j == 7 then np.ay = np.ay - liftpull end
    
    			for jj,pp in ipairs(🧦.points) do
    				if j ~= jj then
    					local dsq = (pp.x-p.x)^2 + (pp.y-p.y)^2
    					local d = dsq^0.5
    					local xm,ym = (pp.x-p.x)/d, (pp.y-p.y)/d
    					
    				--	np.ax = np.ax - xm/d *🧦.circrad
    				--	np.ay = np.ay - ym/d *🧦.circrad
    					
    				--	local neigh = math.abs(jj-j)
    					-- FIXME: THIS IS WRONG AND REMEMBER ONE_INDEXED AND DAUHSUAHSHASA I ALSWAYS FORGET THOWT O DO THIS ervery time it is such a simple thing to want the smallest distance between two numbers on a circle
    				--	if neigh > (#🧦.points-1)/2 then neigh = (#🧦.points+1)-neigh end
    					-- however I do not feel like thinking it right now or I wil lnot get thuehis proram  distwactions can t=dsa yea
    					
    				--	local neigh = math.abs(jj-j)
    				--	if neigh >= (#🧦.points)/2 then neigh = #🧦.points-neigh end
    
    					local ofa = (jj/#🧦.points*tau)
    					local mfa = (j/#🧦.points*tau)
    					local td = ((math.sin(ofa)-math.sin(mfa))^2+(math.cos(ofa)-math.sin(mfa))^2)^0.5
    					local nf = (🧦.targinter*td-d) --/(neigh^1)
    					-- TODO: hang on, should these not be -ses ?:
    					np.ax = np.ax - xm*nf *🧦.holdiness
    					np.ay = np.ay - ym*nf *🧦.holdiness
    					
    				--	np.ax = np.ax + xm/dsq *🧦.attriness
    				--	np.ay = np.ay + ym/dsq *🧦.attriness
    				end
    				-- All signs of insanity should not be read as such, please read as though [IMAGE OF AN ORANGUTANG SAT COMFORTABLY ENJOYING ORANGE JUICE WITH CURIOSITY].
    				-- Where this 🧦🧦🧦🧦🧦🧦🧦🧦🧦 (one for the foot, one for the hand, one for the ear, one for the kidney, one for the nostril, one for the eye, one for the testicle, one for the breast, one for the pointy tooth) has been ammended, newer language is in use.
    			end
    			for ii,🧦🧦 in ipairs(bodies) do
    				if ii ~= i then
    					for jj,pp in ipairs(🧦🧦.points) do
    					--	if ii ~= i or jj ~= j then
    							local dsq = (pp.x-p.x)^2 + (pp.y-p.y)^2
    							local d = dsq^0.5
    							local xm,ym = (pp.x-p.x)/d, (pp.y-p.y)/d
    							
    							np.ax = np.ax - xm*repeltouch/dsq
    							np.ax = np.ax - ym*repeltouch/dsq
    					--	end
    					end
    				end
    			end
    
    		--	np.ax = np.ax - p.vx*frick*dt
    		--	np.ay = np.ay - p.vy*frick*dt
    			
    			np.vx = p.vx + p.ax*dt
    			np.vy = p.vy + p.ay*dt
    
    			np.vx = np.vx - p.vx*frick*dt
    			np.vy = np.vy - p.vy*frick*dt
    			
    			np.x = p.x+p.vx*dt
    			np.y = p.y+p.vy*dt
    
    			if np.y > 0 then np.y=0 np.vy=-boign*np.vy np.ay=0 end -- todoaadnsignsjdha ieda
    			if np.x <-400 then np.x=-400 np.vx=-boign*np.vx np.ax=0 end
    			if np.x > 400 then np.x= 400 np.vx=-boign*np.vx np.ax=0 end
    		end
    	end
    	for i,🧦 in ipairs(bodies) do
    		🧦.points = 🧦.newpoints
    		🧦.newpoints = nil
    	end
    end
    --socks
    --on the bodies
    -- why are they dead
    --- bec ause of the rhoddies
    --  but my socks
    -- my little tubes
    --0 their clocks
    -- have gone to bed
    -- zero holes
    -- zero seconds
    -- is that what it means
    -- to be dead?
    

    entry #2

    written by kimapr
    submitted at
    0 likes

    guesses
    comments 1
    kimapr known at the time as [cg's #2]

    top ten pro gamer tips:

    10 use the left mouse button to create or reposition cubes 9 use the right mouse button to attach cubes to each other or the environment 8 be aware that cubes do not handle strong impacts well 7 press the space bar to toggle freezing and unfreezing the game world 6
    5
    4
    3
    2
    1


    post a comment


    main.lua ASCII text
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
                               Object              =                                  {        assign                          =    function(  
                                 dst                  ,                            src              )                       for           k    
                                 ,                      v                          in            pairs(                    src             )   
                              do                        dst                       [                    k                    ]               =  
                            v                             end                  end                     };            function             OOB( 
                     boulder                                )              local                         w              =                  love
                      .                               graphics             .                    getWidth()         local                      h
                  =                                       love           .                        graphics         .                getHeight()
              for                                           n         =                                  1       ,                            #
           boulder                                         ,        2                                  do      if                      boulder 
         [                                                n       ]                                   >=     0                            and  
      boulder                                           [       n                                    ]      <=                             w   
     and                                          boulder      [                                    n      +                              1    
    ]                                              <=         h                                 then      return                      false    
    end                                         end           return                           true       end                       function   
    drawBoulder(                             body             ,                              ...          )                         love       
     .                                    graphics             .                          polygon(         "fill"                   ,          
       ...                                )                     if                        body              :                    getType()     
         ==                            "dynamic"                  and                    OOB                 {                    ...          
            }                         then                        toDestroy             [                     body               ]             
               =                      true                            end              end                      print(          "meow\n"       
                  )                  function                 checkBoulderDestructure( boulder                     ,            impulse        
                      )              if                                 boulder        :                         getType()      ~=             
                    "dynamic"         then                                return       end                             if       32000          
                           /(         boulder                                   :       getMass())                        <      impulse       
                            then       destructures                               [      boulder                            ]     =            
                              true        end                                     end    function                  destructure(    b           
                                   )       local                                   b2s      =                                {}    local       
                                    r          =                                      b       :                   getFixtures()[      1        
                                   ]:      getUserData()                              /         2                          local     bins      
                                    =              {                                  b           :              getWorldPoints(        -      
                                   r                  /                              2              ,                         -           r    
                                 /                      2                           ,                -                       r             /   
                               2                          ,                       r                    /                    2               ,  
                            r                              /                    2                       ,                 -                  r 
                         /                                  2                 ,                          r              /                     2
                      ,                                      r             /                             2           )}                     for
                  n                                          =           1                               ,         #                       bins
               ,                                            2         do                             local       b2                           =
           love                                            .       physics                              .     newBody(                   world 
         ,                                             bins       [                                    n     ],                           bins 
       [                                                n       +                                    1      ],                       "dynamic" 
     )                                               b2        :                              setAngle(    b                              :    
    getAngle())                                    b2         :                         setLinearVelocity(b                             :      
    getLinearVelocityFromWorldPoint(            bins          [                                 n         ],                          bins     
    [                                          n              +                               1           ]))                        b2        
     :                                 setAngularVelocity(     b                            :             getAngularVelocity())     b2s        
       [                                  #                     b2s                        +                1                      ]           
         =                              b2                       local                   f                   =                   love          
            .                         physics                       .                   newFixture(            b2                ,             
              love                    .                             physics            .                   newRectangleShape(   r              
                  ,                  r                                  ),             1                           )            f              
                      :              setUserData(                          r           )                              f         :              
                  setFriction(        0.9                                     )        end                              b       :              
                      destroy()       return                                  b2s       end                         function    findBody(      
                               x        ,                                         y      )                                for     _            
                                 ,        b                                        in    ipairs(                         world     :           
                        getBodies())        do                                     for      _                                 ,     f          
                                   in       ipairs(                                   b       :                   getFixtures())     do        
                                   if            f                                    :    testPoint(                          x       ,       
                                    y              )                               then        return                          b       end     
                                 end                end                            end          Object                        .       assign(  
                              love                      ,                           {              load                      =      function() 
                           world                          =                     love                   .               physics              .  
                      newWorld(                            0                    ,                     800                );             ground 
                         =                               love                 .                    physics              .              newBody(
                   world                                     ,            love                           .        graphics                    .
              getWidth()                                     /           2                               ,        love                        .
             graphics                                       .      getHeight()                           +       100                          ,
          "static"                                         )       love                                 .     physics                        . 
        newFixture(                                   ground      ,                                 love     .                         physics 
       .                                   newRectangleShape(   love                                 .     graphics                        .   
     getWidth()                                       *        2                                    ,      200                           ),    
    1                                              ):         setFriction(                       0.9      )                           world    
    :                                      setCallbacks(      nil                               ,         nil                          ,       
    nil                                        ,              function(                       a           ,                           b        
     ,                                      _                  ,                            ...            )                       local       
       imps                               =                     {                         ...               }                     local        
         imp                            =                         0                      for                 n                    =            
            1                          ,                            #                   imps                   ,                 2             
               do                     imp                             =                math                      .              max(           
                 imp                 ,                                 imps            [                           n            ])             
                     end             checkBoulderDestructure(              a           :                         getBody(),     imp            
                         )           checkBoulderDestructure(                 b        :                          getBody(),    imp            
                            )         end                                       )       end                               ,      update        
                               =       function(                                 dt      )                                 if    mouseJoint    
                               and      mouseJoint                                  :   isDestroyed()                     then   mouseJoint    
                                   =        nil                                    end      if                       mouseJoint    then        
                                local         mx                                      ,       my                               =    love       
                                    .          mouse                                  .   getPosition()                       if    paused     
                                 then            local                               jx           ,                           jy        =      
                          mouseJoint                  :                    getTarget()           local                        b           =    
                         mouseJoint                     :                  getBodies()            local                      x             ,   
                               y                          =                       b                    :          getPosition()             b  
                            :                    setPosition(                   x                       +                mx                  - 
                        jx                                  ,                 y                          +             my                     -
                     jy                                      )            end                   mouseJoint            :              setTarget(
                  mx                                         ,          my                               )         end             destructures
               =                                           {}         if                               not      paused                     then
           world                                           :      update(                              dt      )                           end 
         for                                              b       ,                                    _     in                         pairs( 
      destructures                                      )       do                                  for     _                              ,   
     b                                               in        ipairs(                      destructure(   b                             ))    
    do                                       destructure(     b                                   )       end                          end     
    if                                       mouseJoint       and                           mouseJoint    :                      isDestroyed() 
    then                                   mouseJoint         =                              nil          end                        end       
     ,                                   mousepressed          =                          function(        x                        ,          
       y                                  ,                     k                          )                local                 body         
         =                             findBody(                  x                      ,                   y                    )            
            if                         k                            ==                  2                      and               body          
              then                   toJoint                          =                body                    preJoint         =              
                 love                .                                physics          .                      newMouseJoint(    body           
                      ,              x                                     ,           y                              )         toJx           
                         =            x                                     toJy       =                                y       end            
                           if          k                                       ~=       1                               then     return        
                             end        if                                      not      body                            then    body          
                                 =       love                                       .    physics                             .   newBody(      
                               world        ,                                        x      ,                                 y     ,          
                            "dynamic"          )                                  local       f                                =    love       
                                    .         physics                                 .    newFixture(                      body       ,       
                                 love              .                            physics           .           newRectangleShape(        60     
                                   ,                 60                             ),              1                         )           f    
                                 :             setUserData(                        60                )                       f             :   
                      setFriction(                      0.9                       )                  end                   if       mouseJoint 
                          then                     mouseJoint                   :               destroy()               end          mouseJoint
                         =                               love                 .                    physics              .        newMouseJoint(
                    body                                     ,             x                             ,            y                       )
                 end                                         ,       keypressed                          =      function(                     k
               )                                           if         k                                 ==     "space"                     then
           paused                                          =        not                            paused      end                         end 
         ,                                     mousereleased      =                             function(    x                              ,  
       y                                                ,       k                                    )      if                             k   
     ==                                               2        and                             toJoint     then                        local   
    body2                                          =          findBody(                           x       ,                             y      
    )                                          local          body                              =         toJoint                      if      
    toJoint                                    :              isDestroyed()                  then         preJoint                    =        
     nil                                  toJoint              =                            nil            toJx                     =          
       nil                               toJy                   =                         nil               end                   toJoint      
         =                              nil                      local                   x2                  ,                    y2           
            =                         toJx                          ,                   toJy                   toJx              =             
              nil                     toJy                            =                nil                     preJoint         :              
               destroy()             preJoint                            =             nil                         if(          not            
                   body2             )                                     or          body2                         ==         body           
                       then          body2                                    =        ground                         end       love           
                            .         physics                                   .      newDistanceJoint(               body      ,             
                           body2        ,                                        x2      ,                                 y2     ,            
                                 x        ,                                         y      ,                              true     )           
                                 end        if                                       k      ~=                                1    then        
                               return         end                                    if    mouseJoint                       then  mouseJoint   
                                    :        destroy()                       mouseJoint         =                            nil      end      
                                  end              ,                               draw           =                   function()       love    
                                   .             graphics                            .          clear(                        0           ,    
                                 0                      ,                           1                )                    love             .   
                         graphics                         .                setColor(                   1                    ,               1  
                            ,                              1                    )               toDestroy                 =                 {} 
                      local                              seenj                =                         {}            for                     _
                      ,                                      b             in                      ipairs(         world                      :
             getBodies())                                   do          for                              _         ,                          f
               in                                      ipairs(        b                                  :   getFixtures())                  do
            if                                             f        :                         getShape():    getType()                      == 
        "polygon"                                      then     drawBoulder(                           b     ,                              b  
       :                                     getWorldPoints(    f                                    :     getShape():            getPoints()))
     end                                            end        end                                love     .                         graphics  
    .                                          setColor(      0.5                                 ,       0.5                           ,      
    0.5                                          )            if                             toJoint      and                         not      
    toJoint                                    :              isDestroyed()                  then         love                        .        
     graphics                               .                  line(                       toJx            ,                       toJy        
       ,                                 love                   .                         mouse             .                   getPosition()) 
         end                            for                       _                      ,                   b                    in           
           ipairs(                    world                         :                  getBodies())            do                for           
               _                      ,                               j                in                      ipairs(          b              
                  :                  getJoints())                       do             if                          j            :              
                 getType()           ==                               "distance"       and                          not         seenj          
                         [            j                                       ]        then                          seenj      [              
                            j          ]                                        =       true                           love      .             
                         graphics       .                                      line(     j                                  :   getAnchors())  
                               end        end                                     end     local                           seen     =           
                                  {}       local                                  todo      =                                {}     for        
                                    _          ,                                      b       in                          pairs(    world      
                                    :      getBodies())                              do        for                             _       ,       
                                    j              in                           ipairs(           b                            :  getJoints()) 
                                  do                 if                              j              :                 getType()          ==    
                            "mouse"                   then                  toDestroy                [                       b             ]   
                               =                        nil                    break                 end                  end              if  
                           not                      toDestroy                   [                       b                 ]               then 
                       todo                                 [                 b                          ]              =                  true
                    seen                                     [             b                             ]            =                    true
                 end                                       end         while                         next(        todo                        )
               do                                        local       ntodo                               =       {}                         for
            b                                              ,        _                                  in     pairs(                      todo 
         )                                               do       for                                  _     ,                              j  
       in                                           pairs(      b                                    :     getJoints())                   do   
     for                                              _        ,                                   b2      in                        ipairs({  
    j                                              :          getBodies()})                      do       if                           not     
    seen                                         [            b2                                ]         then                       ntodo     
    [                                         b2              ]                               =           true                    toDestroy    
     [                                      b2                 ]                            =              nil                     seen        
       [                                  b2                    ]                          =                true                  end          
         end                            end                       end                    todo                =                   ntodo         
            end                       for                           b                   ,                      _                 in            
             pairs(                  toDestroy                        )                do                        b              :              
               destroy()             end                             toDestroy         =                           nil          end            
                      ,              });                                                                                                       
    

    entry #3

    written by oleander
    submitted at
    0 likes

    guesses
    comments 0

    post a comment


    balls.py ASCII text
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    import os
    os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
    import math
    import pygame
    
    def update(balls, surface):
        surface.fill(pygame.Color('white'))
        for i in balls:
            i.render(surface)
        pygame.display.update()
    
    class moment:
        def __init__(self, vxa, vya, vxb, vyb, ma, mb, dx, dy):
            self.vxa = vxa
            self.vya = vya
            self.vxb = vxb
            self.vyb = vyb
            self.ma = ma
            self.mb = mb
            self.dx = dx
            self.dy = dy
            self.va = math.hypot(vxa, vya)
            self.vb = math.hypot(vxb, vyb)
            
            self.ta = math.pi/2 if vxa==0 else math.atan(vya / vxa)
            self.tb = math.pi/2 if vxb==0 else math.atan(vyb / vxb)
            self.c = math.pi/2 if dx==0  else math.atan(dy / dx)
            
            if vxa<=0: self.ta = self.ta +math.pi
            if vxb<=0: self.tb = self.tb+math.pi
            #if dx<0: self.c = self.c+math.pi
            
    
    class ball:
        def __init__(self, dx, dy, vx, vy, color, size):
            self.dx = dx
            self.dy = dy
            self.vx = vx
            self.vy = vy
            self.color = color
            self.size = size
            self.mass = size**2
        def tick(self):
            newX= self.dx + self.vx
            newY= self.dy + self.vy
            if (newX - self.size < 0) or (newX + self.size > 500):
                self.vx *= -1
            elif (newY - self.size < 0) or (newY + self.size > 500):
                self.vy *= -1
            else:
                self.dx = newX
                self.dy = newY
        def detect(self, other):
            distance = math.hypot(self.dx - other.dx, self.dy - other.dy)
            if distance < self.size + other.size:
                self.collide(other)
        
        def collide(self, other):    
            col=moment(self.vx, self.vy, other.vx, other.vy, self.mass, other.mass, self.dx-other.dx, self.dy-other.dy)         
            
            self.vx  = (col.va * math.cos(col.ta - col.c) * (col.ma - col.mb) * math.cos(col.c)) + (2 * col.mb * col.vb * math.cos(col.tb - col.c) * math.cos(col.c)) / (col.ma + col.mb) + (col.va * math.sin(col.ta - col.c) * math.cos(math.pi/2 + col.c))
            self.vy  = (col.va * math.cos(col.ta - col.c) * (col.ma - col.mb) * math.sin(col.c)) + (2 * col.mb * col.vb * math.cos(col.tb - col.c) * math.sin(col.c)) / (col.ma + col.mb) + (col.va * math.sin(col.ta - col.c) * math.sin(math.pi/2 + col.c))
            other.vx = (col.vb * math.cos(col.tb - col.c) * (col.mb - col.ma) * math.cos(col.c)) + (2 * col.ma * col.va * math.cos(col.ta - col.c) * math.cos(col.c)) / (col.mb + col.ma) + (col.vb * math.sin(col.tb - col.c) * math.cos(math.pi/2 + col.c))
            other.vy = (col.vb * math.cos(col.tb - col.c) * (col.mb - col.ma) * math.sin(col.c)) + (2 * col.ma * col.va * math.cos(col.ta - col.c) * math.sin(col.c)) / (col.mb + col.ma) + (col.vb * math.sin(col.tb - col.c) * math.sin(math.pi/2 + col.c))
            
            #1d
            #self.vx  = (col.ma * col.vxa - col.mb * col.vxa + 2 * col.mb * col.vxb) / (col.ma + col.mb)
            #other.vx = (col.mb * col.vxb - col.ma * col.vxb + 2 * col.ma * col.vxa) / (col.mb + col.ma)
            
            #energy lost
            #print(((self.vx**2 + self.vy**2) * self.mass + (other.vx**2 + other.vy**2) * other.mass)- (col.va**2 * col.ma + col.vb**2 * col.mb))
            
            
        def render(self, surface):
            pygame.draw.circle(surface, pygame.Color('black'), [int(self.dx), int(self.dy)], self.size)        
            pygame.draw.circle(surface, pygame.Color(self.color), [int(self.dx), int(self.dy)], self.size-2)
    
    
    pygame.init()
    surface = pygame.display.set_mode((500,500))
    pygame.display.set_caption('Balls')
    
    balls=[
    ball(50,50,.5,.5, 'red', 50),
    ball(350,350,-2,-2, 'blue', 50),
    ball(50,350,0,-2, 'yellow', 50),
    ball(350,50,-.2,1.5, 'green', 50),
    ball(250,250,.4,2, 'purple', 50),
    
    ]
    
    while 1:
        for i in range(0,len(balls)):
            balls[i].tick()
            for j in range(i+1,len(balls)):
                balls[i].detect(balls[j])
        update(balls, surface)
        pygame.time.wait(10)
        
    
    i made him.webp RIFF (little-endian) data, Web/P image, VP8 encoding, 2651x2964, Scaling: [none]x[none], YUV color, decoders should clamp

    entry #4

    written by rrebbbbeca
    submitted at
    0 likes

    guesses
    comments 0

    post a comment


    dir 81
    collision.lucia ASCII text
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    clamp:{y max x min z};
    lerp:{1-x*y+(x*z)};
    stiffness:0.3;
    
    G:love.graphics;
    SIZE:[G.getWidth(), G.getHeight()];
    
    newball: { 
    	pos: 2! map {math.random(SIZE x)};
    	rad: math.random(30,75);
    	col: 3! map {math.random()};
    	[pos:pos,old:pos,rad:rad,col:col]
    };
    balls: 20! map newball;
    
    bound:{clamp([0,0]+x.rad, x.pos, SIZE-x.rad)};
    verlet: {
    	accel: x; dt: y;
    	new: accel*dt*dt - z.old + (2*z.pos);
    	set(z,.old,z.pos);
    	set(z,.pos,new);
    };
    
    set(love, .draw, callable {
    	G.clear(1,1,1);
    	G.setColor(0,1,0);
    	f:{G.circle(y,x.pos 0,x.pos 1, x.rad)};
    	balls map { 
    		G.setColor(x.col); f(x,.fill);
    		G.setColor(0,0,0); f(x,.line);
    	};
    });
    
    hypot:{x*x sum @math.sqrt};
    norm:{h:hypot x;0~h?x*0:x/h};
    
    step: {
    	balls map { set(x, .pos, lerp(stiffness, x.pos, bound x)); };
    	3! map { news: balls map {
    		ball: x;
    		deltas: (balls flip).pos map {x-(ball.pos)}- ;
    		dists: deltas map hypot; dirs: deltas map norm;
    		radsums: (balls flip).rad map {ball.rad+x};
    		overlaps: dists - radsums -;
    		moves: overlaps > 0.001 * stiffness * dirs * overlaps;
    		move: moves sum;
    		x.pos + move
    	}};
    	[balls,news] flip map {set(x 0, .pos, x 1)};
    	call(love.mouse.isDown,1)
    		? set(balls 0, .pos, [love.mouse.getX(),love.mouse.getY()]) 
    		: 0;
    	balls map { verlet([0,1000], 1/60, x) };
    };
    
    set(love, .update, callable step);
    
    conf.lua ASCII text
    1
    function love.conf(t) t.window.title="cg81" end
    
    lucia.lua ASCII text
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    local ok,pprint = pcall(require, 'pprint')
    if not ok then pprint=print pformat=tostring  -- that's all you deserve
    else pformat=pprint.pformat pprint.setup{show_all=true,use_tostring=true} end
    
    local lpeg = require 'lpeg'
    local P,V,R,C,Ct,Cc = lpeg.P,lpeg.V,lpeg.R,lpeg.C,lpeg.Ct,lpeg.Cc
    
    local function isty(ty,x) return type(x) == 'table' and x.ty == ty end
    local function enty(ty) return function(x) x.ty=ty return x end end
    local function inty(ty) return function(x) return {ty=ty,x} end end
    local list = enty'list'
    local dict = inty'dict'
    local fn = inty'fn'
    local function islist(x) return isty('list',x) end
    local function isdict(x) return isty('dict',x) end
    local function isfn(x) return isty('fn',x) end
    
    local function conform(f)
    	local function inner(a,b)
    		local la,lb = islist(a),islist(b)
    		assert(la or type(a) == 'number','unconformation')
    		assert(lb or type(b) == 'number','unconformation '..type(b))
    
    		local out = list{}
    		if not la and not lb then return f(a,b)
    		elseif la and lb then
    			assert(#a == #b, 'unconformation length: '..#a..' '..#b) -- todo
    			for i = 1,#a do out[i] = inner(a[i],b[i]) end
    		elseif la then
    			for i,v in ipairs(a) do out[i] = inner(v,b) end
    		elseif lb then
    			for i,v in ipairs(b) do out[i] = inner(a,v) end
    		end
    		return out
    	end
    	return inner end
    local function conform1(f)
    	local function inner(a)
    		if not islist(a) then assert(type(a) == 'number') return f(a) end
    		local out = list{}
    		for i = 1,#a do out[i] = inner(a[i]) end
    		return out
    	end
    	return inner
    end
    
    local function eqq(a,b)
    	if a == b then return true end
    	if islist(a) and islist(b) and #a==#b then
    		for i=1,#a do if not eqq(a[i],b[i]) then return false end end
    		return true
    	elseif isdict(a) and isdict(b) then
    		local keys = {}
    		for k in pairs(a[1]) do keys[k] = true end
    		for k in pairs(b[1]) do keys[k] = true end
    		for k in pairs(keys) do
    			if not eqq(a[1][k],b[1][k]) then return false end
    		end
    		return true
    	end
    	return false
    end
    local call
    local dyads = {
    	['+'] = conform(function(a,b) return a+b end),
    	['-'] = conform(function(a,b) return a-b end),
    	['/'] = conform(function(a,b) return a/b end),
    	['*'] = conform(function(a,b) return a*b end),
    	['<'] = conform(function(a,b) return a<b and 1 or 0 end),
    	['>'] = conform(function(a,b) return a>b and 1 or 0 end),
    	['='] = conform(function(a,b) return a==b and 1 or 0 end),
    	['~'] = function(a,b) return eqq(a,b) and 1 or 0 end,
    	['++'] = function(a,b) -- it's PEND!!!!
    		if not islist(a) then a = list{a} end
    		if not islist(b) then b = list{b} end
    		local out = list{}
    		table.move(a,1,#a,1,out) table.move(b,1,#b,#a+1,out)
    		return out
    	end,
    	mod = conform(function(a,b) return a%b end),
    	max = conform(math.max),
    	min = conform(math.min),
    	-- this can all probably be generalized a bunch
    	['@'] = function(a,b,c) return call(c,b,{a}) end,
    	map = function(a,b,c)
    		assert(islist(a),'can only map over list, was '..type(a))
    		local out = list{}
    		for i,v in ipairs(a) do out[i] = call(c,b,{v}) end
    		return out
    	end
    }
    
    local monads = {
    	['-'] = conform1(function(a) return -a end),
    	sum = function(a)
    		assert(islist(a),'need list for sum')
    		local s = 0
    		if islist(a[1]) then s = list{} for i=1,#a[1] do s[i] = 0 end end
    		for _,v in ipairs(a) do s = dyads['+'](s,v) end
    		return s
    	end,
    	['!'] = function(a) local out = list{} for i=0,a-1 do out[i+1]=i end return out end,
    	['>'] = function(a) return list{a} end,
    	['<'] = function(a) assert(islist(a) and #a > 0,'cant unlist nonlist') return a[1] end,
    	flip = function(a,c) -- this already needs rewriting
    		if type(a) == 'number' then return a
    		elseif islist(a) then
    			if #a == 0 then return list{} end
    			if type(a[1]) == 'number' then
    				for i = 1,#a do assert(type(a[i]) == 'number','need list of only numbers for flip') end
    				return a
    			elseif islist(a[1]) then
    				local len = #a[1]
    				local out = list{}
    				for j = 1,len do out[j] = list{} end
    				for i,v in ipairs(a) do
    					assert(islist(v),'need list of only lists for flip')
    					assert(#v == len, 'need list of equisized lists for flip')
    					for j,w in ipairs(v) do out[j][i] = w end
    				end
    				return out
    			elseif isdict(a[1]) then
    				local out = dict{}
    				local keys = {} for k in pairs(a[1][1]) do table.insert(keys,k) end
    				for _,k in ipairs(keys) do out[1][k] = list{} end
    				for i,v in ipairs(a) do
    					assert(isdict(v),'need list of only dicts for flip')
    					for _,k in ipairs(keys) do out[1][k][i] = assert(v[1][k],'missing key '..k) end end
    				return out
    			end
    		elseif isdict(a) then
    			local keys = {} for k in pairs(a[1]) do table.insert(keys,k) end
    			local len
    			for _,k in ipairs(keys) do
    				assert(islist(a[1][k]),'need dict of only lists for flip')
    				len = len or #a[1][k]
    				assert(#a[1][k] == len,'need dict of equisized lists for flip')
    			end
    			local out = list{}
    			for i=1,len do out[i] = dict{} end
    			for k,v in pairs(a[1]) do
    				for j,w in ipairs(v) do out[j][1][k] = w end
    			end
    			return out
    		end
    	end,
    }
    
    local S = ("#" * (P(1) - '\n')^0 * ('\n' + P(-1)) + lpeg.S" \n\t")^0
    local function seq(item,sep) return (item * (sep*S*item)^0 )^-1 end
    local number = C(R"09"^1 * '.' * R"09"^1 + R"09"^1) / tonumber
    local op = C(P"+"+"-"+"*"+"/")
    
    local namechar = R"az"+R"AZ"+"_"
    local name = C( (R"az"+R"AZ"+"_")^1 ) / function(s) return {ty='name',n=s} end
    local symbol = ('.'*name) / enty'string'
    
    local function grab_names(map)
    	local keys = {}
    	for k in pairs(map) do table.insert(keys,k) end
    	table.sort(keys,function(a,b) return #a > #b end)
    	local p = P(false)
    	for _,k in ipairs(keys) do
    		if not namechar:match(k) then p = p + k
    		else p = p + (k * -namechar) end end
    	return p end
    
    local monad_names = grab_names(monads)
    local dyad_names = grab_names(dyads)
    local monad = S*C(monad_names)*S
    local dyad = S*C(dyad_names)*S*V'term'
    local reserved = monad_names+dyad_names
    name = name - reserved
    
    local gram = P{"body",
    	call = Ct(V'noun'*('('*S*V'list_body'*')' + V'noun')^1 ) * S / enty'call',
    	noun = (name + symbol + number + V'fn' + "("*V"body"*")" + V'list' + V'dict') * S,
    	term = V'call' + V'noun',
    	oper = (dyad + monad)
    		/ function(v,n) return {ty='oper',v,n} end,
    	real_expr = Ct(V'term' * V'oper'^0) / enty'expr',
    	expr = V'cond' + V'real_expr',
    	cond = Ct(V'real_expr' * '?' * S * V'real_expr' * ':' * S * V'expr') / enty'cond',
    	body = Ct( seq(V'decl' + V'expr', ';') * (S*';'*Cc(0))^-1 * S ) / enty'body',
    	list_body = Ct( seq(V'expr', ',') ) / enty'list_body',
    	list = ('[' * S * V'list_body' * ']') / enty'list_lit',
    	decl = Ct(name * ':' * S * V'expr') / enty'decl',
    	fn = '{'*S*V'body'*'}' / fn,
    	dict = Ct('['*S*':'*S*']' + '['*S*seq(V'decl',',')*']') / enty'dict_lit',
    }
    local patt = S * gram * S * -1
    
    local function qprint(x,ns)
    	local s = ('| '):rep(ns or 0)
    	if type(x) ~= 'table' then print(s..tostring(x))
    	else io.write(s..(x.ty or '???')..(x[1] and ':' or ''))
    		for k,v in pairs(x) do if type(k) == 'string' and k~='ty' then
    				io.write(' '..k..'='..tostring(v)..',') end end
    		print()
    		for i,v in ipairs(x) do qprint(v,(ns or 0)+1) end
    	end
    end
    
    local evals = {}
    local function eval(c,x)
    	if type(x) == 'number' then return x end
    	return (evals[x.ty] or error('uncomprehended type '..x.ty))(c,x)
    end
    
    call = function (c,callee,args)
    	if type(callee) == 'function' then return callee(table.unpack(args))
    	elseif islist(callee) then
    		assert(#args == 1 and type(args[1]) == 'number', 'can only index single number for now '..pformat(args))
    		local idx = math.floor(args[1])
    		assert(0 <= idx and idx < #callee,'index out of bounds')
    		return callee[idx + 1]
    	elseif isfn(callee) then
    		table.insert(c.cs,1,{a=args,f=callee})
    		local res = eval(c,callee[1])
    		table.remove(c.cs,1)
    		return res
    	elseif isdict(callee) then
    		return callee[1][args[1]] or 0
    	elseif type(callee) == 'table' then
    		return callee[args[1]] -- ordinary table access
    	else pprint(callee,args) error'unsupported call style'
    	end
    end
    
    function evals.expr(c,t)
    	local val = eval(c,t[1])
    	for i = 2, #t do
    		local oper = t[i]  assert(oper.ty == 'oper')
    		local v,n = oper[1],oper[2]
    		if n then val = (dyads[v] or error("no such dyad "..v))(val, eval(c,n),c)
    		else val = (monads[v] or error("no such monad "..v))(val,c) end
    	end
    	return val
    end
    function evals.list_lit(c,t)
    	local out = list{}
    	for i,v in ipairs(t) do
    		out[i] = eval(c,v)
    	end
    	return out
    end
    function evals.dict_lit(c,t)
    	local out = dict{}
    	for i,v in ipairs(t) do
    		assert(v.ty == 'decl')
    		local name,val = v[1],v[2]
    		assert(name.ty == 'name')
    		out[1][name.n] = eval(c,v[2])
    	end
    	return out
    end
    function evals.fn(c,t) return t end
    function evals.string(c,t) return t.n end
    function evals.body(c,t)
    	if #t < 1 then return 0 end
    	local v
    	for i=1,#t do v = eval(c,t[i]) end
    	return v
    end
    function evals.decl(c,t)
    	local name=t[1] assert(name.ty=='name')
    	local val = eval(c,t[2])
    	c.g[name.n] = val
    	if isfn(val) then val.name = name.n end
    	return 0
    end
    function evals.name(c,t)
    	-- currently only magical names (x y z xx yy zz) and globals
    	-- todo: proper lexical scoping
    	local name,args,args2 = t.n, c.cs[1].a, c.cs[2].a
    	    if name == 'x' then return args[1] or 0
        elseif name == 'y' then return args[2] or 0
        elseif name == 'z' then return args[3] or 0
    	elseif name == 'xx' then return args2[1] or 0
        elseif name == 'yy' then return args2[2] or 0
        elseif name == 'zz' then return args2[3] or 0
        else return c.g[name] or _G[name] or 0 end end
    
    function evals.call(c,t)
    	local callee = eval(c,t[1])
    	assert(#t >= 2)
    	local function call1(callee,t)
    		local args
    		if isty('list_body',t) then
    			args = {}
    			for i,v in ipairs(t) do args[i] = eval(c,v) end
    		else args = {eval(c,t)} end
    		return call(c,callee,args)
    	end
    	for i=2,#t do
    		callee = call1(callee, t[i])
    	end
    	return callee
    end
    function evals.cond(c,t)
    	local cond = eval(c,t[1])
    	assert(type(cond) == 'number' and (cond == 1 or cond == 0), 'need 0 or 1 for cond')
    	return eval(c, t[3-cond])
    end
    
    local protect
    local function init()
    	local c
    	c = {
    		g={
    			set = function(t,k,v)
    				if isdict(t) then t = t[1] end
    				t[k] = v
    				return t
    			end,
    			-- a LITTLE clunky but i'm running out of time
    			callable = function(x)
    				return function(...) return protect(c, call, c, x, {...}) end
    			end,
    			call = function(f,...)
    				local r = table.pack(f(...))
    				for i=1,r.n do
    					if not r[i] then r[i] = 0
    					elseif r[i] == true then r[i] = 1
    					end
    				end
    				if r.n == 1 then return r[1] else r.n=nil return list(r) end
    			end,
    			pprint = function(...) pprint(...) end,
    			print=print,
    		},
    		cs={{a={},fake=true},{a={},fake=true}}}
    	return c
    end
    
    protect = function(c,...)
    	local ok, err = pcall(...)
    	if not ok then
    		for i,x in ipairs(c.cs) do if not x.fake then
    			print('-->',x.f and x.f.name or '??')
    		end end
    		error(err, 0)
    	else return err end
    end
    
    local function run(s,c,debug)
    	c = c or init()
    	local prog = patt:match(s)
    	if prog == nil then error'nil prog' end
    	if debug then qprint(prog) end
    	return protect(c, eval, c, prog)
    end
    
    local n = 1
    local function c(i,o)
    	io.write(n,'\t',i,'\t') n=n+1
    	io.flush()
    	local oo = run(i)
    	assert(eqq(o,oo), "expected to get "..pformat(o).." but i got "..pformat(oo))
    	print('ok')
    end
    
    c("2+2",4)
    c("6*6-",-36)
    c("2-20/6-",3)
    c("6*6+3",39)
    c("6*(6+3)",54)
    c("6+8/2",7)
    c('10+[1,2,3]',list{11,12,13})
    c('[10,20,30]/10',list{1,2,3})
    c('[2,3]*[4,5]',list{8,15})
    c('   (2+2;4*8;24)-4',20)
    c('  2+2; 5*5',25)
    c('a:6; b:7; a*b',42)
    c('math.sqrt(9)',3)
    c('math.sqrt 9',3)
    c('math.sqrt(7;8;9)',3)
    c('math.sqrt(9,8,7)',3)
    c('13 + math.sqrt 36',19)
    c('math.sqrt 36 + 13',19)
    c('math.sqrt (36 + 13)',7)
    c('math.sqrt 36 + (13-)',-7)
    c('math.sqrt 36 + 13-',-19)
    c('[10,20,30](0)',10)
    c('{x+5}20',25)
    c('{x+5}[10,20,30]',list{15,25,35})
    c('0.5+1',1.5)
    c('lerp:{1-x*y+(x*z)}; lerp(0.25,12,24)',15)
    c('lerp:{1-x*y+(x*z)}; lerp(0.25,[12,0],24)',list{15,6})
    c('lerp:{1-x*y+(x*z)}; lerp(1/4,[10,20],[18,16])',list{12,19})
    c('lerp:{1-x*y+(x*z)}; lerp([1/4,1/2],[10,20],[18,16])',list{12,18})
    c('lerp:{1-x*y+(x*z)}; mid:{lerp(1/2,x,y)}; mid([10,20,30],[90,80,70])',list{50,50,50})
    c('{36}()',36)
    c('[7-,6-,5-,4-,3-,2-,1-,0,1,2,3,4,5,6,7]mod3',list{2,0,1,2,0,1,2,0,1,2,0,1,2,0,1})
    c('modern:69;modern',69)
    c('dbl:{2*x}; 10 @ dbl',20)
    c('dbl:{2*x}; [10,20,30] @ dbl',list{20,40,60})
    c('dbl:{2*x}; [10,20,30] map dbl',list{20,40,60})
    c('[36,81] map math.sqrt',list{6,9})
    c('36 max 81 + 9',90)
    c('([{x+2},{x+10}]1) 5',15)
    c('[{x+2},{x+10}] 1 5',15)
    c('[{x+2},{x+10}] map {x 5}',list{7,15})
    c('.hi','hi')
    c('[1]++2',list{1,2})
    c('1++[2]',list{1,2})
    c('[1]++[2]',list{1,2})
    c('1++2',list{1,2})
    c('[1,2,3]++[4,5]',list{1,2,3,4,5})
    c('[1,2,3]++[[4,5]]',list{1,2,3,list{4,5}})
    c('[]++[1,2,3]',list{1,2,3})
    c('[1,2,3]++[]',list{1,2,3})
    c('[aaa:100, bbb:200, ccc:300].bbb',200)
    c('[ [aaa:100], [aaa:200], [aaa:300] ] map {x.aaa}',list{100,200,300})
    c('[aaa:[bbb:100]].aaa.bbb',100)
    c('[[1,2,3],[10,20,30],[100,200,300]] flip', list{list{1,10,100},list{2,20,200},list{3,30,300}})
    c('[1,2,3] flip',list{1,2,3})
    c('[] flip',list{})
    c('12 flip',12)
    c('[[a:1,b:2],[a:10,b:20],[a:100,b:200]] flip',dict{a=list{1,10,100},b=list{2,20,200}})
    c('[a:[1,10,100],b:[2,20,200]] flip',list{dict{a=1,b=2},dict{a=10,b=20},dict{a=100,b=200}})
    c('math.exp 1',math.exp(1))
    c('[:]',dict{})
    -- c('[:] flip',99999) -- i don't know what this should do
    _G.test = {a=100,b=200}
    c('test.a',100)
    c('set(test,.b,500); test.b',500) assert(_G.test.b == 500)
    c('2+2 # thats easy',4)
    c('5+5; #yeah\n2+2',4)
    c('10!sum',45)
    c('hypot:{x*x sum @math.sqrt}; hypot [3,4]',5)
    c('[10,20-]-',list{-10,20})
    c('0 ? 5 : 10',10)
    c('1 ? 5 : 10',5)
    c('2<3 ? 20 : 30',20)
    c('3<2 ? 20 : 10<20 ? 100 : 200',100)
    c('3<2 ? 20 : 20<10 ? 100 : 200',200)
    c('2<3 ? 20 : 20<10 ? 100 : 200',20)
    _G.test = {c=0,d=0}
    c('0 ? set(test,.c,123) : set(test,.d,456); 0',0) assert(_G.test.c == 0 and _G.test.d == 456)
    _G.test = {c=0,d=0}
    c('1 ? set(test,.c,123) : set(test,.d,456);',0) assert(_G.test.c == 123 and _G.test.d == 0)
    c('[10,20,30]<[18,19,20]',list{1,0,0})
    c('5!=3',list{0,0,0,1,0})
    c('[1,0,1,0]=[1,1,0,0]',list{1,0,0,1})
    c('[1,0,1,0]~[1,1,0,0]',0)
    c('[1,0,1,0]~[1,0,1,0]',1)
    c('[a:100,b:200]~[a:100]',0)
    c('[a:100,b:200]~[a:100,b:300]',0)
    c('[a:100,b:200]~[b:200,a:100]',1)
    c('2+2; 4+4',8)
    c('2+2; 4+4;',0)
    c('2>',list{2})
    c('[2,3]>',list{list{2,3}})
    c('[2,3]<',2)
    c('[2,3]><',list{2,3})
    c('{x}(1,2,3)',1)
    c('{y}(1,2,3)',2)
    c('{z}(1,2,3)',3)
    -- c('a:100; {a:200}(); a',100) -- todo
    -- c('a:100; {a:200; a}()+a',300) -- todo
    c('([ [a:10,b:20], [a:100,b:200] ] flip).a',list{10,100}) --egh
    -- c('[ [a:10,b:20], [a:100,b:200] ] flip.a',list{10,100}) --egh
    
    return {
    	run=run,
    }
    
    main.lua ASCII text
    1
    require'lucia'.run(io.open'collision.lucia':read'*a')
    

    entry #5

    written by Dolphy
    submitted at
    0 likes

    guesses
    comments 0

    post a comment


    spamton.png PNG image data, 498 x 498, 8-bit/color RGBA, non-interlaced
    tenna.png PNG image data, 894 x 894, 8-bit/color RGBA, non-interlaced
    yaoi.c ASCII text
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    #include "raylib.h"
    #include <stdbool.h>
    #include <stdio.h>
    #define MIN(x, y) ((x) < (y) ? (x) : (y))
    #define MAX(x, y) ((x) > (y) ? (x) : (y))
    
    typedef struct {
        int x;
        int y;
        int width;
        int height;
        Color color;
    } Box;
    
    bool aabb_collision(Box* a, Box* b) {
        return a->x < b->x + b->width && a->x + a->width > b->x &&
               a->y < b->y + b->height && a->y + a->height > b->y;
    }
    
    
    int main() {
        const int screenWidth = 1280;
        const int screenHeight = 720;
        InitWindow(screenWidth, screenHeight, "Yaoi");
    
        Box box1 = {
            .x = 20,
            .y = 300,
            .width = 128,
            .height = 128,
            .color = BLUE,
        };
    
        Box box2 = {
            .x = 1100,
            .y = 300,
            .width = 128,
            .height = 128,
            .color = RED
        };
    
        int spamton_frames = 0;
        int tenna_frames = 0;
        Image spamton = LoadImageAnim("spamton.png", &spamton_frames);
        ImageResize(&spamton, box1.width, box1.height);
        Image tenna = LoadImageAnim("tenna.png", &tenna_frames);
        ImageResize(&tenna, box2.width, box2.height);
        Texture2D spamton_texture = LoadTextureFromImage(spamton);
        Texture2D tenna_texture = LoadTextureFromImage(tenna);
    
        SetTargetFPS(60);
        const int SPD = 10;
    
        while (!WindowShouldClose()) {
            int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0;
    
            if (IsKeyDown(KEY_LEFT)) {
                dx1 = -SPD;
            }
            if (IsKeyDown(KEY_RIGHT)) {
                dx1 = SPD;
            }
            if (IsKeyDown(KEY_UP)) {
                dy1 = -SPD;
            }
            if (IsKeyDown(KEY_DOWN)) {
                dy1 = SPD;
            }
            if (IsKeyDown(KEY_A)) {
                dx2 = -SPD;
            }
            if (IsKeyDown(KEY_D)) {
                dx2 = SPD;
            }
            if (IsKeyDown(KEY_W)) {
                dy2 = -SPD;
            }
            if (IsKeyDown(KEY_S)) {
                dy2 = SPD;
            }
    
            box1.x += dx1;
            box1.y += dy1;
            box2.x += dx2;
            box2.y += dy2;
    
            if(aabb_collision(&box1, &box2)) {
                int overlap_x = MIN(box1.x + box1.width, box2.x + box2.width) - MAX(box1.x, box2.x);
                int overlap_y = MIN(box1.y + box1.height, box2.y + box2.height) - MAX(box1.y, box2.y);
                
                Vector2 mtv = {.x = 0, .y = 0};
                if (overlap_x < overlap_y) {
                    mtv.x = overlap_x * (box1.x < box2.x ? -1 : 1);
                }
                else {
                    mtv.y = overlap_y * (box1.y < box2.y ? -1 : 1);
                }
                if (dx1 != 0 || dy1 != 0) {
                    box1.x += mtv.x;
                    box1.y += mtv.y;
                }
                if(dx2 != 0 || dy2 != 0) {
                    box2.x -= mtv.x;
                    box2.y -= mtv.y;
                }
            }
    
            BeginDrawing();
                ClearBackground(BLACK);
    
                DrawTexture(spamton_texture, box1.x, box1.y, WHITE);
                DrawTexture(tenna_texture, box2.x, box2.y, WHITE);
            EndDrawing();
        }
    
        CloseWindow();
    
        return 0;
    }
    

    entry #6

    written by yeti
    submitted at
    0 likes

    guesses
    comments 3
    rrebbbbeca

    you need to initialize that variable.....


    (author of #5)

    thats a valid observation


    (author of #5)

    thats a valid observation


    post a comment


    main2.c ASCII text
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    #include <SDL3/SDL.h>
    #include <stdbool.h>
    #include <stdio.h>
    int
    main (void)
    {
      SDL_Window *window;
      SDL_Renderer *renderer;
      int y;
      if (false == SDL_Init (SDL_INIT_VIDEO))
        {
          puts (SDL_GetError ());
          return 1;
        }
      if (-1
          == SDL_CreateWindowAndRenderer ("foo", 256, 256, 0, &window, &renderer))
        {
          puts (SDL_GetError ());
          return 1;
        }
      while (true)
        {
          SDL_Event e;
          while (SDL_PollEvent (&e))
            if (SDL_EVENT_QUIT == e.type)
              return 0;
          SDL_SetRenderDrawColor (renderer, 0, 0, 0, 255);
          SDL_RenderClear (renderer);
          SDL_SetRenderDrawColor (renderer, 255, 255, 255, 255);
          SDL_FRect rectangle;
          rectangle.x = 64;
          rectangle.y = y;
          rectangle.w = 64;
          rectangle.h = 64;
          SDL_RenderFillRect (renderer, &rectangle);
          rectangle.x = 0;
          rectangle.y = 192;
          rectangle.w = 256;
          rectangle.h = 256;
          SDL_RenderFillRect (renderer, &rectangle);
          SDL_RenderPresent (renderer);
          y = 1 + y;
          if (y > 192 - 64)
            {
              y = y - 1;
            }
          SDL_Delay (1000 / 60);
        }
      return 0;
    }