Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


Space Invaders (With cheats)

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Lua Scripting
View previous topic :: View next topic  
Author Message
Dark Byte
Site Admin
Reputation: 475

Joined: 09 May 2003
Posts: 26030
Location: The netherlands

PostPosted: Mon Nov 16, 2026 3:11 am    Post subject: Space Invaders (With cheats) Reply with quote

I asked through CE's AITool (latest version https://github.com/cheat-engine/AITools ) on gemini 3.8 to write me a space invader game:

Code:

-- ============================================================================
-- SPACE INVADERS - CHEAT ENGINE EDITION
-- ============================================================================
-- Complete Space Invaders arcade clone written entirely in Cheat Engine Lua.
-- Features:
--   * Authentic retro pixel-art sprites (Squids, Crabs, Octopuses, UFO, Cannons)
--   * Destructible 4-bunker defense shields
--   * Dynamic marching fleet with acceleration as invaders are eliminated
--   * Alien bomb drops & mystery UFO fly-bys
--   * Flicker-free backbuffer rendering via LCL Bitmap & PaintBox
--   * Sound effects (arcade beeps)
--   * Interactive Cheat Menu (Press [C]) & global '_G.SpaceInvaders' state table
-- ============================================================================

-- Clean up any existing game window before starting a new one
if _G.SpaceInvadersInstance and _G.SpaceInvadersInstance.form and not _G.SpaceInvadersInstance.form.isDestroying then
  pcall(function() _G.SpaceInvadersInstance.form.close() end)
end

local SCREEN_W = 640
local SCREEN_H = 700

-- Game States
local STATE_TITLE       = 0
local STATE_PLAYING     = 1
local STATE_PLAYER_DEAD = 2
local STATE_NEXT_WAVE   = 3
local STATE_GAMEOVER    = 4

-- Retro Sprites (1 = pixel present, 0 = transparent)
local SPRITES = {
  squid = {
    {
      "00011000",
      "00111100",
      "01111110",
      "11011011",
      "11111111",
      "00100100",
      "01011010",
      "10100101"
    },
    {
      "00011000",
      "00111100",
      "01111110",
      "11011011",
      "11111111",
      "01011010",
      "10000001",
      "01000010"
    }
  },
  crab = {
    {
      "00100000100",
      "00010001000",
      "00111111100",
      "01101110110",
      "11111111111",
      "10111111101",
      "10100000101",
      "00011011000"
    },
    {
      "00100000100",
      "10010001001",
      "10111111101",
      "11100110111",
      "11111111111",
      "01111111110",
      "00100000100",
      "01000000010"
    }
  },
  octopus = {
    {
      "000011110000",
      "011111111110",
      "111111111111",
      "111001100111",
      "111111111111",
      "000110011000",
      "001101101100",
      "110000000011"
    },
    {
      "000011110000",
      "011111111110",
      "111111111111",
      "111001100111",
      "111111111111",
      "001100110000",
      "011000000110",
      "000110011000"
    }
  },
  ufo = {
    {
      "0000011111100000",
      "0001111111111000",
      "0011111111111100",
      "0110110110110110",
      "1111111111111111",
      "0001110001110000",
      "0000100000100000"
    }
  },
  player = {
    {
      "0000001000000",
      "0000011100000",
      "0000011100000",
      "0111111111110",
      "1111111111111",
      "1111111111111",
      "1111111111111",
      "1111111111111"
    }
  },
  alien_explosion = {
    {
      "0100010001000",
      "0010010010000",
      "0001000100000",
      "1110000000111",
      "0001000100000",
      "0010010010000",
      "0100010001000",
      "0000000000000"
    }
  },
  player_explosion = {
    {
      "010010100101001",
      "001001110010010",
      "000101110100000",
      "111100000111100",
      "000101110100000",
      "001001110010010",
      "010010100101001",
      "000000000000000"
    }
  }
}

-- Global Game State (Exposed to Cheat Engine users for direct memory inspection!)
_G.SpaceInvaders = {
  score = 0,
  highScore = (_G.SpaceInvaders and _G.SpaceInvaders.highScore) or 5000,
  lives = 3,
  wave = 1,
  godMode = false,
  rapidFire = false,
  piercingLaser = false,
  slowInvaders = false,
  soundEnabled = true
}

local G = _G.SpaceInvaders

-- Local session variables
local gameState = STATE_TITLE
local keys = {}
local keyOnce = {}

local player = {
  x = 300,
  y = 620,
  w = 39,
  h = 24,
  speed = 5,
  cooldown = 0
}

local playerBullets = {}
local alienBombs = {}
local explosions = {}
local ufoFloats = {}

local fleet = {
  x = 80,
  y = 110,
  dir = 1,
  stepX = 12,
  dropY = 16,
  timer = 0,
  stepInterval = 0.65,
  animFrame = 1,
  aliveCount = 55
}

local aliens = {}
local bunkers = {}

local ufo = {
  active = false,
  x = -50,
  y = 55,
  w = 48,
  h = 21,
  dir = 1,
  speed = 2.5,
  spawnTimer = 18.0
}

local stateTimer = 0
local showCheatMenu = false

