我正在尝试制作一个类似于蛇的简单游戏(但是玩家不会随着时间的推移变得更长)。游戏几乎完成了,但是我遇到了一个问题,即通常会改变您前进方向的按钮按下被延迟。这使得游戏比它需要的更难。
基本上我需要知道如何让玩家在按下按钮后立即改变方向,没有任何延迟。
代码:
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()