Sunday, May 29, 2016

I broke Pico 8 and I am not even mad.

Yesterday I made Pico 8 run out of memory. I was trying to figure out how to spawn "enemies" in such way so they wouldn't overlap (which is important for the game). So far it works, but it is not a great solution if you need more than a handful things spawned (which I don't). It can quickly start hogging the memory, because the program gets lost in an ever expanding loop of spawning and deleting those squares. The top left variable tracks how many times the program goes through that loop before it can find a square that does not overlap any of the existing ones, and I have seen it add 500 on few occasions. To be honest, 500 is still a very impressive number. As someone new to programming, I am amazed how much even the limited Pico8 can compute. Anyway, here's the code for this function...


function create_bug()
--responsible for assigning
--random values to enemies
 local o={}
 o.x=flr(rnd(110))+10
 o.y=flr(rnd(60))+10
 o.w=flr(rnd(12))+4
 o.h=o.w
 o.x2=o.x+o.w
 o.y2=o.y+o.h
 o.col=flr(rnd(14))
 o.xdir=flr(rnd(2)+1)
 o.ydir=flr(rnd(2)+1)
 add(bugs,o)
 
--check if the new bug is not overlapping
--with any existing bug.
 for a=1,#bugs -1 do
--by using the collision formula
   if bugs[a].x<=o.x+o.w 
    and bugs[a].x+bugs[a].w>=o.x
    and bugs[a].y<=o.y+o.h
    and bugs[a].y+bugs[a].h>=o.y
    then test+=1
    del (bugs,bugs[#bugs]) --delete overlapping bug.
    create_bug() --try again
   end
 end
 
end

I won't use that method as there is a possibility it will simply break the game. But, I will leave it here, as a pretty good example of the programming process (at least for newbies): code, find out it doesn't work exactly how you wanted, find the reason why, code more. I am quite proud that I was able to break PICO8 and that I could identify why it happened. So there's that. It seems that, instead of deleting and trying again, a better way is to move the new object so it is no longer on top of any of the existing ones. At least it seems better on the surface...

No comments:

Post a Comment