-- Create Bunkers
local function resetBunkers()
  bunkers = {}
  local bxPositions = {70, 215, 360, 505}
  local pattern = {
    {0, 1, 1, 1, 1, 1, 1, 0},
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 0, 0, 0, 0, 1, 1},
    {1, 1, 0, 0, 0, 0, 1, 1}
  }
  local bSize = 5
  for _, bx in ipairs(bxPositions) do
    local b = {x = bx, y = 525, blockSize = bSize, grid = {}}
    for r = 1, #pattern do
      b.grid[r] = {}
      for c = 1, #pattern[r] do
        b.grid[r][c] = pattern[r][c]
      end
    end
    table.insert(bunkers, b)
  end
end

-- Initialize Alien Fleet
local function initFleet(waveNum)
  aliens = {}
  local startY = math.min(180, 100 + (waveNum - 1) * 12)
  fleet.x = 75
  fleet.y = startY
  fleet.dir = 1
  fleet.timer = 0
  fleet.animFrame = 1
  fleet.aliveCount = 55
  fleet.stepInterval = math.max(0.35, 0.65 - (waveNum - 1) * 0.05)

  for row = 0, 4 do
    local aType, pts, sprName, sprW, sprColor
    if row == 0 then
      aType = 1; pts = 30; sprName = "squid"; sprW = 24; sprColor = 0xFF00FF -- Pink/Magenta
    elseif row == 1 or row == 2 then
      aType = 2; pts = 20; sprName = "crab";  sprW = 33; sprColor = 0xFFFF00 -- Cyan
    else
      aType = 3; pts = 10; sprName = "octopus"; sprW = 36; sprColor = 0x00FF00 -- Lime Green
    end

    for col = 0, 10 do
      local relX = col * 44 + math.floor((44 - sprW) / 2)
      local relY = row * 34
      table.insert(aliens, {
        row = row,
        col = col,
        relX = relX,
        relY = relY,
        w = sprW,
        h = 24,
        type = aType,
        pts = pts,
        sprName = sprName,
        color = sprColor,
        alive = true
      })
    end
  end
end

-- Reset Game Session
local function startNewGame()
  G.score = 0
  G.lives = 3
  G.wave = 1
  player.x = 300
  player.cooldown = 0
  playerBullets = {}
  alienBombs = {}
  explosions = {}
  ufoFloats = {}
  ufo.active = false
  ufo.spawnTimer = 15.0
  initFleet(G.wave)
  resetBunkers()
  gameState = STATE_PLAYING
end

-- Helper: Draw pixel sprite onto canvas
local function drawSprite(canvas, sprite, x, y, scale, color)
  canvas.Brush.Color = color
  for r = 1, #sprite do
    local line = sprite[r]
    for c = 1, #line do
      if line:sub(c, c) == '1' then
        local px = x + (c - 1) * scale
        local py = y + (r - 1) * scale
        canvas.fillRect(px, py, px + scale, py + scale)
      end
    end
  end
end

-- Helper: Check AABB box overlap
local function rectsOverlap(x1, y1, w1, h1, x2, y2, w2, h2)
  return x1 < x2 + w2 and x1 + w1 > x2 and y1 < y2 + h2 and y1 + h1 > y2
end

-- Bunker damage handler
local function damageBunkerAt(bx, by)
  for _, b in ipairs(bunkers) do
    local bw = 8 * b.blockSize
    local bh = 6 * b.blockSize
    if bx >= b.x and bx <= b.x + bw and by >= b.y and by <= b.y + bh then
      local col = math.floor((bx - b.x) / b.blockSize) + 1
      local row = math.floor((by - b.y) / b.blockSize) + 1
      if row >= 1 and row <= 6 and col >= 1 and col <= 8 then
        if b.grid[row][col] == 1 then
          b.grid[row][col] = 0
          -- Chip neighboring block for natural blast cratering
          if math.random() > 0.4 then
            local nr = row + (math.random(-1, 1))
            local nc = col + (math.random(-1, 1))
            if nr >= 1 and nr <= 6 and nc >= 1 and nc <= 8 then
              b.grid[nr][nc] = 0
            end
          end
          return true
        end
      end
    end
  end
  return false
end

-- GUI Setup
local form = createForm(false)
form.Caption = "Space Invaders - Cheat Engine Edition"
form.Width = SCREEN_W
form.Height = SCREEN_H
form.BorderStyle = "bsSingle"
form.Position = "poScreenCenter"
form.Color = 0x000000
form.KeyPreview = true

local paintBox = createPaintBox(form)
paintBox.Align = "alClient"

local backbuffer = createBitmap(SCREEN_W, SCREEN_H)
local gameTimer = createTimer(form)
gameTimer.Interval = 16 -- ~60 FPS

_G.SpaceInvadersInstance = {form = form, timer = gameTimer, bitmap = backbuffer}

