OXT Community Stacks

The scripts of Ladybird Maze

Version 1.0. These are the scripts exactly as they are in the stack that plays here. Each line has its number, and a link to a line keeps it.

the stack script

Ladybird Maze.oxtstack, stack "Ladybird Maze", 1397 lines

-- Ladybird Maze: collect the leaves, reach the gold gate, keep away
-- from the spiders.
--
-- Two ideas are shown here, both in plain script:
--
-- 1. Collision by pixels. The hedges are ONE image whose transparent
--    pixels are the paths. The ladybird is a small round image. Before
--    every pixel of movement the game asks the engine
--       intersect(image "Lady", image "Hedge", "opaque pixels")
--    and only moves if the answer is false. The hedge corners are
--    rounded, so the ladybird slides around them. The leaves and the
--    spiders are caught with the same function.
--
-- 2. Pathfinding with A*. The spiders walk the maze cell by cell.
--    Each time a spider reaches a cell it asks mzAStar for the shortest
--    path to the ladybird (or to a random spot while it is only
--    patrolling). Tap or click a spot in the maze and the ladybird
--    walks there along the path that mzAStar finds for it, too.
--    Tick "Show paths" to see every path as it is found.
--
-- The game runs on a timer loop: mzTick moves everything a little,
-- then sends itself again 16 milliseconds later.
--
-- Arrow keys or WASD steer, Space pauses, N makes a new maze,
-- P shows the paths. On a phone: swipe to steer, tap to walk.

constant kTile = 24
constant kCols = 29
constant kRows = 21
constant kLeft = 20
constant kTop = 88
constant kLeafCount = 8
constant kPlayerSpeed = 100
constant kSpiderColours = "150,90,220|60,150,230|240,140,40|230,70,120"
constant kPathColours = "190,140,255|120,190,255|255,180,90|255,130,170"

local sWall, sFloorList, sState, sLevel, sLives, sScore, sLeaves
local sPX, sPY, sDir, sWant, sMoveBank, sAuto
local sSpiders, sSpiderCount, sLast, sTimer, sGraceUntil, sFrameAt, sFrame
local sLadyData, sSpiderData, sSpiderAlpha, sGateCell, sStartCell
local sHitTests, sSearches, sStatsAt, sFrames, sDownAt, sShowPaths
local sRowData, sRowAlpha, sFacing, sPiece, sAlphaPiece

-- ===================================================================
-- Opening and closing
-- ===================================================================

on openStack
   if sState is empty then
      put false into sShowPaths
      mzMakeSprites
      put 1 into sLevel
      put 3 into sLives
      put 0 into sScore
      mzNewLevel mzFreshSeed()
      put "ready" into sState
      mzMessage "Ladybird Maze", "Collect every leaf, then reach the gold gate." & return & \
            "Arrow keys or WASD to steer, Space to pause." & return & \
            "On a phone: swipe to steer, tap a spot to walk there." & return & return & \
            "Press Space or tap the maze to start."
   end if
end openStack

on closeStack
   mzStopTimer
   if sState is "playing" then put "paused" into sState
end closeStack

command mzStopTimer
   if sTimer is not empty then cancel sTimer
   put empty into sTimer
end mzStopTimer

-- ===================================================================
-- The maze
-- ===================================================================

-- A maze of corridors one tile wide. The tiles at odd columns and odd
-- rows are rooms; a depth-first walk joins them, then a few more walls
-- are knocked through so there are loops to run around.
command mzMakeMaze pSeed
   local tStack, tTop, tC, tR, tChoices, tStep, tNC, tNR, tPick, tKnock, i, tTries
   set the randomSeed to pSeed
   put empty into sWall
   repeat with tC = 0 to kCols - 1
      repeat with tR = 0 to kRows - 1
         put true into sWall[tC, tR]
      end repeat
   end repeat
   put false into sWall[1, 1]
   put "1,1" into tStack
   repeat while tStack is not empty
      put the last line of tStack into tTop
      put item 1 of tTop into tC
      put item 2 of tTop into tR
      put empty into tChoices
      repeat for each item tStep in "0 -2,2 0,0 2,-2 0"
         put tC + word 1 of tStep into tNC
         put tR + word 2 of tStep into tNR
         if tNC >= 1 and tNC <= kCols - 2 and tNR >= 1 and tNR <= kRows - 2 then
            if sWall[tNC, tNR] then put tNC & "," & tNR & return after tChoices
         end if
      end repeat
      if tChoices is empty then
         delete the last line of tStack
      else
         put line random(the number of lines of tChoices) of tChoices into tPick
         put item 1 of tPick into tNC
         put item 2 of tPick into tNR
         put false into sWall[tNC, tNR]
         put false into sWall[(tC + tNC) div 2, (tR + tNR) div 2]
         put return & tPick after tStack
      end if
   end repeat
   -- Loops: knock through walls that sit between two paths
   put 0 into tKnock
   put 0 into tTries
   repeat while tKnock < 22 and tTries < 2000
      add 1 to tTries
      put random(kCols - 2) into tC
      put random(kRows - 2) into tR
      if not sWall[tC, tR] then next repeat
      if (tC mod 2 is 0 and tR mod 2 is 1 and not sWall[tC - 1, tR] and not sWall[tC + 1, tR]) or \
            (tC mod 2 is 1 and tR mod 2 is 0 and not sWall[tC, tR - 1] and not sWall[tC, tR + 1]) then
         put false into sWall[tC, tR]
         add 1 to tKnock
      end if
   end repeat
   put empty into sFloorList
   repeat with tC = 0 to kCols - 1
      repeat with tR = 0 to kRows - 1
         if not sWall[tC, tR] then put tC & "," & tR & return after sFloorList
      end repeat
   end repeat
   delete the last char of sFloorList
end mzMakeMaze

-- A seed for a new maze. (The milliseconds since 1970 are too big a
-- number for the randomSeed, which would then be the same every time.)
function mzFreshSeed
   return (the milliseconds mod 1000000) + 1
end mzFreshSeed

function mzIsWall pC, pR
   if pC < 0 or pR < 0 or pC >= kCols or pR >= kRows then return true
   return sWall[pC, pR]
end mzIsWall

-- How many steps from one tile to every other (a flood fill), as an
-- array keyed "c,r". Used to place things far apart.
function mzDistances pFrom
   local tDist, tQueue, tHead, tCell, tC, tR, tNext, tStep
   put 0 into tDist[pFrom]
   put pFrom into tQueue
   put 1 into tHead
   repeat while tHead <= the number of lines of tQueue
      put line tHead of tQueue into tCell
      add 1 to tHead
      put item 1 of tCell into tC
      put item 2 of tCell into tR
      repeat for each item tStep in "0 -1,1 0,0 1,-1 0"
         put (tC + word 1 of tStep) & "," & (tR + word 2 of tStep) into tNext
         if mzIsWall(item 1 of tNext, item 2 of tNext) then next repeat
         if tDist[tNext] is not empty then next repeat
         put tDist[tCell] + 1 into tDist[tNext]
         put return & tNext after tQueue
      end repeat
   end repeat
   return tDist
