I am trying to make a simple game similar to snake (however the player does not get longer over time). The game is almost complete, however I have encountered a problem where the button presses that would normally change the direction that you are moving in are delayed. This makes the game a lot harder than it needs to be.
Basically I need to know how to make the player change direction instantly after a button press, without any delay.
Code:
from microbit import *
import random
class Game:
running = True
score = 0
speed = 500
x = 2
y = 2
goalX = random.randint(0, 4)
goalY = random.randint(0, 4)
direction = None
def __init__(self):
pass
def startGame(self):
Game.defaultDirection(self)
display.clear()
display.set_pixel(self.x, self.y, 9)
display.set_pixel(self.goalX, self.goalY, 5)
Game.mainLoop(self)
def mainLoop(self):
while self.running is True:
display.clear()
Game.checkBorderCollision(self)
Game.checkGoalCollision(self)
display.set_pixel(self.x, self.y, 9)
display.set_pixel(self.goalX, self.goalY, 5)
Game.buttonAInput(self)
Game.buttonBInput(self)
Game.movePlayer(self)
def defaultDirection(self):
if self.x == 1:
self.direction = 0
if self.x == 3:
self.direction = 2
else:
randomDirection = random.randint(0, 1)
if randomDirection == 0:
self.direction = 2
else:
self.direction = 0
def movePlayer(self):
if self.direction == 2:
self.x -= 1
sleep(self.speed)
if self.direction == 0:
self.x += 1
sleep(self.speed)
if self.direction == 1:
self.y -= 1
sleep(self.speed)
if self.direction == 3:
self.y += 1
sleep(self.speed)
def buttonAInput(self):
if button_a.was_pressed() or button_a.is_pressed():
if self.direction == 3:
self.direction = 0
else:
self.direction += 1
def buttonBInput(self):
if button_b.was_pressed() or button_b.is_pressed():
if self.direction == 0:
self.direction = 3
else:
self.direction -= 1
def checkBorderCollision(self):
if self.x < 0 or self.x > 4 or self.y < 0 or self.y > 4:
animation = 0
if self.direction == 0:
self.x -= 1
if self.direction == 2:
self.x += 1
if self.direction == 3:
self.y -= 1
if self.direction == 1:
self.y += 1
while animation < 3:
display.clear()
display.set_pixel(self.x, self.y, 9)
sleep(300)
display.clear()
sleep(300)
animation += 1
display.scroll(self.score)
self.score = 0
self.x = random.randint(1, 3)
self.y = random.randint(1, 3)
Game.defaultDirection(self)
def checkGoalCollision(self):
if self.x == self.goalX and self.y == self.goalY:
self.score += 1
self.goalX = random.randint(0, 4)
self.goalY = random.randint(0, 4)
if self.speed == 150:
pass
else:
self.speed -= 10
game = Game()
game.startGame()