-- Keyboard Handlers
form.OnKeyDown = function(sender, key)
  keys[key] = true
  if not keyOnce[key] then
    keyOnce[key] = true

    -- Toggle Cheat Menu [C] = 67
    if key == 67 then
      showCheatMenu = not showCheatMenu
    end

    -- Cheat shortcuts when Cheat Menu is visible
    if showCheatMenu then
      if key == 49 then -- '1'spaghetti monsterMode
        G.godMode = not G.godMode
      elseif key == 50 then -- '2' Rapid Fire
        G.rapidFire = not G.rapidFire
      elseif key == 51 then -- '3' Piercing Laser
        G.piercingLaser = not G.piercingLaser
      elseif key == 52 then -- '4' Add Score
        G.score = G.score + 5000
      elseif key == 53 then -- '5' Extra Life
        G.lives = G.lives + 1
      elseif key == 54 then -- '6' Nuke Fleet
        for _, a in ipairs(aliens) do a.alive = false end
        fleet.aliveCount = 0
      elseif key == 55 then -- '7' Slow Invaders
        G.slowInvaders = not G.slowInvaders
      elseif key == 56 then -- '8' Toggle Sound
        G.soundEnabled = not G.soundEnabled
      end
    end

    -- Space (32) or Enter (13) on Title / Game Over
    if key == 32 or key == 13 then
      if gameState == STATE_TITLE or gameState == STATE_GAMEOVER then
        startNewGame()
      end
    end
  end
  return key
end

form.OnKeyUp = function(sender, key)
  keys[key] = false
  keyOnce[key] = false
  return key
end

