Snake's body not appearing and game crashing for some reason
Posted: Tue Jan 03, 2017 11:08 pm
I'm having (another) problem with my snake game. The code I have for the creation of the snake's body doesn't seem to work, and crashes the game too. I know that the problem that leads to the game crashing is located somewhere in the lastCalc() function, but I have no idea how it causes the game to crash as it seems like it would execute without any problems.
Here's the code:
Also I've attached the .love file:
Thanks for reading and any help would be appreciated !
Here's the code:
Code: Select all
local height = love.graphics.getHeight()
local width = love.graphics.getWidth()
local gameover = false
local lastX = {
}
local lastY = {
}
local nummiesAte = 1
local GMmessage = ""
local Xloss = false
local Yloss = false
local i = 0
local t = 0
local q = 0
local lastsDone = 1
didThing = false
function love.load()
direction = 0
time = 0
snakeHead = {
x = 500,
y = 200,
speed = 0.1
}
nummyBool = false
end
function love.update (dt)
time = time + dt
eatNummy()
checkBorder()
if gameover ~= true then
if time > snakeHead.speed then
if direction == 1 then
snakeHead.y = snakeHead.y -20
elseif direction == 2 then
snakeHead.x = snakeHead.x +20
elseif direction == 3 then
snakeHead.y = snakeHead.y +20
elseif direction == 4 then
snakeHead.x = snakeHead.x -20
end
preLastCalc()
lastCalc()
time = 0
lastsDone = lastsDone + 1
end
elseif gameover == true then
GMmessage = "you lost"
end
end
function love.draw()
spawnNummy()
if nummyBool == true then
love.graphics.setColor(0,255,0)
love.graphics.rectangle('fill', nummyX, nummyY, 20, 20)
end
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle('fill', snakeHead.x, snakeHead.y, 20, 20)
love.graphics.setColor(255,0,0)
love.graphics.print(GMmessage, width/2, height/2)
if lastsDone > 1 then
for t=1, lastsDone do
love.graphics.setColor(255,255,255)
love.graphics.rectangle('fill', lastX[t], lastY[t], 20, 20)
end
end
end
function love.keypressed(key)
if key == ("up") then
direction = 1
elseif key == ("right") then
direction = 2
elseif key == ("down") then
direction = 3
elseif key == ("left") then
direction = 4
end
end
function checkBorder()
if snakeHead.x > width or snakeHead.x < 0 then
gameover = true
Xloss = true
end
if snakeHead.y > height or snakeHead.y < 0 then
gameover = true
Yloss = true
end
end
function spawnNummy()
if nummyBool == false then
nummyX = math.random(love.graphics.getWidth()/20)*20
nummyY = math.random(love.graphics.getHeight()/20)*20
if nummyX ~= snakeHead.x and nummyY ~= snakeHead.y then
nummyBool = true
end
end
end
function eatNummy()
if snakeHead.x == nummyX and snakeHead.y == nummyY then
nummiesAte = nummiesAte + 1
nummyBool = false
end
end
function lastCalc()
lastX[lastsDone] = snakeHead.x
lastY[lastsDone] = snakeHead.y
end
function preLastCalc()
local k= 0
if lastsDone >= 2 and lastsDone >= nummiesAte then
for k= 1, lastsDone do
lastX[k] = lastX[k+1]
end
end
end