在下面的代码中,边界是屏幕的宽度和高度,因此最好从一开始就定义它们。在
处理此问题的一种方法是防止x和{}坐标低于0,高于{}的宽度和{}的高度,同时不忘减去框的大小。在
我建议使用助推器来提高游戏性,而不是按其他键,最好使用修改器,如shift或control。
下面的代码使用左移来加速移动。在import sys
import pygame as pg
def main():
width, height = 640, 480
hbox, vbox = 20, 20
screen = pg.display.set_mode((width, height))
clock = pg.time.Clock()
rect = pg.Rect(300, 220, hbox, vbox)
velocity = (0, 0)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pg.key.get_pressed()
# booster
move = 8 if keys[pg.K_LSHIFT] else 4
if keys[pg.K_a]: #to move left
rect.x -= move
if rect.x < 0 : rect.x = 0
if keys[pg.K_d]: #to move right
rec