-- Main Update Loop
local function updateGame()
  if showCheatMenu then return end -- Pause when cheat menu is open

  -- 1. TITLE / GAMEOVER
  if gameState == STATE_TITLE or gameState == STATE_GAMEOVER then
    return
  end

  -- 2. PLAYER DEAD ANIMATION
  if gameState == STATE_PLAYER_DEAD then
    stateTimer = stateTimer - 0.016
    if stateTimer <= 0 then
      if G.lives > 0 then
        player.x = 300
        player.cooldown = 0
        gameState = STATE_PLAYING
      else
        gameState = STATE_GAMEOVER
      end
    end
    return
  end

  -- 3. NEXT WAVE INTERMISSION
  if gameState == STATE_NEXT_WAVE then
    stateTimer = stateTimer - 0.016
    if stateTimer <= 0 then
      G.wave = G.wave + 1
      initFleet(G.wave)
      gameState = STATE_PLAYING
    end
    return
  end

  -- 4. PLAYER MOVEMENT
  local moveLeft = keys[37] or keys[65]   -- Left or 'A'
  local moveRight = keys[39] or keys[68]  -- Right or 'D'

  if moveLeft and player.x > 25 then
    player.x = player.x - player.speed
  end
  if moveRight and player.x < SCREEN_W - 25 - player.w then
    player.x = player.x + player.speed
  end

  -- 5. PLAYER SHOOTING
  if player.cooldown > 0 then
    player.cooldown = player.cooldown - 1
  end

  local shoot = keys[32] -- Space
  local maxShots = G.rapidFire and 8 or 1
  if shoot and player.cooldown <= 0 and #playerBullets < maxShots then
    table.insert(playerBullets, {
      x = player.x + math.floor(player.w / 2) - 1,
      y = player.y - 6,
      w = 3,
      h = 10,
      speed = 10,
      piercing = G.piercingLaser
    })
    player.cooldown = G.rapidFire and 8 or 20
    if G.soundEnabled then pcall(beep) end
  end

  -- 6. UPDATE PLAYER BULLETS
  for i = #playerBullets, 1, -1 do
    local b = playerBullets[i]
    b.y = b.y - b.speed

    local bulletRemoved = false

    -- Check top of screen
    if b.y < 45 then
      table.remove(playerBullets, i)
      bulletRemoved = true
    end

    -- Check Bunkers
    if not bulletRemoved and damageBunkerAt(b.x + 1, b.y) then
      if not b.piercing then
        table.remove(playerBullets, i)
        bulletRemoved = true
      end
    end

    -- Check UFO
    if not bulletRemoved and ufo.active and rectsOverlap(b.x, b.y, b.w, b.h, ufo.x, ufo.y, ufo.w, ufo.h) then
      ufo.active = false
      local pts = 50 * math.random(2, 6)
      G.score = G.score + pts
      if G.score > G.highScore then G.highScore = G.score end
      table.insert(ufoFloats, {text = tostring(pts), x = ufo.x, y = ufo.y, timer = 1.0})
      table.insert(explosions, {spr = "alien_explosion", x = ufo.x + 10, y = ufo.y, timer = 0.25})
      if not b.piercing then
        table.remove(playerBullets, i)
        bulletRemoved = true
      end
    end

    -- Check Aliens
    if not bulletRemoved then
      for _, a in ipairs(aliens) do
        if a.alive then
          local ax = fleet.x + a.relX
          local ay = fleet.y + a.relY
          if rectsOverlap(b.x, b.y, b.w, b.h, ax, ay, a.w, a.h) then
            a.alive = false
            fleet.aliveCount = fleet.aliveCount - 1
            G.score = G.score + a.pts
            if G.score > G.highScore then G.highScore = G.score end

            table.insert(explosions, {spr = "alien_explosion", x = ax, y = ay, timer = 0.18})

            if not b.piercing then
              table.remove(playerBullets, i)
              bulletRemoved = true
            end

            -- Speed up fleet as numbers dwindle!
            local speedRatio = fleet.aliveCount / 55
            fleet.stepInterval = math.max(0.04, 0.02 + 0.65 * speedRatio)
            break
          end
        end
      end
    end
  end

  -- 7. CHECK VICTORY (Wave Cleared)
  if fleet.aliveCount <= 0 then
    gameState = STATE_NEXT_WAVE
    stateTimer = 1.5
    return
  end

  -- 8. UPDATE ALIEN FLEET MARCH
  fleet.timer = fleet.timer + 0.016
  local currentInterval = G.slowInvaders and (fleet.stepInterval * 2.5) or fleet.stepInterval

  if fleet.timer >= currentInterval then
    fleet.timer = 0
    fleet.animFrame = 3 - fleet.animFrame -- Alternate 1 <-> 2

    -- Find horizontal bounds of surviving aliens
    local minX = 999999
    local maxX = -999999
    for _, a in ipairs(aliens) do
      if a.alive then
        local ax = fleet.x + a.relX
        if ax < minX then minX = ax end
        if ax + a.w > maxX then maxX = ax + a.w end
      end
    end

    -- Boundary check & direction change
    if fleet.dir == 1 and maxX + fleet.stepX >= SCREEN_W - 25 then
      fleet.dir = -1
      fleet.y = fleet.y + fleet.dropY
    elseif fleet.dir == -1 and minX - fleet.stepX <= 25 then
      fleet.dir = 1
      fleet.y = fleet.y + fleet.dropY
    else
      fleet.x = fleet.x + fleet.dir * fleet.stepX
    end

    -- Check if aliens reached bunkers or player cannon (Invasion Successful!)
    for _, a in ipairs(aliens) do
      if a.alive then
        local ay = fleet.y + a.relY
        if ay + a.h >= player.y then
          if not G.godMode then
            G.lives = 0
            gameState = STATE_GAMEOVER
            return
          end
        end
      end
    end
  end

  -- 9. ALIEN BOMB DROPPING
  if #alienBombs < math.min(5, 2 + math.floor(G.wave / 2)) and math.random() < 0.05 then
    -- Find lowest living alien in each column
    local bottomAliens = {}
    for col = 0, 10 do
      for row = 4, 0, -1 do
        local idx = row * 11 + col + 1
        local a = aliens[idx]
        if a and a.alive then
          table.insert(bottomAliens, a)
          break
        end
      end
    end

    if #bottomAliens > 0 then
      local shooter = bottomAliens[math.random(#bottomAliens)]
      local bx = fleet.x + shooter.relX + math.floor(shooter.w / 2)
      local by = fleet.y + shooter.relY + shooter.h
      table.insert(alienBombs, {x = bx, y = by, w = 3, h = 8, speed = 4.2})
    end
  end

  -- 10. UPDATE ALIEN BOMBS
  for i = #alienBombs, 1, -1 do
    local ab = alienBombs[i]
    ab.y = ab.y + ab.speed
    local bombRemoved = false

    -- Screen bottom
    if ab.y > 660 then
      table.remove(alienBombs, i)
      bombRemoved = true
    end

    -- Bunker hit
    if not bombRemoved and damageBunkerAt(ab.x + 1, ab.y + ab.h) then
      table.remove(alienBombs, i)
      bombRemoved = true
    end

    -- Player hit
    if not bombRemoved and rectsOverlap(ab.x, ab.y, ab.w, ab.h, player.x, player.y, player.w, player.h) then
      table.remove(alienBombs, i)
      bombRemoved = true

      if not G.godMode then
        G.lives = G.lives - 1
        table.insert(explosions, {spr = "player_explosion", x = player.x, y = player.y, timer = 1.0})
        gameState = STATE_PLAYER_DEAD
        stateTimer = 1.0
      end
    end
  end

  -- 11. UFO UPDATE
  ufo.spawnTimer = ufo.spawnTimer - 0.016
  if ufo.spawnTimer <= 0 and not ufo.active then
    ufo.active = true
    ufo.spawnTimer = 22.0 + math.random(5, 15)
    if math.random() > 0.5 then
      ufo.x = -50
      ufo.dir = 1
    else
      ufo.x = SCREEN_W + 10
      ufo.dir = -1
    end
  end

  if ufo.active then
    ufo.x = ufo.x + ufo.dir * ufo.speed
    if (ufo.dir == 1 and ufo.x > SCREEN_W + 20) or (ufo.dir == -1 and ufo.x < -60) then
      ufo.active = false
    end
  end

  -- 12. UPDATE TIMERS & PARTICLES
  for i = #explosions, 1, -1 do
    explosions[i].timer = explosions[i].timer - 0.016
    if explosions[i].timer <= 0 then table.remove(explosions, i) end
  end

  for i = #ufoFloats, 1, -1 do
    ufoFloats[i].timer = ufoFloats[i].timer - 0.016
    ufoFloats[i].y = ufoFloats[i].y - 0.5
    if ufoFloats[i].timer <= 0 then table.remove(ufoFloats, i) end
  end
end

-- Render Function
local function drawGame()
  local c = backbuffer.Canvas

  -- 1. Clear Screen
  c.Brush.Color = 0x000000
  c.fillRect(0, 0, SCREEN_W, SCREEN_H)

  -- 2. HUD (Top)
  c.Font.Name = "Courier New"
  c.Font.Size = 12
  c.Font.Color = 0xFFFFFF
  c.Brush.Style = "bsClear"

  c.textOut(30, 12, string.format("SCORE: %05d", G.score))
  c.textOut(250, 12, string.format("HI-SCORE: %05d", G.highScore))
  c.textOut(510, 12, string.format("WAVE: %02d", G.wave))

  -- Ground Line
  c.Pen.Color = 0x00FF00
  c.Pen.Width = 2
  c.line(10, 660, SCREEN_W - 10, 660)

  -- 3. Bottom Status Bar (Lives & Cheat badges)
  c.Font.Size = 10
  c.Font.Color = 0x00FF00
  c.textOut(30, 670, "LIVES:")
  for l = 1, math.max(0, G.lives - 1) do
    if l <= 6 then
      drawSprite(c, SPRITES.player[1], 80 + (l - 1) * 32, 668, 2, 0x00FF00)
    end
  end

  -- Cheat Indicators
  local tagX = 300
  if G.godMode then
    c.Font.Color = 0x00FFFF -- Yellow
    c.textOut(tagX, 672, "[GOD]")
    tagX = tagX + 60
  end
  if G.rapidFire then
    c.Font.Color = 0xFFFF00 -- Cyan
    c.textOut(tagX, 672, "[RAPID]")
    tagX = tagX + 70
  end
  if G.piercingLaser then
    c.Font.Color = 0xFF00FF -- Magenta
    c.textOut(tagX, 672, "[PIERCE]")
    tagX = tagX + 80
  end

  c.Font.Color = 0x888888
  c.textOut(510, 672, "[C] CHEATS")

  -- 4. TITLE SCREEN
  if gameState == STATE_TITLE then
    c.Font.Size = 24
    c.Font.Color = 0x00FF00
    local titleStr = "SPACE INVADERS"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(titleStr)) / 2), 110, titleStr)

    c.Font.Size = 11
    c.Font.Color = 0xFFFF00
    local subStr = "- CHEAT ENGINE EDITION -"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(subStr)) / 2), 155, subStr)

    -- Point Table
    c.Font.Size = 12
    c.Font.Color = 0xFFFFFF
    c.textOut(230, 220, "*SCORE ADVANCE TABLE*")

    drawSprite(c, SPRITES.ufo[1], 230, 260, 2, 0x0000FF)
    c.Font.Color = 0x0000FF
    c.textOut(280, 262, "= ?  MYSTERY")

    drawSprite(c, SPRITES.squid[1], 238, 295, 2, 0xFF00FF)
    c.Font.Color = 0xFF00FF
    c.textOut(280, 297, "= 30 POINTS")

    drawSprite(c, SPRITES.crab[1], 235, 330, 2, 0xFFFF00)
    c.Font.Color = 0xFFFF00
    c.textOut(280, 332, "= 20 POINTS")

    drawSprite(c, SPRITES.octopus[1], 234, 365, 2, 0x00FF00)
    c.Font.Color = 0x00FF00
    c.textOut(280, 367, "= 10 POINTS")

    -- Controls Box
    c.Font.Size = 10
    c.Font.Color = 0xAAAAAA
    c.textOut(160, 440, "CONTROLS:")
    c.textOut(160, 465, "[A] / [D] or [LEFT] / [RIGHT]  : MOVE")
    c.textOut(160, 490, "[SPACE]                        : FIRE CANNON")
    c.textOut(160, 515, "[C]                            : CHEAT ENGINE TRAINER")

    c.Font.Size = 14
    c.Font.Color = 0x00FFFF
    local playStr = "PRESS [SPACE] OR [ENTER] TO PLAY"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(playStr)) / 2), 580, playStr)
    return
  end

  -- 5. BUNKERS
  c.Brush.Color = 0x00FF00
  for _, b in ipairs(bunkers) do
    for r = 1, #b.grid do
      for col = 1, #b.grid[r] do
        if b.grid[r][col] == 1 then
          local px = b.x + (col - 1) * b.blockSize
          local py = b.y + (r - 1) * b.blockSize
          c.fillRect(px, py, px + b.blockSize, py + b.blockSize)
        end
      end
    end
  end

  -- 6. ALIEN FLEET
  for _, a in ipairs(aliens) do
    if a.alive then
      local ax = fleet.x + a.relX
      local ay = fleet.y + a.relY
      local spr = SPRITES[a.sprName][fleet.animFrame]
      drawSprite(c, spr, ax, ay, 3, a.color)
    end
  end

  -- 7. UFO
  if ufo.active then
    drawSprite(c, SPRITES.ufo[1], ufo.x, ufo.y, 3, 0x0000FF)
  end

  -- Floating UFO points
  c.Font.Size = 10
  c.Font.Color = 0x0000FF
  for _, f in ipairs(ufoFloats) do
    c.textOut(f.x, f.y, f.text)
  end

  -- 8. PLAYER CANNON
  if gameState ~= STATE_PLAYER_DEAD then
    drawSprite(c, SPRITES.player[1], player.x, player.y, 3, 0x00FF00)
  end

  -- 9. BULLETS & BOMBS
  -- Player Lasers
  for _, b in ipairs(playerBullets) do
    c.Brush.Color = b.piercing and 0xFF00FF or 0x00FFFF
    c.fillRect(b.x, b.y, b.x + b.w, b.y + b.h)
  end

  -- Alien Bombs
  c.Brush.Color = 0x0080FF
  for _, ab in ipairs(alienBombs) do
    c.fillRect(ab.x, ab.y, ab.x + ab.w, ab.y + ab.h)
  end

  -- 10. EXPLOSIONS
  for _, exp in ipairs(explosions) do
    drawSprite(c, SPRITES[exp.spr][1], exp.x, exp.y, 3, 0xFFFFFF)
  end

  -- 11. NEXT WAVE / GAMEOVER OVERLAYS
  if gameState == STATE_NEXT_WAVE then
    c.Font.Size = 18
    c.Font.Color = 0x00FFFF
    local wStr = string.format("WAVE %d CLEARED!", G.wave)
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(wStr)) / 2), 300, wStr)
  elseif gameState == STATE_GAMEOVER then
    c.Font.Size = 24
    c.Font.Color = 0x0000FF
    local goStr = "GAME OVER"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(goStr)) / 2), 270, goStr)

    c.Font.Size = 12
    c.Font.Color = 0xFFFFFF
    local reStr = "PRESS [SPACE] OR [ENTER] TO RESTART"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(reStr)) / 2), 330, reStr)
  end

  -- 12. CHEAT MENU OVERLAY (Trainer Window)
  if showCheatMenu then
    c.Brush.Color = 0x000000
    c.Pen.Color = 0x00FFFF
    c.Pen.Width = 3
    c.fillRect(100, 160, 540, 520)
    c.Brush.Style = "bsClear"

    c.Font.Size = 16
    c.Font.Color = 0x00FFFF
    local mTitle = "CHEAT ENGINE TRAINER MENU"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(mTitle)) / 2), 175, mTitle)

    c.Font.Size = 10
    c.Font.Color = 0x888888
    local sub = "Press number key to toggle/activate cheat:"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(sub)) / 2), 205, sub)

    c.Font.Size = 12
    local menuItems = {
      string.format("[1]spaghetti monsterMODE (Invulnerable) : %s", G.godMode and "ON" or "OFF"),
      string.format("[2] RAPID FIRE LASERS       : %s", G.rapidFire and "ON" or "OFF"),
      string.format("[3] PIERCING LASERS         : %s", G.piercingLaser and "ON" or "OFF"),
      string.format("[4] ADD +5,000 SCORE"),
      string.format("[5] ADD +1 EXTRA LIFE       (Current: %d)", G.lives),
      string.format("[6] NUKE CURRENT WAVE       (Destroy All)"),
      string.format("[7] SLOW INVADER SPEED      : %s", G.slowInvaders and "ON" or "OFF"),
      string.format("[8] RETRO AUDIO BEEPS       : %s", G.soundEnabled and "ON" or "OFF")
    }

    local yPos = 245
    for _, item in ipairs(menuItems) do
      c.Font.Color = (item:find("ON") and 0x00FF00) or 0xFFFFFF
      c.textOut(130, yPos, item)
      yPos = yPos + 30
    end

    c.Font.Size = 11
    c.Font.Color = 0x00FFFF
    local resumeStr = "PRESS [C] TO RESUME GAME"
    c.textOut(math.floor((SCREEN_W - c.getTextWidth(resumeStr)) / 2), 485, resumeStr)
  end