end mzDistances

-- ===================================================================
-- A* pathfinding
-- ===================================================================

-- The shortest path between two tiles, one "c,r" per line from pFrom
-- to pTo, or empty when there is none. A* keeps the tiles it may visit
-- next in tOpen, each with its score f = steps so far (g) + a guess of
-- the steps still to go (h, the Manhattan distance, which never guesses
-- too many, so the path found is always a shortest one).
function mzAStar pFrom, pTo
   local tOpen, tOpenCount, tG, tCame, tClosed, tBest, tBestF, tBestH, tKey, tF, tH
   local tC, tR, tStep, tNext, tTry, tPath, tGoalC, tGoalR
   add 1 to sSearches
   if mzIsWall(item 1 of pFrom, item 2 of pFrom) or mzIsWall(item 1 of pTo, item 2 of pTo) then return empty
   put item 1 of pTo into tGoalC
   put item 2 of pTo into tGoalR
   put 0 into tG[pFrom]
   put abs(item 1 of pFrom - tGoalC) + abs(item 2 of pFrom - tGoalR) into tOpen[pFrom]
   put 1 into tOpenCount
   repeat while tOpenCount > 0
      -- the open tile with the lowest f (on a tie, the one nearer the goal)
      put empty into tBest
      repeat for each key tKey in tOpen
         put tOpen[tKey] into tF
         put tF - tG[tKey] into tH
         if tBest is empty or tF < tBestF or (tF = tBestF and tH < tBestH) then
            put tKey into tBest
            put tF into tBestF
            put tH into tBestH
         end if
      end repeat
      if tBest is pTo then
         put pTo into tPath
         repeat while tPath is not empty and line 1 of tPath is not pFrom
            put tCame[line 1 of tPath] & return before tPath
         end repeat
         return tPath
      end if
      delete variable tOpen[tBest]
      subtract 1 from tOpenCount
      put true into tClosed[tBest]
      put item 1 of tBest into tC
      put item 2 of tBest into tR
      repeat for each item tStep in "0 -1,1 0,0 1,-1 0"
         put (tC + word 1 of tStep) & "," & (tR + word 2 of tStep) into tNext
         if mzIsWall(item 1 of tNext, item 2 of tNext) then next repeat
         if tClosed[tNext] is true then next repeat
         put tG[tBest] + 1 into tTry
         if tG[tNext] is empty or tTry < tG[tNext] then
            if tOpen[tNext] is empty then add 1 to tOpenCount
            put tTry into tG[tNext]
            put tBest into tCame[tNext]
            put tTry + abs(item 1 of tNext - tGoalC) + abs(item 2 of tNext - tGoalR) into tOpen[tNext]
         end if
      end repeat
   end repeat
   return empty
end mzAStar

-- ===================================================================
-- Pictures: the hedges, the ladybird, the spiders
-- ===================================================================

-- The hedge image, built a row of pixels at a time from 24-pixel
-- pieces. A hedge tile has one of 16 looks, by which of its sides face
-- a path: those sides are lit or shaded, and a corner between two such
-- sides is rounded off (transparent), so it is the PIXELS that block.
command mzDrawHedges
   local tFloor, tFloorAlpha, tMask, tY, tC, tR, tData, tAlpha, tRow, tRowAlpha, tKey
   put empty into tFloor
   put empty into tFloorAlpha
   repeat kTile times
      put numToByte(0) & numToByte(0) & numToByte(0) & numToByte(0) after tFloor
      put numToByte(0) after tFloorAlpha
   end repeat
   -- the 16 looks are made once, with their own fixed random numbers
   if sPiece is empty then
      set the randomSeed to 4242
      repeat with tMask = 0 to 15
         repeat with tY = 0 to kTile - 1
            mzHedgeRow tMask, tY
            put sRowData into sPiece[tMask, tY]
            put sRowAlpha into sAlphaPiece[tMask, tY]
         end repeat
      end repeat
      set the randomSeed to mzFreshSeed()
   end if
   put empty into tData
   put empty into tAlpha
   repeat with tR = 0 to kRows - 1
      repeat with tY = 0 to kTile - 1
         put empty into tRow
         put empty into tRowAlpha
         repeat with tC = 0 to kCols - 1
            if sWall[tC, tR] then
               put mzExposed(tC, tR) into tMask
               put sPiece[tMask, tY] after tRow
               put sAlphaPiece[tMask, tY] after tRowAlpha
            else
               put tFloor after tRow
               put tFloorAlpha after tRowAlpha
            end if
         end repeat
         put tRow after tData
         put tRowAlpha after tAlpha
      end repeat
   end repeat
   lock screen
   set the width of image "Hedge" to kCols * kTile
   set the height of image "Hedge" to kRows * kTile
   set the topLeft of image "Hedge" to kLeft, kTop
   set the imageData of image "Hedge" to tData
   set the alphaData of image "Hedge" to tAlpha
   unlock screen
end mzDrawHedges

-- Which sides of a hedge tile face a path: 1 up, 2 right, 4 down, 8 left.
function mzExposed pC, pR
   local tMask
   put 0 into tMask
   if not mzIsWall(pC, pR - 1) then add 1 to tMask
   if not mzIsWall(pC + 1, pR) then add 2 to tMask
   if not mzIsWall(pC, pR + 1) then add 4 to tMask
   if not mzIsWall(pC - 1, pR) then add 8 to tMask
   return tMask
end mzExposed

-- One row of pixels of one hedge look, into sRowData and sRowAlpha.
command mzHedgeRow pMask, pY
   local tX, tUp, tRight, tDown, tLeft, tGreen, tLight, tCut, tRad, tCX, tCY
   put (pMask bitAnd 1) > 0 into tUp
   put (pMask bitAnd 2) > 0 into tRight
   put (pMask bitAnd 4) > 0 into tDown
   put (pMask bitAnd 8) > 0 into tLeft
   put 9 into tRad
   put empty into sRowData
   put empty into sRowAlpha
   repeat with tX = 0 to kTile - 1
      put false into tCut
      put empty into tCX
      if tUp and tLeft and tX < tRad and pY < tRad then
         put tRad into tCX
         put tRad into tCY
      else if tUp and tRight and tX >= kTile - tRad and pY < tRad then
         put kTile - tRad into tCX
         put tRad into tCY
      else if tDown and tLeft and tX < tRad and pY >= kTile - tRad then
         put tRad into tCX
         put kTile - tRad into tCY
      else if tDown and tRight and tX >= kTile - tRad and pY >= kTile - tRad then
         put kTile - tRad into tCX
         put kTile - tRad into tCY
      end if
      if tCX is not empty then
         put (tX + 0.5 - tCX) ^ 2 + (pY + 0.5 - tCY) ^ 2 > tRad ^ 2 into tCut
      end if
      if tCut then
         put numToByte(0) & numToByte(0) & numToByte(0) & numToByte(0) after sRowData
         put numToByte(0) after sRowAlpha
      else
         put random(36) - 18 into tLight
         if tUp and pY < 3 then add 46 to tLight
         if tLeft and tX < 2 then add 22 to tLight
         if tDown and pY > kTile - 4 then subtract 40 from tLight
         if tRight and tX > kTile - 3 then subtract 26 from tLight
         if random(23) = 1 then add 60 to tLight
         put max(0, min(255, 120 + tLight)) into tGreen
         put numToByte(0) & numToByte(max(0, min(255, 40 + tLight div 2))) & numToByte(tGreen) & \
               numToByte(max(0, min(255, 46 + tLight div 3))) after sRowData
         put numToByte(255) after sRowAlpha
      end if
   end repeat
