先上效果图:
![17d7f6506b69331d30bb985836e36dc6.gif](https://img-blog.csdnimg.cn/img_convert/17d7f6506b69331d30bb985836e36dc6.gif)
代码:function love.load() snake = {}--用二维数组表示蛇--for i = 1, 3 dotable.insert(snake, {x = i * 31, y = 0, w = 30, h = 30})endsnakeTime = 5 --控制蛇速度的变量--direction = { "right" } --方向table--food = {} --食物--index = 0 --索引--score = 0 --分数--foodInit() --初始化食物--endfunction love.update(dt)if snakeTime < 0 thenfor i = 1, #snake - 1 dosnake[i].x = snake[i + 1].xsnake[i].y = snake[i + 1].yendif direction[#direction] == "right" thensnake[#snake].x = snake[#snake].x + 31snake[#snake].y = snake[#snake].y + 0elseif direction[#direction] == "left" thensnake[#snake].x = snake[#snake].x - 31snake[#snake].y = snake[#snake].y + 0elseif direction[#direction] == "up" thensnake[#snake].x = snake[#snake].x + 0snake[#snake].y = snake[#snake].y - 31elseif direction[#direction] == "down" thensnake[#snake].x = snake[#snake].x + 0snake[#snake].y = snake[#snake].y + 31endif #direction > 1 thentable.remove(direction, #direction)endsnakeTime = 5elsesnakeTime = snakeTime - 1endif snake[#snake].x > 620 thensnake[#snake].x = 0endif snake[#snake].x < 0 thensnake[#snake].x = 620 endif snake[#snake].y > 620 thensnake[#snake].y = 0endif snake[#snake].y < 0 thensnake[#snake].y = 620endcollision()endfunction love.draw() for k, v in ipairs(snake) dolove.graphics.rectangle("fill", v.x, v.y, v.w, v.h)endlove.graphics.setColor(255, 0, 0, 255)love.graphics.rectangle("fill", food[index].x, food[index].y, food[index].w, food[index].h)love.graphics.setColor(255, 255, 255, 255)love.graphics.print("score: "..score, 540, 0)endfunction love.keypressed(key)if key == "right" and direction[#direction] ~= "left" thentable.insert(direction, 1, "right")elseif key == "left" and direction[#direction] ~= "right" thentable.insert(direction, 1, "left")elseif key == "up" and direction[#direction] ~= "down" thentable.insert(direction, 1, "up")elseif key == "down" and direction[#direction] ~= "up" thentable.insert(direction, 1, "down")endend--食物生成--function foodInit() for i = 0, 589 / 31 dofor j = 0, 589 / 31 dopossible = truefor m = 1, #snake doif snake[m].x / 31== i and snake[m].y / 31 == j thenpossible = falseendendif possible thentable.insert(food, {x = i * 31, y = j * 31, w = 30, h = 30})endendendindex = love.math.random(#food)endfunction collision() if snake[#snake].x == food[index].x and snake[#snake].y == food[index].y thenscore = score + 1table.insert(snake, {x = food[index].x, y = food[index].y, w = 30, h = 30})foodInit()endend
碰撞实现(蛇吃食物)和设置窗口大小
碰撞的实现很简单,只要判断蛇头是否和食物位置相等即可,如果相等则向snake里面插入吃掉的食物元素的数据,之后重新生成蛇。
窗口大小的设置:在工程目录下新建conf.lua,之后写上如下代码:
function love.conf(t)t.window.width = 620t.window.height = 620end
我们改成了620x620分辨率的大小,为了适应游戏数据。
蛇吃自己的逻辑
这里不给大家提供代码,而是留给各位自己实现,事实上蛇头是无法碰到蛇尾的,所以我们只需要遍历除去这两个之外的蛇体,判断蛇头是否与蛇体碰撞即可。
结束语
刚来到自媒体,写作技巧不是很高,望大家谅解。love2d贪吃蛇教程到这里结束。
本期教程到这里结束,如果你有任何疑问,欢迎在评论区讨论,或者私信我,喜欢本教程的请关注,点赞,收藏,转发,谢谢。