So the square wanders randomly around, and every once in awhile complains about being lost.
Code: Select all
-- tutorial.gridlock
-- from https://love2d.org/wiki/Tutorial:Gridlocked_Player
function love.load()
math.randomseed(os.time())
interval = 2
tick = 0
player = {
grid_x = 256,
grid_y = 256,
act_x = 200,
act_y = 200,
rand_number = 0,
speed = 10,
text = ""
}
map = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
{ 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
}
end
function love.update(dt)
player.act_y = player.act_y - ((player.act_y - player.grid_y) * player.speed * dt)
player.act_x = player.act_x - ((player.act_x - player.grid_x) * player.speed * dt)
tick = tick + dt
if tick > interval then
--Here you call the function ,generate random number and all that stuff
wander()
tick = 0
end
end
function love.draw()
love.graphics.print("Our random number is (" .. player.rand_number .. ")", 500, 500)
if player.text ~= "" then
love.graphics.print(player.text, 500, 550)
end
love.graphics.rectangle("fill", player.act_x, player.act_y, 32, 32)
for y=1, #map do
for x=1, #map[y] do
if map[y][x] == 1 then
love.graphics.rectangle("line", x * 32, y * 32, 32, 32)
end
end
end
end
function love.keypressed(key)
if key == "up" then
if testMap(0, -1) then
player.grid_y = player.grid_y - 32
end
elseif key == "down" then
if testMap(0, 1) then
player.grid_y = player.grid_y + 32
end
elseif key == "left" then
if testMap(-1, 0) then
player.grid_x = player.grid_x - 32
end
elseif key == "right" then
if testMap(1, 0) then
player.grid_x = player.grid_x + 32
end
end
end
function testMap(x, y)
if map[(player.grid_y / 32) + y][(player.grid_x / 32) + x] == 1 then
return false
end
return true
end
function wander()
player.rand_number = math.random(100)
if player.rand_number < 99 then
-- do something
rand2 = math.random(4)
if rand2 == 1 then
if testMap(0, -1) then
player.grid_y = player.grid_y - 32
end
elseif rand2 == 2 then
if testMap(0, 1) then
player.grid_y = player.grid_y + 32
end
elseif rand2 == 3 then
if testMap(-1, 0) then
player.grid_x = player.grid_x - 32
end
elseif rand2 == 4 then
if testMap(1, 0) then
player.grid_x = player.grid_x + 32
end
end
if player.rand_number < 20 then
player.text = "Man, I am SO lost!"
else player.text = ""
end
end
end