wangy 发表于 2021-7-1 08:45:44

【lua教程】生成迷宫

require "import"
import "android.app.*"
import "android.os.*"
import "android.util.*"
import "android.view.*"
import "android.content.*"
import "android.graphics.*"
activity.setTitle('Androlua迷宫生成')
activity.setTheme(android.R.style.Theme_DeviceDefault_Light)--设置md主题
--迷宫生成算法:https://github.com/joewing/maze
--修改成Androlua:落叶似秋

--初始化迷宫
function init_maze(width, height)
local result = {}
for y = 0, height - 1 do
    for x = 0, width - 1 do
      result = 1
    end
    result = 0
    result = 0
end
for x = 0, width - 1 do
    result = 0
    result[(height - 1) * width + x] = 0
end
return result
end

-- 画迷宫
function draw_maze(canvas,maze, width, height)

local x1,y1,rectW,rectH=0,0,10,10
local paint=Paint()
paint.setColor(Color.BLACK)

for y = 0, height - 1 do
    for x = 0, width - 1 do
      if maze == 0 then

      x1=x1+rectW
       else
      --画矩形
      canvas.drawRect(x1,y1,x1+rectW,y1+rectH,paint)
      x1=x1+rectW
      end
    end
    y1=y1+rectH
    x1=0
end
end

-- 从x,y打通路
function carve_maze(maze, width, height, x, y)
local r = math.random(0, 3)
maze = 0
for i = 0, 3 do
    local d = (i + r) % 4
    local dx = 0
    local dy = 0
    if d == 0 then
      dx = 1
   elseif d == 1 then
      dx = -1
   elseif d == 2 then
      dy = 1
   else
      dy = -1
    end
    local nx = x + dx
    local ny = y + dy
    local nx2 = nx + dx
    local ny2 = ny + dy
    if maze == 1 then
      if maze == 1 then
      maze = 0
      carve_maze(maze, width, height, nx2, ny2)
      end
    end
end
end

--以下为Android绘图相关
local surface = SurfaceView(activity)

local callback=SurfaceHolder_Callback{
surfaceChanged=function(holder,format,width,height)
end,
surfaceCreated=function(holder)

    --local width=surface.getWidth()-1
    -- local height=surface.getHeight()-1
    -- 迷宫的高宽,都必须为奇数
    local width = 71
    local height = 71


    local maze = init_maze(width, height)
    carve_maze(maze, width, height, 2, 2)
    maze = 0
    maze[(height - 2) * width + width - 3] = 0


    canvas=sfh.lockCanvas()
    canvas.drawColor(Color.WHITE)
    draw_maze(canvas,maze,width,height)

    if canvas~=nil then
      sfh.unlockCanvasAndPost(canvas)
    end
end,
surfaceDestroyed=function(holder)
end
}
sfh=surface.getHolder()
sfh.addCallback(callback)
activity.setContentView(surface)
页: [1]
查看完整版本: 【lua教程】生成迷宫