end mzHedgeRow

-- The ladybird is round, so it has the same outline facing any way:
-- turning never pushes a pixel into a hedge. Only the drawing on its
-- back (the head, the line, the spots) turns.
command mzMakeSprites
   local tDir, tFX, tFY, tX, tY, tU, tV, tData, tAlpha, tColour, i, tFrame
   repeat for each item tDir in "right,down,left,up"
      switch tDir
         case "right"
            put 1 into tFX
            put 0 into tFY
            break
         case "down"
            put 0 into tFX
            put 1 into tFY
            break
         case "left"
            put -1 into tFX
            put 0 into tFY
            break
         default
            put 0 into tFX
            put -1 into tFY
      end switch
      put empty into tData
      put empty into tAlpha
      repeat with tY = 0 to 15
         repeat with tX = 0 to 15
            -- (tU along the way it faces, tV across)
            put (tX + 0.5 - 8) * tFX + (tY + 0.5 - 8) * tFY into tU
            put (tY + 0.5 - 8) * tFX - (tX + 0.5 - 8) * tFY into tV
            put mzLadyColour(tU, tV) into tColour
            if tColour is empty then
               put numToByte(0) & numToByte(0) & numToByte(0) & numToByte(0) after tData
               put numToByte(0) after tAlpha
            else
               put numToByte(0) & numToByte(item 1 of tColour) & numToByte(item 2 of tColour) & \
                     numToByte(item 3 of tColour) after tData
               put numToByte(255) after tAlpha
            end if
         end repeat
      end repeat
      put tData into sLadyData[tDir]
      put tAlpha into sLadyData[tDir, "alpha"]
   end repeat
   repeat with i = 1 to 4
      repeat with tFrame = 1 to 2
         mzSpiderPicture mzPick(kSpiderColours, i), tFrame
         put sRowData into sSpiderData[i, tFrame]
         put sRowAlpha into sSpiderAlpha[i, tFrame]
      end repeat
   end repeat
end mzMakeSprites

-- The colour of the ladybird at a point (tU forward, tV across, from
-- its middle), or empty outside it.
function mzLadyColour pU, pV
   local tD
   put pU ^ 2 + pV ^ 2 into tD
   if tD > 7.4 ^ 2 then return empty
   if pU > 3.2 then
      if abs(pV) > 1.6 and abs(pV) < 3.2 and pU < 4.6 then return "255,255,255"
      return "25,20,25"
   end if
   if abs(pV) < 0.6 then return "25,20,25"
   if (pU + 2.5) ^ 2 + (abs(pV) - 3.4) ^ 2 < 2.4 then return "25,20,25"
   if (pU - 1.2) ^ 2 + (abs(pV) - 3.8) ^ 2 < 1.8 then return "25,20,25"
   if (pU + 4.8) ^ 2 + (abs(pV) - 1.8) ^ 2 < 1.2 then return "25,20,25"
   if pU > -1 and pU < 1.4 and pV < -2 and pV > -3.6 then return "255,140,130"
   return "222,38,38"
end mzLadyColour

-- One spider picture, 18 by 18, into sRowData (pixels) and sRowAlpha.
-- Frame 2 has its legs moved, so a walking spider wiggles.
command mzSpiderPicture pColour, pFrame
   local tX, tY, tPX, tPY, tLeg, tAngle, tKnee, tOK, tShift, tDark
   put empty into sRowData
   put empty into sRowAlpha
   put (item 1 of pColour div 2) & "," & (item 2 of pColour div 2) & "," & (item 3 of pColour div 2) into tDark
   repeat with tY = 0 to 17
      repeat with tX = 0 to 17
         put tX + 0.5 - 9 into tPX
         put tY + 0.5 - 9 into tPY
         put empty into tOK
         if tPX ^ 2 + (tPY - 1.5) ^ 2 < 4.6 ^ 2 then put pColour into tOK
         if tPX ^ 2 + (tPY + 3.8) ^ 2 < 2.6 ^ 2 then put tDark into tOK
         if tOK is empty then
            repeat with tLeg = 0 to 7
               put (tLeg mod 4) into tAngle
               if pFrame is 2 then
                  put (tLeg mod 2) * 2 - 1 into tShift
               else
                  put 1 - (tLeg mod 2) * 2 into tShift
               end if
               if mzNearLeg(tPX, tPY, tLeg, tShift) then
                  put tDark into tOK
                  exit repeat
               end if
            end repeat
         end if
         if (abs(tPX + 1) < 0.8 or abs(tPX - 1) < 0.8) and abs(tPY + 4.5) < 0.7 then put "255,80,80" into tOK
         if tOK is empty then
            put numToByte(0) & numToByte(0) & numToByte(0) & numToByte(0) after sRowData
            put numToByte(0) after sRowAlpha
         else
            put numToByte(0) & numToByte(item 1 of tOK) & numToByte(item 2 of tOK) & numToByte(item 3 of tOK) after sRowData
            put numToByte(255) after sRowAlpha
         end if
      end repeat
   end repeat
end mzSpiderPicture

-- Is a point on one of the spider's eight legs? Each leg is two
-- straight pieces: out from the body to a knee, then down to a foot.
function mzNearLeg pX, pY, pLeg, pShift
   local tSide, tRow, tKX, tKY, tFX, tFY, tBX, tBY
   if pLeg < 4 then
      put -1 into tSide
   else
      put 1 into tSide
   end if
   put pLeg mod 4 into tRow
   put tSide * 2.5 into tBX
   put -1 + tRow * 1.6 into tBY
   put tSide * 6 into tKX
   put -4 + tRow * 2.6 + pShift * 0.6 into tKY
   put tSide * 8.2 into tFX
   put -6 + tRow * 4.6 + pShift into tFY
   if mzSegDist(pX, pY, tBX, tBY, tKX, tKY) < 0.75 then return true
   return mzSegDist(pX, pY, tKX, tKY, tFX, tFY) < 0.75
end mzNearLeg

-- One colour of a list like "1,2,3|4,5,6".
function mzPick pList, pIndex
   set the itemDelimiter to "|"
   return item pIndex of pList
end mzPick

function mzSegDist pX, pY, pAX, pAY, pBX, pBY
   local tDX, tDY, tLen, tT
   put pBX - pAX into tDX
   put pBY - pAY into tDY
   put tDX ^ 2 + tDY ^ 2 into tLen
   if tLen = 0 then return sqrt((pX - pAX) ^ 2 + (pY - pAY) ^ 2)
   put ((pX - pAX) * tDX + (pY - pAY) * tDY) / tLen into tT
   put max(0, min(1, tT)) into tT
   return sqrt((pX - pAX - tT * tDX) ^ 2 + (pY - pAY - tT * tDY) ^ 2)
end mzSegDist

-- ===================================================================
-- Levels
-- ===================================================================

command mzNewLevel pSeed
   local tDist, tFar, tKey, tCells, i, tCell, tPick, tSpot, tMax
   lock screen
   mzMakeMaze pSeed
   mzDrawHedges
   put "1,1" into sStartCell
   put mzDistances(sStartCell) into tDist
   -- the gate: the tile furthest from the start
   put 0 into tMax
   repeat for each key tKey in tDist
      if tDist[tKey] > tMax then
         put tDist[tKey] into tMax
         put tKey into sGateCell
      end if
   end repeat
   mzPlaceAtCell "graphic", "Gate", sGateCell, 18
   set the backgroundColor of graphic "Gate" to "90,90,100"
   set the blendLevel of graphic "Gate" to 40
   -- leaves: on tiles at least a few steps from the start
   put empty into tCells
   repeat for each key tKey in tDist
      if tDist[tKey] >= 6 and tKey is not sGateCell then put tKey & return after tCells
   end repeat
   repeat with i = 1 to kLeafCount
      put random(the number of lines of tCells) into tPick
      put line tPick of tCells into tCell
      delete line tPick of tCells
      mzPlaceAtCell "graphic", "leaf" & i, tCell, 11
      set the visible of graphic ("leaf" & i) to true
   end repeat
   put kLeafCount into sLeaves
   -- spiders: as many as the level allows, on tiles far from the start
   put min(4, sLevel + 1) into sSpiderCount
   put empty into tFar
   repeat for each key tKey in tDist
      if tDist[tKey] >= tMax * 0.55 then put tKey & return after tFar
   end repeat
   put empty into sSpiders
   repeat with i = 1 to 4
      if i <= sSpiderCount then
         put random(the number of lines of tFar) into tPick
         put line tPick of tFar into tSpot
         if the number of lines of tFar > 1 then delete line tPick of tFar
         put tSpot into sSpiders[i]["home"]
         set the visible of image ("spider" & i) to true
      else
         set the visible of image ("spider" & i) to false
      end if
      set the visible of graphic ("path" & i) to false
   end repeat
   mzRespawn
   mzShowStats
   unlock screen
end mzNewLevel

-- Everyone back to where they started.
command mzRespawn
   local i, tCenter
   put mzCellCenter(sStartCell) into tCenter
   put item 1 of tCenter - 8 into sPX
   put item 2 of tCenter - 8 into sPY
   put empty into sDir
   put empty into sWant
   put 0 into sMoveBank
   put empty into sAuto
   mzDrawPlayerPath
   set the topLeft of image "Lady" to round(sPX), round(sPY)
   mzFace "right"
   set the blendLevel of image "Lady" to 0
   repeat with i = 1 to sSpiderCount
      put sSpiders[i]["home"] into sSpiders[i]["cell"]
      put sSpiders[i]["home"] into sSpiders[i]["next"]
      put empty into sSpiders[i]["aim"]
      put empty into sSpiders[i]["path"]
      put "patrol" into sSpiders[i]["mode"]
      put mzCellCenter(sSpiders[i]["home"]) into tCenter
      put item 1 of tCenter into sSpiders[i]["x"]
      put item 2 of tCenter into sSpiders[i]["y"]
      set the loc of image ("spider" & i) to tCenter
      set the visible of graphic ("path" & i) to false
   end repeat
   put the milliseconds + 1500 into sGraceUntil
end mzRespawn

command mzPlaceAtCell pType, pName, pCell, pSize
   local tCenter
   put mzCellCenter(pCell) into tCenter
   if pType is "graphic" then
      set the width of graphic pName to pSize
      set the height of graphic pName to pSize
      set the loc of graphic pName to tCenter
   end if
end mzPlaceAtCell

function mzCellCenter pCell
   return (kLeft + item 1 of pCell * kTile + kTile div 2) & "," & (kTop + item 2 of pCell * kTile + kTile div 2)
end mzCellCenter

-- The tile under a point of the screen.
function mzCellAt pX, pY
   return ((pX - kLeft) div kTile) & "," & ((pY - kTop) div kTile)
end mzCellAt

function mzPlayerCell
   return mzCellAt(sPX + 8, sPY + 8)
end mzPlayerCell

-- ===================================================================
-- Playing
-- ===================================================================

command mzPlayPause
   switch sState
      case "playing"
         put "paused" into sState
         mzStopTimer
         mzMessage "Paused", "Press Space or tap the maze to go on."
         break
      case "paused"
      case "ready"
         mzHideMessage
         put "playing" into sState
         put the milliseconds into sLast
         put the milliseconds + 1500 into sGraceUntil
         mzStartTick
         break
      case "won"
         add 1 to sLevel
         mzNewLevel mzFreshSeed()
         mzHideMessage
         put "playing" into sState
         put the milliseconds into sLast
         mzStartTick
         break
      default
         -- over: a new game
         put 1 into sLevel
         put 3 into sLives
         put 0 into sScore
         mzNewLevel mzFreshSeed()
         mzHideMessage
         put "playing" into sState
         put the milliseconds into sLast
         mzStartTick
   end switch
   mzShowStats
end mzPlayPause

command mzStartTick
   mzStopTimer
   put the milliseconds into sStatsAt
   put 0 into sHitTests
   put 0 into sSearches
   put 0 into sFrames
   send "mzTick" to me in 16 milliseconds
   put the result into sTimer
end mzStartTick

-- One step of the game.
on mzTick
   local tNow, tDT, i
   put empty into sTimer
   if sState is not "playing" then exit mzTick
   put the milliseconds into tNow
   put min(50, max(0, tNow - sLast)) into tDT
   put tNow into sLast
   lock screen
   mzMovePlayer tDT
   mzCheckLeaves
   if sState is "playing" then mzMoveSpiders tDT
   if sState is "playing" then mzCheckSpiders
   if tNow < sGraceUntil then
      set the blendLevel of image "Lady" to 55 * ((tNow div 120) mod 2)
   else
      set the blendLevel of image "Lady" to 0
   end if
   add 1 to sFrames
   if tNow - sStatsAt >= 1000 then
      put "Each second:" & return & \
            sHitTests && "pixel hit tests" & return & \
            sSearches && "A* path searches" & return & \
            sFrames && "pictures" into field "Stats"
      put tNow into sStatsAt
      put 0 into sHitTests
      put 0 into sSearches
      put 0 into sFrames
   end if
   unlock screen
   if sState is "playing" then
      send "mzTick" to me in 16 milliseconds
      put the result into sTimer
   end if
end mzTick

-- ---------------------------------------------------- the ladybird

