一个用来测试正确的尾调用的迷宫小游戏

-- 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的堆栈
无语

开源是一种精神

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值