-- local map = {
-- {1,1,0,0,0,0,0,0,0,0},
-- {0,1,1,0,0,0,0,0,0,0},
-- {0,0,1,0,0,0,0,0,0,0},
-- {0,0,0,1,1,0,0,0,0,0},
-- {0,0,0,0,1,1,0,0,0,0},
-- {0,0,0,0,0,1,1,0,0,0},
-- {0,0,0,0,0,0,1,1,0,0},
-- {0,0,0,0,0,0,0,1,1,0},
-- {0,0,0,0,0,0,0,0,1,1},
-- {0,0,0,0,0,0,0,0,0,2},
-- }
local map = {
{1,1,0,0,0},
{0,1,0,0,0},
{0,1,0,0,0},
{0,1,1,1,1},
{0,0,0,0,2},
}
-- local map = {
-- {1,0,0},
-- {1,0,0},
-- {2,0,0},
-- }
local left = 1
local right = #map[1]
local up = 1
local down = #map
local exit = 2;
local count = 0;
local Dir = {
up = 1,
down = 2,
left = 3,
right = 4,
}
local beginTime = os.time();
math.randomseed(os.time());
function GetDir()
return math.random(Dir.up,Dir.right);
end
function CheckReach(x,y)
print("Pos("..x..","..y..")")
count = count + 1
if(count > 200)then
print("不跑了,累死了")
return;
end
local value = map[x][y];
local reach = (value == exit);
if(reach == true)then
print("出来了,用了"..count.."步".."耗时".. os.time() - beginTime .."秒")
return
end
if(value ~= 1)then
if(map[x - 1] ~= nil and map[x - 1][y] == 1)then
return TurnUp(x -1 ,y);
end
if(map[x + 1] ~= nil and map[x + 1][y] == 1)then
return TurnDown(x +1 ,y);
end
if(map[x][y - 1] == 1)then
return TurnLeft(x ,y - 1);
end
if(map[x][y + 1] == 1)then
return TurnRight(x ,y + 1);
end
end
local move = GetDir();
if(move == Dir.up)then
return TurnUp(x- 1,y);
elseif(move == Dir.down)then
return TurnDown(x +1 ,y);
elseif(move == Dir.left)then
return TurnLeft(x,y -1);
else
return TurnRight(x,y+1);
end
end
function TurnUp(x,y)
print("↑")
if(x < up)then
return TurnDown(x + 1,y)
end
return CheckReach(x,y);
end
function TurnDown(x,y)
print("↓")
if(x > down)then
return TurnUp(x - 1,y)
end
return CheckReach(x,y);
end
function TurnLeft(x,y)
print("←")
if(y < left)then
return TurnRight(x,y + 1)
end
return CheckReach(x,y);
end
function TurnRight(x,y)
print("→")
if(y > right)then
return TurnLeft(x,y - 1)
end
return CheckReach(x,y);
end
CheckReach(1,1)
上面的代码很简单,在学到lua的尾调用的时候,写来玩,测一下堆栈会不会爆
然而写完这个小游戏后,发现不知道怎么查看lua的堆栈
无语
开源是一种精神