A list of helpful libraries and code

Cheat Codes

I've been working on adding some cheats to my game, figured I'd share the class here incase anyone else would like it.

local keys = {
  a = playdate.kButtonA,
  b = playdate.kButtonB,
  up = playdate.kButtonUp,
  down = playdate.kButtonDown,
  left = playdate.kButtonLeft,
  right = playdate.kButtonRight
}

class("CheatCode").extends()

function CheatCode:init(...)
  local seq = {}
  for _, key in ipairs({...}) do
    local v = keys[key]
    assert(v, "CheatCode: unknown key given => "..tostring(key))
    table.insert(seq, v)
  end

  self._seq = seq
  self.progress = 1
  self.completed = false
  self.run_once = true
  self:setTimerDelay(400)
end

function CheatCode:update()
  -- exit early if complete
  if self.run_once and self.completed then return end

  local _, pressed, _ = playdate.getButtonState()
  -- exit early if no button currently pressed
  if pressed == 0 then return end

  if pressed == self._seq[self.progress] then
    self.progress += 1
    self._timer:reset()

    if self.progress > #self._seq then
      self.completed = true
      if type(self.onComplete) == "function" then
        self.onComplete()
      end
    end
  else
    self:reset()
  end
end

function CheatCode:reset()
  self.progress = 1
  self._timer:reset()
  self._timer:pause()
end

function CheatCode:setTimerDelay(ms)
  if self._timer then
    self._timer:remove()
  end
  self._timer = playdate.timer.new(ms, function() self:reset() end)
  self._timer:pause()
  self._timer.discardOnCompletion = false
end

function CheatCode:nextIs(key)
  return keys[key] == self._seq[self.progress]
end

Using it is simple enough

-- initialize 
local cheat = CheatCode("up", "up", "down", "down", "left", "right", "left", "right", "b", "a")
cheat.onComplete = function() print("cheat") end
-- in update function
playdate.timer.updateTimers() -- uses timers so make sure you call this
cheat:update()

By default it'll only trigger the first time the sequence is called, can be changed by setting run_once to false

CheatCode:nextIs([key]) is a helper to allow you to avoid triggering other effects while the code is being entered. eg:

if not cheat:nextIs("a") then
    -- do something else
end
8 Likes