From 5019be454c03b362a1a13e1aabefb397c17ff383 Mon Sep 17 00:00:00 2001
From: annabunches <annabunches@gmail.com>
Date: Sat, 30 Sep 2023 18:23:42 -0400
Subject: [PATCH] Clean up dead sprites properly.

---
 src/bullet.lua    |  6 +++++-
 src/enemy/ebi.lua | 22 ++++++++++++----------
 src/entity.lua    |  7 ++++++-
 src/main.lua      |  8 +++++++-
 4 files changed, 30 insertions(+), 13 deletions(-)

diff --git a/src/bullet.lua b/src/bullet.lua
index ac9e31b..bc91f53 100644
--- a/src/bullet.lua
+++ b/src/bullet.lua
@@ -38,7 +38,11 @@ function Bullet:update()
       obj:damage(self.damage)
    end
 
-   if #collisions >= 1 then
+   if #collisions >= 1 or self:outOfBounds() then
       self:remove()
    end
 end
+
+function Bullet:outOfBounds()
+   return self.x < 0 or self.y < 0 or self.x > 400 or self.y > 240
+end
diff --git a/src/enemy/ebi.lua b/src/enemy/ebi.lua
index 026c2c6..0760638 100644
--- a/src/enemy/ebi.lua
+++ b/src/enemy/ebi.lua
@@ -17,9 +17,17 @@ function Ebi:init()
    if math.random(2) == 1 then
       dir = -1
    end
+
    self.vector = {x=0, y=dir}
 
-   self:weaponTimer()
+   self.weaponTimer = playdate.timer.new(2500,
+      function()
+         local b = Bullet(2, 1, {x=-1, y=0}, 0x2)
+         b:moveTo(self.x - (self.width/2) - 1, self.y)
+         b:add()
+      end
+   )
+   self.weaponTimer.repeats = true
 end
 
 function Ebi:update()
@@ -31,13 +39,7 @@ function Ebi:update()
    end
 end
 
-function Ebi:weaponTimer()
-   local t = playdate.timer.new(1000,
-      function()
-         local b = Bullet(2, 1, {x=-1, y=0}, 0x2)
-         b:moveTo(self.x - (self.width/2) - 1, self.y)
-         b:add()
-      end
-   )
-   t.repeats = true
+function Ebi:delete()
+   Ebi.super.delete(self)
+   self.weaponTimer:remove()
 end
diff --git a/src/entity.lua b/src/entity.lua
index 2c90352..296af25 100644
--- a/src/entity.lua
+++ b/src/entity.lua
@@ -30,7 +30,7 @@ function Entity:damage(amount)
    self.health = math.max(self.health - (amount - self.armor), 0)
 
    if self.health == 0 then
-      self:remove()
+      self:delete()
    end
 end
 
@@ -38,3 +38,8 @@ function Entity:update()
    local collisions = select(3, self:moveWithCollisions(self.x + self.vector.x, self.y + self.vector.y))
    return collisions
 end
+
+-- override this if you create timers
+function Entity:delete()
+   self:remove()
+end
diff --git a/src/main.lua b/src/main.lua
index 49c937f..859156c 100644
--- a/src/main.lua
+++ b/src/main.lua
@@ -46,8 +46,14 @@ function setup()
    enemy:add()
 
    makeWalls()
-   
    drawBackground()
+
+   -- debug, TODO remove this code
+   playdate.inputHandlers.push({
+         BButtonUp = function()
+            print(gfx.sprite.spriteCount())
+         end
+   })
 end
 
 function makeWalls()