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")