各位看官,原版请移步下面链接,代码转载自:
https://blog.csdn.net/qinyuanpei/article/details/44279585
debug = true
--定义窗口宽度和高度
local w=640
local h=640
--定义网格单元大小
local unitSize=20;
--方块的初始位置
local initX=320
local initY=320
--贪吃蛇集合
local snakes={}
--食物状态
--WaitToEat:绘制食物
--BeEated:随机生成食物
local foodState="WaitToEat"
--游戏状态
--0:游戏结束
--1:游戏正常
local gameState=1
--食物的位置
local foodX=0
local foodY=0
--移动方向
local dir=1
local fpstotal=0;
function love.load(arg)
love.graphics.setLineWidth(0.1)
love.graphics.setLineStyle("smooth")
--蛇的初始化(蛇的长度为5)
for i=1,5 do
snake={}
snake.x=initX +(i-1) * 20
snake.y=initY
snakes[i]=snake
end
--食物初始化
foodX=love.math.random(32-1)*20
foodY=love.math.random(32-1)*20
end
function love.update(dt)
--print(dt)
fpstotal=fpstotal+dt;
if fpstotal<=0.3 then return end
fpstotal=0
-- if love.timer then love.timer.sleep(0.3) end
--判断游戏状态
if(snakes[1].x<=0 or snakes[1].x>=640 or snakes[1].y<=0 or snakes[1].y>=640) then
gameState=0
else
gameState=1
end
--如果游戏状态为正常
if(gameState==1) then
SnakeUpdate()
FoodUpdate()
end
end
function love.draw(dt)
love.graphics.setColor(128,128,0,255)
--绘制横线
for i=0,w,unitSize do
love.graphics.line(0,i,h,i)
end
--绘制竖线
for j=0,h,unitSize do
love.graphics.line(j,0,j,w)
end
--绘制蛇
for i=1,table.maxn(snakes) do
love.graphics.setColor(255,0,0,100)
love.graphics.rectangle("fill",snakes[i].x,snakes[i].y,20,20)
end
--绘制食物
if(foodState=="WaitToEat") then
love.graphics.setColor(255,0,0,255)
love.graphics.rectangle("fill",foodX,foodY,20,20)
end
--如果游戏结束则显示GameOver
if(gameState==0) then
love.graphics.setColor(255,0,0,255)
love.graphics.print("Game Over",250,300)
end
love.graphics.setColor(0,255,0,255)
love.graphics.print("Current FPS: "..tostring(love.timer.getFPS( )), 10, 10)
end
--随机生成食物
function FoodUpdate()
--如果食物被蛇吃掉则重新生成食物
if(foodState=="BeEated") then
foodX=love.math.random(32-1)*20
foodY=love.math.random(32-1)*20
foodState="WaitToEat"
end
end
--根据玩家按下的键位定义不同的方向
function love.keypressed(key)
if(key=="a" and dir~=3) then
dir=2
end
if(key=="d" and dir~=2) then
dir=3
end
if(key=="w" and dir~=1) then
dir=0
end
if(key=="s" and dir~=0) then
dir=1
end
end
--核心算法——蛇的移动
function SnakeUpdate()
--获取元素个数
local n=table.maxn(snakes)
if(table.maxn(snakes)>0) then
if(getNextPoint().x==foodX and getNextPoint().y==foodY) then
--将下一个目标点的位置插入表中
table.insert(snakes, 1, getNextPoint())
--将食物状态设置为BeEated
foodState="BeEated"
else
--将下一个目标点的位置插入表中
table.insert(snakes, 1, getNextPoint())
--移除最后一个元素
table.remove(snakes,n+1)
end
end
end
function getNextPoint()
--计算下一个目标点
snake={}
if(dir==0) then
snake.x=snakes[1].x
snake.y=snakes[1].y-20
end
if(dir==1) then
snake.x=snakes[1].x
snake.y=snakes[1].y+20
end
if(dir==2) then
snake.x=snakes[1].x-20
snake.y=snakes[1].y
end
if(dir==3) then
snake.x=snakes[1].x+20
snake.y=snakes[1].y
end
return snake
end