end

-- Paint Box Paint Handler
paintBox.OnPaint = function(sender)
  paintBox.Canvas.draw(0, 0, backbuffer)
end

-- Game Timer Tick
gameTimer.OnTimer = function(sender)
  updateGame()
  drawGame()
  paintBox.repaint()
end

-- Cleanup on Window Close
form.OnClose = function(sender)
  gameTimer.Enabled = false
  gameTimer.destroy()
  backbuffer.destroy()
  _G.SpaceInvadersInstance = nil
  return caFree
end

-- Launch the Game Window
form.show()
print("==================================================")
print("Space Invaders (Cheat Engine Edition) started!")
print("Window opened. Controls:")
print("  - [A]/[D] or [Left]/[Right] : Move Cannon")
print("  - [Space]                   : Fire Laser")
print("  - [C]                       : Open Cheat Menu")
print("Memory record access: inspect global table '_G.SpaceInvaders'")
print("==================================================")

_________________
Tools give you results. Knowledge gives you control.

Like my help? Join me on Patreon so i can keep helping
Back to top
View user's profile Send private message MSN Messenger
Csimbi
I post too much
Reputation: 99

Joined: 14 Jul 2007
Posts: 3440

PostPosted: Mon Nov 16, 2026 1:35 pm    Post subject: Reply with quote

