Lua 代码中存在缺陷的游戏逻辑

Flawed game logic in Lua code

该代码适用于一个简单的蛇克隆,如果它已经向右移动,我不想让蛇向左移动。

如果我在向右走的时候只按向左,它会起作用,但是如果我在时间范围内按向上然后向左,它就会开始向左移动。

function self.update(dt)
    if love.keyboard.isDown(self.left) and self.prevvelocity.x ~= 1 then 
        self.velocity.x = -1
        self.velocity.y = 0
    end 
    if love.keyboard.isDown(self.right) and self.prevvelocity.x ~= -1 then 
        self.velocity.x = 1     
        self.velocity.y = 0
    end     
    if love.keyboard.isDown(self.up) and self.prevvelocity.y ~= 1 then  
        self.velocity.x = 0
        self.velocity.y = -1
    end 
    if love.keyboard.isDown(self.down) and self.prevvelocity.y ~= -1 then   
        self.velocity.x = 0
        self.velocity.y = 1
    end 

    if self.timeSinceLastMove < self.speedinverted then
        self.timeSinceLastMove = self.timeSinceLastMove + dt
    else

        table.remove(self.tail, 1)

        tail = { x = self.position.x, y = self.position.y }

        table.insert(self.tail, tail)

        self.position.x = self.position.x + self.velocity.x * tileSize
        self.position.y = self.position.y + self.velocity.y * tileSize

        self.prevvelocity = self.velocity

        self.timeSinceLastMove = 0;
    end
end
function self.update(dt)
    if love.keyboard.isDown(self.left) and self.prevvelocity.x ~= 1 then 
        self.velocity.x = -1
        self.velocity.y = 0
    end 
    if love.keyboard.isDown(self.right) and self.prevvelocity.x ~= -1 then 
        self.velocity.x = 1     
        self.velocity.y = 0
    end     
    if love.keyboard.isDown(self.up) and self.prevvelocity.y ~= 1 then  
        self.velocity.x = 0
        self.velocity.y = -1
    end 
    if love.keyboard.isDown(self.down) and self.prevvelocity.y ~= -1 then   
        self.velocity.x = 0
        self.velocity.y = 1
    end 

    self.timeSinceLastMove = self.timeSinceLastMove + dt

    if self.timeSinceLastMove >= self.speedinverted then
        self.timeSinceLastMove = self.timeSinceLastMove - self.speedinverted

        self.position.x = self.position.x + self.velocity.x * tileSize
        self.position.y = self.position.y + self.velocity.y * tileSize

        table.remove(self.tail, 1)
        local head = { x = self.position.x, y = self.position.y }
        table.insert(self.tail, head)

        self.prevvelocity = { x = self.velocity.x, y = self.velocity.y }
    end
end