micropython - Micro:Bit 按钮按下延迟
问题描述
我正在尝试制作一个类似于蛇的简单游戏(但是玩家不会随着时间的推移变得更长)。游戏几乎完成了,但是我遇到了一个问题,即通常会改变您前进方向的按钮按下被延迟。这使得游戏比它需要的更难。
基本上我需要知道如何让玩家在按下按钮后立即改变方向,没有任何延迟。
代码:
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()
解决方案
尝试将此行更改if self.speed == 150:
为if self.speed <= 150
. 你在哪里初始化self.speed
应该有一行.startGame
将它设置为一些高值
推荐阅读
- ssh - SSH 挂起,然后超时而没有连接
- android - 为什么我必须单击 2-3 次才能使注册表单起作用?
- javascript - Cypress.io:是否可以在 Cypress 中设置全局变量,如果可以;如何?
- mongodb - Mongo 大于 BigInt
- docker - 构建 docker 图像 asp.net 核心时出现 OutofMemory 异常
- google-apps-script - 如何在谷歌表格中创建一个计数器来计算计算单元格更改值的次数?
- node.js - 尝试从 Node.js Firebase 函数中读取 Firebase 数据库时无法确定 Firebase 数据库 URL
- android - 如何在没有 ActionBar 的 AndroidX 中设置 BottomNavigationView
- awk - 如何优化这个 awk 脚本?
- sql - 生成 Excel 工作表崩溃