lua简单小游戏(贪吃蛇)

lua语言贪吃蛇

vscode中的lua端口运行程序

local width=10

local heigth=10

local snake={{x=2,y=8}}

local direction="right"

--生成食物

local function generateFood()

    local x=math.random(2,width)

    local y=math.random(2,heigth)

    for _, body in ipairs(snake) do

        if body.x==x and body.y==y then

            return generateFood()

        end

    end

    return {x=x,y=y}

end

local food=generateFood()

--渲染游戏界面

local function render()

    for y = 1, heigth+1, 1 do

        for x = 1, width+1, 1 do

            local isSnakeBody=false

            for _, body in ipairs(snake) do

                if body.x==x and body.y==y then

                    if x~=1 and x~=width+1 and y~=1 and y~=heigth+1 then

                        isSnakeBody=true

                        break

                    end

                end

            end

            if isSnakeBody then

                io.write("* ")

            elseif food.x==x and food.y==y then

                io.write("o ")

            elseif x==1 or x==width+1 or y==1 or y==heigth+1 then

                io.write("□ ")

            else

                io.write("  ")

            end

        end

        io.write("\n")

    end

end

---移动

local function move()

    local head=snake[1]

    local newhead={}

    if direction=="right" then

        newhead={x=head.x+1,y=head.y}

    elseif direction=="left" then

        newhead={x=head.x-1,y=head.y}

    elseif direction=="up" then

        newhead={x=head.x,y=head.y-1}

    elseif direction=="down" then

        newhead={x=head.x,y=head.y+1}

    end

    if newhead.x<1 or newhead.x>width or newhead.y<1 or newhead.y>heigth then

        return false

    end

    for _, body in ipairs(snake) do

        if body.x==newhead.x and body.y==newhead.y then

            return false

        end

    end

    table.insert(snake,1,newhead)

    if food.x==newhead.x and food.y==newhead.y then

        food=generateFood()

    else

        table.remove(snake)

    end

    return true

end

while true do

    render()

    local input=io.read()

    if input=="w" and direction~="down" then

        direction="up"

    elseif input=="s" and direction~="up" then

        direction="down"

    elseif input=="a" and direction~="right" then

        direction="left"

    elseif input=="d" and direction~="left" then

        direction="right"

    end

    if not move() then

        break;

    end

end

print("GameOver")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值