Nice!
The main menu is largely unreadable - the background is indistinguishable from the letters in most cases - so I could not get it started though.
Back to top
View user's profile Send private message
AylinCE
Grandmaster Cheater Supreme
Reputation: 39

Joined: 16 Feb 2017
Posts: 1603

PostPosted: Thu Nov 19, 2026 5:26 am    Post subject: Reply with quote

This is exactly what I’m talking about.

I’m glad I’m not the only one who thinks the potential of CE goes far beyond just creating cheats.

Since DB has provided a starting point, here is the core code for my own game—a foundation to which many more features can be added.

A "match-3" algorithm built using CE. (Game core code.)

Code:
-- ========================================================
-- Match-3 RPG Engine (Single-Timer Main Loop)
-- ByAylinCE
-- ========================================================

local BASE_DPI = 96

local function getCurrentDPI()
    if type(getScreenDPI) == "function" then
        local dpi = getScreenDPI()
        if dpi and dpi > 0 then
            return dpi
        end
    end
    return BASE_DPI
end

local DPI_SCALE = getCurrentDPI() / BASE_DPI

local function px(value)
    return math.floor(value * DPI_SCALE + 0.5)
end

local GRID_SIZE = 9
local CELL_SIZE = px(44)
local MARGIN = px(4)
local GAME_TOP = px(120) -- Reserved space at the top for the Boss