-- Does the ladybird touch a hedge if it stands at pX,pY (its top left)?
-- This is the whole collision test: one call to intersect.
function mzBlocked pX, pY
   set the topLeft of image "Lady" to round(pX), round(pY)
   add 1 to sHitTests
   return intersect(image "Lady", image "Hedge", "opaque pixels")
end mzBlocked

function mzDelta pDir
   switch pDir
      case "up"
         return "0,-1"
      case "down"
         return "0,1"
      case "left"
         return "-1,0"
      case "right"
         return "1,0"
   end switch
   return "0,0"
end mzDelta

-- Moves the ladybird one pixel at a time, testing each pixel.
command mzMovePlayer pDT
   local tDelta, tSteps, tFree, tSide, tOff, tCenter, tDone, tNext
   add kPlayerSpeed * pDT / 1000 to sMoveBank
   put trunc(sMoveBank) into tSteps
   subtract tSteps from sMoveBank
   repeat tSteps times
      if sAuto is not empty then
         mzAutoStep
         next repeat
      end if
      -- a turn that was asked for is taken as soon as there is room
      if sWant is not empty and sWant is not sDir then
         put mzDelta(sWant) into tDelta
         if not mzBlocked(sPX + item 1 of tDelta, sPY + item 2 of tDelta) then
            put sWant into sDir
            mzFace sDir
         end if
      end if
      if sDir is empty then exit repeat
      put mzDelta(sDir) into tDelta
      if not mzBlocked(sPX + item 1 of tDelta, sPY + item 2 of tDelta) then
         add item 1 of tDelta to sPX
         add item 2 of tDelta to sPY
      else
         -- slide round a rounded corner: a pixel sideways, toward the
         -- middle of the lane, and on
         put false into tDone
         put mzCellCenter(mzPlayerCell()) into tCenter
         if item 1 of tDelta is 0 then
            put item 1 of tCenter - (sPX + 8) into tOff
         else
            put item 2 of tCenter - (sPY + 8) into tOff
         end if
         if tOff is not 0 then
            put mzSign(tOff) into tSide
            if item 1 of tDelta is 0 then
               if not mzBlocked(sPX + tSide, sPY + item 2 of tDelta) then
                  add tSide to sPX
                  add item 2 of tDelta to sPY
                  put true into tDone
               end if
            else
               if not mzBlocked(sPX + item 1 of tDelta, sPY + tSide) then
                  add item 1 of tDelta to sPX
                  add tSide to sPY
                  put true into tDone
               end if
            end if
         end if
         if not tDone then
            exit repeat
         end if
      end if
   end repeat
   set the topLeft of image "Lady" to round(sPX), round(sPY)
end mzMovePlayer

function mzSign pN
   if pN < 0 then return -1
   if pN > 0 then return 1
   return 0
end mzSign

-- Walking to a tapped spot: toward the middle of the next tile on the
-- path, one pixel at a time (still tested against the hedges).
command mzAutoStep
   local tNext, tCenter, tDX, tDY, tStepX, tStepY
   put line 1 of sAuto into tNext
   put mzCellCenter(tNext) into tCenter
   put item 1 of tCenter - (sPX + 8) into tDX
   put item 2 of tCenter - (sPY + 8) into tDY
   if tDX is 0 and tDY is 0 then
      delete line 1 of sAuto
      mzDrawPlayerPath
      exit mzAutoStep
   end if
   put 0 into tStepX
   put 0 into tStepY
   if abs(tDX) >= abs(tDY) then
      put mzSign(tDX) into tStepX
   else
      put mzSign(tDY) into tStepY
   end if
   if mzBlocked(sPX + tStepX, sPY + tStepY) then
      put empty into sAuto
      mzDrawPlayerPath
      exit mzAutoStep
   end if
   add tStepX to sPX
   add tStepY to sPY
   if tStepX > 0 then mzFace "right"
   if tStepX < 0 then mzFace "left"
   if tStepY > 0 then mzFace "down"
   if tStepY < 0 then mzFace "up"
end mzAutoStep

command mzFace pDir
   if pDir is sFacing then exit mzFace
   put pDir into sFacing
   set the imageData of image "Lady" to sLadyData[pDir]
   set the alphaData of image "Lady" to sLadyData[pDir, "alpha"]
end mzFace

-- The leaves and the gate, caught by pixels too.
command mzCheckLeaves
   local i, tName
   repeat with i = 1 to kLeafCount
      put "leaf" & i into tName
      if not the visible of graphic tName then next repeat
      if not mzNear(the loc of graphic tName, 20) then next repeat
      add 1 to sHitTests
      if intersect(image "Lady", graphic tName, "opaque pixels") then
         set the visible of graphic tName to false
         subtract 1 from sLeaves
         add 10 to sScore
         if sLeaves is 0 then
            set the backgroundColor of graphic "Gate" to "250,204,21"
            set the blendLevel of graphic "Gate" to 0
         end if
         mzShowStats
      end if
   end repeat
   if sLeaves is 0 and mzNear(the loc of graphic "Gate", 20) then
      add 1 to sHitTests
      if intersect(image "Lady", graphic "Gate", "opaque pixels") then
         add 100 * sLevel to sScore
         put "won" into sState
         mzStopTimer
         mzShowStats
         mzMessage "Level" && sLevel && "done!", "Score:" && sScore & return & return & \
               "Press Space or tap the maze for level" && sLevel + 1 & \
               ", with" && min(4, sLevel + 2) && "spiders."
      end if
   end if
end mzCheckLeaves

-- Is the ladybird's middle within pRange pixels of a point?
function mzNear pLoc, pRange
   return abs(item 1 of pLoc - (sPX + 8)) <= pRange and abs(item 2 of pLoc - (sPY + 8)) <= pRange
end mzNear

-- ---------------------------------------------------- the spiders

command mzMoveSpiders pDT
   local i, tSpeed, tStep, tCenter, tDX, tDY, tDist, tFrameNow
   put min(105, 52 + 9 * sLevel) into tSpeed
   put the milliseconds div 140 into tFrameNow
   repeat with i = 1 to sSpiderCount
      put tSpeed * pDT / 1000 into tStep
      repeat while tStep > 0
         put mzCellCenter(sSpiders[i]["next"]) into tCenter
         put item 1 of tCenter - sSpiders[i]["x"] into tDX
         put item 2 of tCenter - sSpiders[i]["y"] into tDY
         put abs(tDX) + abs(tDY) into tDist
         if tDist <= tStep then
            put item 1 of tCenter into sSpiders[i]["x"]
            put item 2 of tCenter into sSpiders[i]["y"]
            subtract tDist from tStep
            put sSpiders[i]["next"] into sSpiders[i]["cell"]
            mzSpiderThink i
            if sSpiders[i]["next"] is sSpiders[i]["cell"] then
               exit repeat
            end if
         else
            add mzSign(tDX) * tStep to sSpiders[i]["x"]
            add mzSign(tDY) * tStep to sSpiders[i]["y"]
            put 0 into tStep
         end if
      end repeat
      set the loc of image ("spider" & i) to round(sSpiders[i]["x"]), round(sSpiders[i]["y"])
      if tFrameNow is not sFrame or sFrameAt is empty then
         set the imageData of image ("spider" & i) to sSpiderData[i, 1 + tFrameNow mod 2]
         set the alphaData of image ("spider" & i) to sSpiderAlpha[i, 1 + tFrameNow mod 2]
      end if
   end repeat
   put tFrameNow into sFrame
   put true into sFrameAt
