Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Maze Generation Using Depth-First Search
- local width, height = 20, 20
- local maze = {}
- local visited = {}
- for y = 1, height do
- maze[y] = {}
- visited[y] = {}
- for x = 1, width do
- maze[y][x] = 1 -- 1 = wall
- visited[y][x] = false
- end
- end
- local directions = {
- {x = 2, y = 0},
- {x = -2, y = 0},
- {x = 0, y = 2},
- {x = 0, y = -2}
- }
- function generateMaze(x, y)
- visited[y][x] = true
- maze[y][x] = 0 -- 0 = path
- local shuffled = {}
- for i = 1, #directions do
- shuffled[i] = directions[i]
- end
- for i = #shuffled, 2, -1 do
- local j = math.random(i)
- shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
- end
- for _, dir in ipairs(shuffled) do
- local nx, ny = x + dir.x, y + dir.y
- local mx, my = x + dir.x / 2, y + dir.y / 2
- if nx > 0 and ny > 0 and nx <= width and ny <= height and not visited[ny][nx] then
- maze[my][mx] = 0
- generateMaze(nx, ny)
- end
- end
- end
- math.randomseed(os.time())
- generateMaze(2, 2)
- -- Player and goal
- local playerX, playerY = 2, 2
- local goalX, goalY = width - 1, height - 1
- -- Limited view settings
- local viewWidth, viewHeight = 10, 10
- -- Function to draw the maze with player centered
- function drawMaze()
- term.clear()
- local startX = math.max(1, playerX - math.floor(viewWidth / 2))
- local startY = math.max(1, playerY - math.floor(viewHeight / 2))
- local endX = math.min(width, playerX + math.floor(viewWidth / 2))
- local endY = math.min(height, playerY + math.floor(viewHeight / 2))
- -- Adjust for view dimensions
- local viewXStart = math.max(1, playerX - math.floor(viewWidth / 2))
- local viewYStart = math.max(1, playerY - math.floor(viewHeight / 2))
- for y = startY, endY do
- for x = startX, endX do
- local screenX = x - viewXStart + 1
- local screenY = y - viewYStart + 1
- if x == playerX and y == playerY then
- term.setCursorPos(screenX, screenY)
- term.write("P") -- Player
- elseif x == goalX and y == goalY then
- term.setCursorPos(screenX, screenY)
- term.write("G") -- Goal
- elseif maze[y][x] == 1 then
- term.setCursorPos(screenX, screenY)
- term.write("#") -- Wall
- else
- term.setCursorPos(screenX, screenY)
- term.write(" ") -- Path
- end
- end
- end
- end
- -- Function to move the player
- function movePlayer(dx, dy)
- local newX = playerX + dx
- local newY = playerY + dy
- if newX > 0 and newX <= width and newY > 0 and newY <= height and maze[newY][newX] == 0 then
- playerX = newX
- playerY = newY
- end
- end
- -- Main game loop
- while true do
- drawMaze()
- local event, key = os.pullEvent("key")
- if key == keys.w then
- movePlayer(0, -1)
- elseif key == keys.s then
- movePlayer(0, 1)
- elseif key == keys.a then
- movePlayer(-1, 0)
- elseif key == keys.d then
- movePlayer(1, 0)
- end
- if playerX == goalX and playerY == goalY then
- term.clear()
- print("Congratulations, you won!")
- break
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement