Log In  

Cart #46571 | 2017-11-22 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
3

My first cart with PICO-8, Dot Party is a very simplistic implementation of a particle system using OOP techniques. I'm an hobbyist programmer and I've never used Lua before so this was mainly a learning experience figuring out how to make and use "classes" in PICO-8.

I'm not sure if my implementation is the best way (or even good), but here's the breakdown:

dot = {
  x      = 64,
  y      = 64,
  size   = 15,
  shrink = 0.2
}

function dot:new(o)
  local o = o or {}
  setmetatable(o, self)
  self.__index = self
  return o
end

function dot:update()
  self.x -= (self.x-64)/128
  self.y -= (self.y-64)/128
  self.size -= self.shrink
end

function dot:draw()
  circfill(self.x,
           self.y,
           self.size,
           self.size)
end

function dot:exists()
  return self.size > 0
end

This is the "dot" class and its members. It's got a constructor and various functions to update, draw, and return its status.

function spawn_dot(t)
  add(t, dot:new {
    x      = rnd(128),
    y      = rnd(128),
    size   = 1+rnd(15),
    shrink = 0.2+rnd(0.3)
  })
end

function update_all(t)
  local d = {}
  for _,o in pairs(t) do
    if o:exists() then
      o:update()
    else
      add(d, o)
    end
  end
  for _,o in pairs(d) do
    del(t, o)
  end
end

function draw_all(t)
  for _,o in pairs(t) do
    o:draw()
  end
end

Here we have a function that spawns a new dot and functions to update and draw tables of instanced objects. They assume these objects contain certain functions that they call for each.

function _init()
  dots = {}
end

function _update()
  update_all(dots)
  spawn_dot(dots)
end

function _draw()
  cls()
  draw_all(dots)
end

And here's the game loop, which looks nice and neat thanks to our functions.

This is certainly more abstracted than it needs to be, but again I'm just trying to learn. If there's something that I could be doing better I'd definitely like to know. I'm really enjoying using PICO-8 so far.

edit1: Updated the code to use foreach() where I could instead of for in all() because I've heard it's faster. Saved a couple tokens too at the expense of a few more chars.

edit2: Updated to use the pairs() iterator function because I found it to be the fastest method in my own tests. One thing to keep in mind is that pairs() does not iterate in a particular order, but for this it didn't seem to matter.

edit3: Removed recycling to simplify the code and I don't think it made a performance difference anyway.

edit4: Fixed bug in update_all() where deleting dots inside the loop caused the next dot to get skipped entirely. Also realized that pairs() does iterate in order when dealing with a sequenced table, so that's nice.

P#46540 2017-11-21 03:47 ( Edited 2017-11-22 07:02)


[Please log in to post a comment]