local COLORS = {
    [1] = 0x0000FF, -- Red (Attack)
    [2] = 0x00FF00, -- Green (Heal)
    [3] = 0xFF0000, -- Blue (Magic)
    [4] = 0x00FFFF  -- Yellow (Critical)
}

local boardData = {}
local boardUI = {}

-- Game State Control
local STATE = "IDLE" -- IDLE, MATCHING, CLEARING, FALLING
local bossHP = 1000
local bossLabel = nil

local function getLeft(c) return MARGIN + (c - 1) * (CELL_SIZE + MARGIN) end
local function getTop(r)  return GAME_TOP + MARGIN + (r - 1) * (CELL_SIZE + MARGIN) end

-- --------------------------------------------------------
-- Main Game Loop (Single Timer - Stack Overflow Impossible)
-- --------------------------------------------------------
local mainTimer = createTimer()
mainTimer.Interval = 100
mainTimer.OnTimer = function()
    if STATE == "MATCHING" then
        local hasMatch, matched = findMatches()
        if hasMatch then
            STATE = "CLEARING"
            clearMatches(matched)
        else
            STATE = "IDLE"
        end
    end
end

function findMatches()
    local matched = {}
    for r = 1, GRID_SIZE do matched[r] = {} end
    local hasMatch = false

    -- Horizontal match check
    for r = 1, GRID_SIZE do
        for c = 1, GRID_SIZE - 2 do
            local id = boardData[r][c]
            if id ~= 0 and id == boardData[r][c+1] and id == boardData[r][c+2] then
                matched[r][c] = true; matched[r][c+1] = true; matched[r][c+2] = true; hasMatch = true
            end
        end
    end

    -- Vertical match check
    for c = 1, GRID_SIZE do
        for r = 1, GRID_SIZE - 2 do
            local id = boardData[r][c]
            if id ~= 0 and id == boardData[r+1][c] and id == boardData[r+2][c] then
                matched[r][c] = true; matched[r+1][c] = true; matched[r+2][c] = true; hasMatch = true
            end
        end
    end
    return hasMatch, matched
end

function clearMatches(matched)
    local damageCount = 0
    local flyStep = math.max(1, px(12))
    local hitLineY = px(40)

    for r = 1, GRID_SIZE do
        for c = 1, GRID_SIZE do
            if matched[r][c] then
                boardData[r][c] = 0
                damageCount = damageCount + 1
                local cell = boardUI[r][c]
                boardUI[r][c] = nil

                if cell then
                    -- Projectile-like rise effect toward the Boss
                    local fxTimer = createTimer()
                    fxTimer.Interval = 15
                    fxTimer.OnTimer = function(t)
                        if cell and cell.Top then
                            cell.Top = cell.Top - flyStep -- Move upward scaled by DPI
                            if cell.Top <= hitLineY then  -- Hit the Boss area
                                t.destroy()
                                cell.destroy()
                            end
                        else
                            t.destroy()
                        end
                    end
                end
            end
        end
    end

    -- Reduce Boss HP
    bossHP = math.max(0, bossHP - (damageCount * 15))
    if bossLabel then bossLabel.Caption = "BOSS HP: " .. tostring(bossHP) end

    -- Trigger Gravity and Refill after 300ms
    local delayTimer = createTimer()
    delayTimer.Interval = 300
    delayTimer.OnTimer = function(t)
        t.destroy()
        applyGravityAndRefill()
        STATE = "MATCHING" -- Check again for chain matches
    end
end