end mzMoveSpiders

-- A spider at the middle of a tile decides where to go next. It asks
-- A* for the way to the ladybird; if that is short enough (it can
-- "smell" her), it hunts. Otherwise it patrols to a random tile.
-- From level 4 on, every spider always hunts.
command mzSpiderThink pSpider
   local tCell, tPath, tSmell, tTarget
   put sSpiders[pSpider]["cell"] into tCell
   put mzAStar(tCell, mzPlayerCell()) into tPath
   put 8 + 4 * sLevel into tSmell
   if tPath is not empty and (the number of lines of tPath - 1 <= tSmell or sLevel >= 4) then
      put "hunt" into sSpiders[pSpider]["mode"]
   else
      if sSpiders[pSpider]["mode"] is "hunt" or sSpiders[pSpider]["aim"] is empty or sSpiders[pSpider]["aim"] is tCell then
         put line random(the number of lines of sFloorList) of sFloorList into sSpiders[pSpider]["aim"]
      end if
      put "patrol" into sSpiders[pSpider]["mode"]
      put mzAStar(tCell, sSpiders[pSpider]["aim"]) into tPath
   end if
   put tPath into sSpiders[pSpider]["path"]
   if the number of lines of tPath >= 2 then
      put line 2 of tPath into sSpiders[pSpider]["next"]
   else
      put tCell into sSpiders[pSpider]["next"]
   end if
   mzDrawSpiderPath pSpider
end mzSpiderThink

command mzDrawSpiderPath pSpider
   local tPoints, tCell, tName
   put "path" & pSpider into tName
   if not sShowPaths or the number of lines of sSpiders[pSpider]["path"] < 2 then
      set the visible of graphic tName to false
      exit mzDrawSpiderPath
   end if
   put round(sSpiders[pSpider]["x"]) & "," & round(sSpiders[pSpider]["y"]) into tPoints
   repeat for each line tCell in line 2 to -1 of sSpiders[pSpider]["path"]
      put return & mzCellCenter(tCell) after tPoints
   end repeat
   set the points of graphic tName to tPoints
   if sSpiders[pSpider]["mode"] is "hunt" then
      set the lineSize of graphic tName to 3
      set the dashes of graphic tName to empty
   else
      set the lineSize of graphic tName to 2
      set the dashes of graphic tName to "4,5"
   end if
   set the visible of graphic tName to true
end mzDrawSpiderPath

command mzDrawPlayerPath
   local tPoints, tCell
   if sAuto is empty then
      set the visible of graphic "WalkPath" to false
      exit mzDrawPlayerPath
   end if
   put round(sPX + 8) & "," & round(sPY + 8) into tPoints
   repeat for each line tCell in sAuto
      put return & mzCellCenter(tCell) after tPoints
   end repeat
   set the points of graphic "WalkPath" to tPoints
   set the visible of graphic "WalkPath" to true
end mzDrawPlayerPath

-- A spider that touches the ladybird (by pixels) takes a life.
command mzCheckSpiders
   local i
   if the milliseconds < sGraceUntil then exit mzCheckSpiders
   repeat with i = 1 to sSpiderCount
      if not mzNear(sSpiders[i]["x"] & "," & sSpiders[i]["y"], 18) then next repeat
      add 1 to sHitTests
      if intersect(image "Lady", image ("spider" & i), "opaque pixels") then
         mzCaught
         exit repeat
      end if
   end repeat
end mzCheckSpiders

command mzCaught
   subtract 1 from sLives
   mzShowStats
   if sLives <= 0 then
      put "over" into sState
      mzStopTimer
      mzMessage "Caught!", "The spiders got you on level" && sLevel & "." & return & \
            "Score:" && sScore & return & return & "Press Space or tap the maze to play again."
   else
      mzRespawn
   end if
end mzCaught

-- ===================================================================
-- Keys, taps and swipes
-- ===================================================================

on arrowKey pKey
   mzSteer pKey
end arrowKey

on keyDown pKey
   switch toLower(pKey)
      case "w"
         mzSteer "up"
         break
      case "s"
         mzSteer "down"
         break
      case "a"
         mzSteer "left"
         break
      case "d"
         mzSteer "right"
         break
      case space
         mzPlayPause
         break
      case "n"
         mzNewMaze
         break
      case "p"
         set the hilite of button "Show paths" to not the hilite of button "Show paths"
         mzSetShowPaths the hilite of button "Show paths"
         break
      default
         pass keyDown
   end switch
end keyDown

on returnKey
   if sState is not "playing" then mzPlayPause
end returnKey

command mzSteer pDir
   if sState is not "playing" then exit mzSteer
   put empty into sAuto
   mzDrawPlayerPath
   put pDir into sWant
   if sDir is empty then
      put pDir into sDir
      mzFace pDir
   end if
end mzSteer

on mouseDown
   if the mouseLoc is within the rect of image "Hedge" and word 1 of the name of the target is not "button" then
      put the mouseLoc into sDownAt
   else
      put empty into sDownAt
      pass mouseDown
   end if
end mouseDown

on mouseUp
   local tDX, tDY, tLoc, tName
   put the short name of the target into tName
   if word 1 of the name of the target is "button" then
      switch tName
         case "Play"
            mzPlayPause
            break
         case "New maze"
            mzNewMaze
            break
         case "Show paths"
            mzSetShowPaths the hilite of button "Show paths"
            break
      end switch
      exit mouseUp
   end if
   if sDownAt is empty then pass mouseUp
   put the mouseLoc into tLoc
   put item 1 of tLoc - item 1 of sDownAt into tDX
   put item 2 of tLoc - item 2 of sDownAt into tDY
   if sState is not "playing" then
      put empty into sDownAt
      mzPlayPause
      exit mouseUp
   end if
   if max(abs(tDX), abs(tDY)) < 16 then
      mzWalkTo item 1 of sDownAt, item 2 of sDownAt
   else if abs(tDX) > abs(tDY) then
      if tDX > 0 then
         mzSteer "right"
      else
         mzSteer "left"
      end if
   else
      if tDY > 0 then
         mzSteer "down"
      else
         mzSteer "up"
      end if
   end if
   put empty into sDownAt
end mouseUp

on mouseRelease
   put empty into sDownAt
end mouseRelease

-- A tap: the ladybird walks to that tile along the path A* finds.
command mzWalkTo pX, pY
   local tGoal, tPath, tCenter
   put mzCellAt(pX, pY) into tGoal
   if mzIsWall(item 1 of tGoal, item 2 of tGoal) then exit mzWalkTo
   put mzAStar(mzPlayerCell(), tGoal) into tPath
   if tPath is empty then exit mzWalkTo
   put empty into sDir
   put empty into sWant
   -- the tile it stands on is the first line: it walks to its middle first
   put tPath into sAuto
   mzDrawPlayerPath
end mzWalkTo

command mzNewMaze
   mzStartLevel 1
end mzNewMaze

-- A new game at a level, waiting for Space. (Level 4 and up: every
-- spider always hunts.)
command mzStartLevel pLevel
   mzStopTimer
   put max(1, pLevel) into sLevel
   put 3 into sLives
   put 0 into sScore
   mzNewLevel mzFreshSeed()
   put "ready" into sState
   mzMessage "A new maze", "Level" && sLevel & "." & return & "Press Space or tap the maze to start."
end mzStartLevel

command mzSetShowPaths pOn
   local i
   put (pOn is true) into sShowPaths
   repeat with i = 1 to 4
      if i <= sSpiderCount then
         mzDrawSpiderPath i
      else
         set the visible of graphic ("path" & i) to false
      end if
   end repeat
end mzSetShowPaths

-- ===================================================================
-- The panel and the messages
-- ===================================================================

command mzShowStats
   put sLevel into field "LevelValue"
   put (kLeafCount - sLeaves) & " / " & kLeafCount into field "LeavesValue"
   put sLives into field "LivesValue"
   put sScore into field "ScoreValue"
   if sState is "playing" then
      set the label of button "Play" to "Pause"
   else
      set the label of button "Play" to "Play"
   end if
end mzShowStats

command mzMessage pTitle, pText
   put pTitle into field "OverTitle"
   put pText into field "OverText"
   set the visible of group "Over" to true
   mzShowStats
end mzMessage

command mzHideMessage
   set the visible of group "Over" to false
end mzHideMessage

-- ===================================================================
-- Building the card (run once, when the stack file is made)
-- ===================================================================

command mzBuildUI
   local i, tColour
   set the name of this stack to "Ladybird Maze"
   set the title of this stack to "Ladybird Maze"
   set the width of this stack to 940
   set the height of this stack to 612
   set the resizable of this stack to false
   set the backgroundColor of this stack to "17,24,39"
   set the defaultStack to the short name of this stack
   repeat while the number of controls of this card > 0
      delete control 1 of this card
   end repeat
   mzField "Title", "Ladybird Maze", 20, 14, 600, 50, 28, "bold", "250,250,250"
   mzField "Sub", "Pixel-perfect collision with intersect, and spiders that hunt with A* pathfinding.", \
         21, 50, 720, 76, 14, "plain", "148,163,184"
   create graphic "Soil"
   set the style of graphic "Soil" to "rectangle"
   set the filled of graphic "Soil" to true
   set the lineSize of graphic "Soil" to 0
   set the backgroundColor of graphic "Soil" to "66,48,34"
   set the rect of graphic "Soil" to kLeft, kTop, kLeft + kCols * kTile, kTop + kRows * kTile
   create graphic "Gate"
   set the style of graphic "Gate" to "roundrect"
   set the roundRadius of graphic "Gate" to 6
   set the filled of graphic "Gate" to true
   set the lineSize of graphic "Gate" to 0
   repeat with i = 1 to kLeafCount
      create graphic ("leaf" & i)
      set the style of graphic ("leaf" & i) to "oval"
      set the filled of graphic ("leaf" & i) to true
      set the lineSize of graphic ("leaf" & i) to 1
      set the foregroundColor of graphic ("leaf" & i) to "77,124,15"
      set the backgroundColor of graphic ("leaf" & i) to "163,230,53"
   end repeat
   create image "Hedge"
   repeat with i = 1 to 4
      create graphic ("path" & i)
      set the style of graphic ("path" & i) to "polygon"
      set the filled of graphic ("path" & i) to false
      set the foregroundColor of graphic ("path" & i) to mzPick(kPathColours, i)
      set the visible of graphic ("path" & i) to false
   end repeat
   create graphic "WalkPath"
   set the style of graphic "WalkPath" to "polygon"
   set the filled of graphic "WalkPath" to false
   set the lineSize of graphic "WalkPath" to 2
   set the dashes of graphic "WalkPath" to "2,4"
   set the foregroundColor of graphic "WalkPath" to "255,255,255"
   set the visible of graphic "WalkPath" to false
   create image "Lady"
   set the width of image "Lady" to 16
   set the height of image "Lady" to 16
   repeat with i = 1 to 4
      create image ("spider" & i)
      set the width of image ("spider" & i) to 18
      set the height of image ("spider" & i) to 18
   end repeat
   -- the panel
   mzField "LevelLabel", "Level", 736, 90, 826, 110, 13, "plain", "148,163,184"
   mzField "LevelValue", "1", 736, 108, 826, 140, 24, "bold", "250,250,250"
   mzField "LivesLabel", "Lives", 830, 90, 920, 110, 13, "plain", "148,163,184"
   mzField "LivesValue", "3", 830, 108, 920, 140, 24, "bold", "244,114,182"
   mzField "LeavesLabel", "Leaves", 736, 146, 826, 166, 13, "plain", "148,163,184"
   mzField "LeavesValue", "0 / 8", 736, 164, 826, 196, 24, "bold", "163,230,53"
   mzField "ScoreLabel", "Score", 830, 146, 920, 166, 13, "plain", "148,163,184"
   mzField "ScoreValue", "0", 830, 164, 920, 196, 24, "bold", "250,204,21"
   mzButton "Play", 736, 210, 920, 244
   mzButton "New maze", 736, 252, 920, 286
   create button "Show paths"
   set the style of button "Show paths" to "checkbox"
   set the rect of button "Show paths" to 736, 296, 920, 322
   set the textColor of button "Show paths" to "226,232,240"
   set the textSize of button "Show paths" to 14
   set the hilite of button "Show paths" to false
   set the showBorder of button "Show paths" to false
   mzField "Stats", "Each second:" & return & "0 pixel hit tests" & return & "0 A* path searches" & return & "0 pictures", \
         736, 334, 920, 410, 13, "plain", "148,163,184"
   mzField "Help", "Arrow keys or WASD steer." & return & "Space pauses, N new maze," & return & "P shows paths." & return & return & \
         "Phone: swipe to steer," & return & "tap a spot to walk there.", 736, 424, 920, 540, 13, "plain", "148,163,184"
   -- the message over the maze
   create graphic "OverBack"
   set the style of graphic "OverBack" to "roundrect"
   set the roundRadius of graphic "OverBack" to 16
   set the filled of graphic "OverBack" to true
   set the backgroundColor of graphic "OverBack" to "15,23,42"
   set the foregroundColor of graphic "OverBack" to "250,204,21"
   set the lineSize of graphic "OverBack" to 2
   set the blendLevel of graphic "OverBack" to 8
   set the rect of graphic "OverBack" to 148, 220, 588, 452
   mzField "OverTitle", "", 160, 236, 576, 280, 26, "bold", "250,204,21"
   set the textAlign of field "OverTitle" to "center"
   mzField "OverText", "", 170, 286, 566, 444, 15, "plain", "226,232,240"
   set the textAlign of field "OverText" to "center"
   select empty
   group graphic "OverBack" and field "OverTitle" and field "OverText"
   set the name of the last group to "Over"
   set the visible of group "Over" to false
   put empty into sState
end mzBuildUI

command mzField pName, pText, pL, pT, pR, pB, pSize, pStyle, pColour
   create field pName
   set the rect of field pName to pL, pT, pR, pB
   set the lockText of field pName to true
   set the traversalOn of field pName to false
   set the opaque of field pName to false
   set the showBorder of field pName to false
   set the dontWrap of field pName to false
   set the textSize of field pName to pSize
   set the textStyle of field pName to pStyle
   set the textColor of field pName to pColour
   put pText into field pName
end mzField

command mzButton pName, pL, pT, pR, pB
   create button pName
   set the rect of button pName to pL, pT, pR, pB
   set the textSize of button pName to 15
   set the textStyle of button pName to "bold"
end mzButton

-- ===================================================================
-- Self test (for the people who look after this stack; returns lines
-- that start with PASS or FAIL)
-- ===================================================================

function mzSelfTest
   local tOut, tSeed, tDist, tCount, tA, tB, tPath, tLine, tPrev, tOK, i, tCell, tFails, tPair
   put 0 into tFails
   repeat for each item tSeed in "1,77,2026"
      mzMakeMaze tSeed
      -- every path tile is reachable from the start, and the border is hedge
      put mzDistances("1,1") into tDist
      put the number of lines of the keys of tDist into tCount
      put mzCheck(tCount = the number of lines of sFloorList, "seed" && tSeed & ": all" && tCount && "path tiles joined") after tOut
      put true into tOK
      repeat with i = 0 to kCols - 1
         if not sWall[i, 0] or not sWall[i, kRows - 1] then put false into tOK
      end repeat
      repeat with i = 0 to kRows - 1
         if not sWall[0, i] or not sWall[kCols - 1, i] then put false into tOK
      end repeat
      put mzCheck(tOK, "seed" && tSeed & ": the border is all hedge") after tOut
      -- A* agrees with the flood fill on 40 pairs, and every step is real
      set the randomSeed to tSeed
      put true into tOK
      repeat 40 times
         put line random(the number of lines of sFloorList) of sFloorList into tA
         put line random(the number of lines of sFloorList) of sFloorList into tB
         put mzDistances(tA) into tDist
         put mzAStar(tA, tB) into tPath
         if the number of lines of tPath - 1 is not tDist[tB] then
            put false into tOK
            put "  A* from" && tA && "to" && tB && "took" && the number of lines of tPath - 1 && "steps, shortest is" && tDist[tB] & return after tOut
         end if
         if line 1 of tPath is not tA or line -1 of tPath is not tB then put false into tOK
         put empty into tPrev
         repeat for each line tLine in tPath
            if mzIsWall(item 1 of tLine, item 2 of tLine) then put false into tOK
            if tPrev is not empty and abs(item 1 of tLine - item 1 of tPrev) + abs(item 2 of tLine - item 2 of tPrev) is not 1 then put false into tOK
            put tLine into tPrev
         end repeat
      end repeat
      put mzCheck(tOK, "seed" && tSeed & ": A* finds a shortest path, through paths only, 40 times") after tOut
   end repeat
   -- no way through: a wall as the goal, and a sealed-in tile
   put mzCheck(mzAStar("1,1", "0,0") is empty, "A* gives no path to a hedge tile") after tOut
   put false into sWall[kCols - 2, kRows - 2]
   put true into sWall[kCols - 3, kRows - 2]
   put true into sWall[kCols - 2, kRows - 3]
   put mzCheck(mzAStar("1,1", (kCols - 2) & "," & (kRows - 2)) is empty, "A* gives no path to a sealed-in tile") after tOut
   put mzCheck(mzAStar("1,1", "1,1") is "1,1", "A* from a tile to itself is that one tile") after tOut
   -- collision by pixels, on a real maze
   mzMakeMaze 5
   mzDrawHedges
   put mzCellCenter("1,1") into tCell
   put mzCheck(not mzBlocked(item 1 of tCell - 8, item 2 of tCell - 8), "the ladybird fits in the middle of a path tile") after tOut
   put mzCellCenter("0,0") into tCell
   put mzCheck(mzBlocked(item 1 of tCell - 8, item 2 of tCell - 8), "the ladybird on a hedge tile is blocked") after tOut
   put mzCellCenter("1,1") into tCell
   -- (the gap is 4 pixels, and the round ladybird has a clear pixel at its edge)
   put mzCheck(not mzBlocked(item 1 of tCell - 8 - 5, item 2 of tCell - 8), "five pixels left of the middle is still free") after tOut
   put mzCheck(mzBlocked(item 1 of tCell - 8 - 6, item 2 of tCell - 8), "six pixels left of the middle touches the hedge") after tOut
   -- the rounded corner: where bounds overlap but no pixel does
   put mzRoundedCornerCase() into tPair
   put mzCheck(tPair is not empty, "a rounded hedge corner was found") after tOut
   if tPair is not empty then
      set the topLeft of image "Lady" to item 1 to 2 of tPair
      put mzCheck(intersect(image "Lady", image "Hedge", "opaque pixels") is false and \
            item 3 of tPair is true, \
            "at a rounded corner the boxes overlap but no pixels do") after tOut
   end if
   repeat for each line tLine in tOut
      if word 1 of tLine is "FAIL" then add 1 to tFails
   end repeat
   -- a fresh game again
   put 1 into sLevel
   put 3 into sLives
   put 0 into sScore
   mzNewLevel mzFreshSeed()
   return tOut & "RESULT" && tFails && "failed"
end mzSelfTest

function mzCheck pOK, pWhat
   if pOK is true then return "PASS" && pWhat & return
   return "FAIL" && pWhat & return
end mzCheck

-- A spot for the ladybird beside a rounded hedge corner, so that its
-- box reaches into the corner's box but none of its pixels touch.
function mzRoundedCornerCase
   local tC, tR, tCenter, tX, tY, tBoxes
   repeat with tC = 1 to kCols - 2
      repeat with tR = 1 to kRows - 2
         if sWall[tC, tR] and not mzIsWall(tC, tR - 1) and not mzIsWall(tC - 1, tR) and not mzIsWall(tC - 1, tR - 1) then
            -- the ladybird in the path tile up and to the left, nudged in
            put mzCellCenter((tC - 1) & "," & (tR - 1)) into tCenter
            put item 1 of tCenter - 8 + 7 into tX
            put item 2 of tCenter - 8 + 7 into tY
            set the topLeft of image "Lady" to tX, tY
            -- its box reaches into the corner tile's square...
            put tX + 16 > kLeft + tC * kTile and tY + 16 > kTop + tR * kTile into tBoxes
            -- ...but none of its pixels touch a hedge pixel
            if tBoxes and not intersect(image "Lady", image "Hedge", "opaque pixels") then return tX & "," & tY & "," & tBoxes
         end if
      end repeat
   end repeat
   return empty
end mzRoundedCornerCase