function applyGravityAndRefill()
    for c = 1, GRID_SIZE do
        local writeRow = GRID_SIZE
        for r = GRID_SIZE, 1, -1 do
            if boardData[r][c] ~= 0 then
                if writeRow ~= r then
                    boardData[writeRow][c] = boardData[r][c]
                    boardUI[writeRow][c] = boardUI[r][c]
                    boardData[r][c] = 0
                    boardUI[r][c] = nil

                    if boardUI[writeRow][c] then
                        boardUI[writeRow][c].Top = getTop(writeRow)
                    end
                end
                writeRow = writeRow - 1
            end
        end

        for r = writeRow, 1, -1 do
            boardData[r][c] = math.random(1, 4)
            boardUI[r][c] = createCellUI(r, c, boardData[r][c])
        end
    end
end

function createCellUI(r, c, colorId)
    local cell = createPanel(gamePanel)
    cell.Parent = gamePanel
    cell.Width = CELL_SIZE; cell.Height = CELL_SIZE
    cell.Left = getLeft(c); cell.Top = getTop(r)
    cell.Color = COLORS[colorId]
    cell.BevelOuter = "bvNone"

    -- Simple Click / Drag input handling
    local dragState = { active = false, startX = 0, startY = 0 }
    local dragThreshold = math.max(4, px(18))

    cell.OnMouseDown = function(sender, button, x, y)
        if STATE ~= "IDLE" then return end
        dragState.active = true
        dragState.startX, dragState.startY = sender.clientToScreen(x, y)
    end

    cell.OnMouseMove = function(sender, x, y)
        if not dragState.active or STATE ~= "IDLE" then return end
        local cx, cy = sender.clientToScreen(x, y)
        local dx = cx - dragState.startX
        local dy = cy - dragState.startY

        if math.abs(dx) > dragThreshold or math.abs(dy) > dragThreshold then
            dragState.active = false
            local curR, curC = nil, nil
            for tr = 1, GRID_SIZE do
                for tc = 1, GRID_SIZE do
                    if boardUI[tr][tc] == sender then curR, curC = tr, tc end
                end
            end

            if curR and curC then
                local tR, tC = curR, curC
                if math.abs(dx) > math.abs(dy) then
                    tC = tC + (dx > 0 and 1 or -1)
                else
                    tR = tR + (dy > 0 and 1 or -1)
                end

                if tR >= 1 and tR <= GRID_SIZE and tC >= 1 and tC <= GRID_SIZE then
                    -- Temporarily swap cells
                    boardData[curR][curC], boardData[tR][tC] = boardData[tR][tC], boardData[curR][curC]
                    boardUI[curR][curC], boardUI[tR][tC] = boardUI[tR][tC], boardUI[curR][curC]

                    boardUI[curR][curC].Left, boardUI[curR][curC].Top = getLeft(curC), getTop(curR)
                    boardUI[tR][tC].Left, boardUI[tR][tC].Top = getLeft(tC), getTop(tR)

                    -- Only allow swap if it creates a match; otherwise revert
                    local hasMatch, _ = findMatches()
                    if hasMatch then
                        STATE = "MATCHING"
                    else
                        boardData[curR][curC], boardData[tR][tC] = boardData[tR][tC], boardData[curR][curC]
                        boardUI[curR][curC], boardUI[tR][tC] = boardUI[tR][tC], boardUI[curR][curC]

                        boardUI[curR][curC].Left, boardUI[curR][curC].Top = getLeft(curC), getTop(curR)
                        boardUI[tR][tC].Left, boardUI[tR][tC].Top = getLeft(tC), getTop(tR)
                    end
                end
            end
        end
    end
    cell.OnMouseUp = function() dragState.active = false end
    return cell
end

-- Form Setup
math.randomseed(os.time())
local matchForm = createForm(false)
matchForm.Caption = "Match-3 RPG Boss Battle"
matchForm.Width = GRID_SIZE * (CELL_SIZE + MARGIN) + MARGIN + px(20)
matchForm.Height = GRID_SIZE * (CELL_SIZE + MARGIN) + GAME_TOP + px(60)
matchForm.Position = "poScreenCenter"

gamePanel = createPanel(matchForm)
gamePanel.Parent = matchForm
gamePanel.Left = px(10); gamePanel.Top = px(10)
gamePanel.Width = matchForm.Width - px(20)
gamePanel.Height = matchForm.Height - px(20)
gamePanel.Color = 0x111111

-- Boss Area
bossLabel = createLabel(gamePanel)
bossLabel.Parent = gamePanel
bossLabel.Left = px(120); bossLabel.Top = px(30)
bossLabel.Caption = "BOSS HP: 1000"
bossLabel.Font.Size = px(16)
bossLabel.Font.Color = 0x0000FF

-- Populate Board
for r = 1, GRID_SIZE do
    boardData[r] = {}; boardUI[r] = {}
    for c = 1, GRID_SIZE do
        local colorId = math.random(1, 4)
        boardData[r][c] = colorId
        boardUI[r][c] = createCellUI(r, c, colorId)
    end
end

matchForm.show()

_________________
Hi Hitler Different Trainer forms for you!
https://forum.cheatengine.org/viewtopic.php?t=619279
Enthusiastic people: Always one step ahead
Do not underestimate me Master: You were a beginner in the past
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Lua Scripting All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites