如何为pygame
设置边界,以免矩形(你可以说正方形)离开屏幕?
我访问了其他网站,但没有任何内容对我有用。
盒子将左(a)、右(d)、上(w)、下(s)移动
。
我的代码:
import sys
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(300, 220, 20, 20)
velocity = (0, 0)
done = False
#screen
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pg.key.get_pressed()
#move slow
if keys[pg.K_a]:
rect.x -= 4
if keys[pg.K_d]:
rect.x += 4
if keys[pg.K_s]:
rect.y += 4
if keys[pg.K_w]:
rect.y -= 4
#move fast
if keys[pg.K_g]:
rect.x -= 8
if keys[pg.K_j]:
rect.x += 8
if keys[pg.K_h]:
rect.y += 8
if keys[pg.K_y]:
rect.y -= 8
screen.fill((40, 40, 40))
pg.draw.rect(screen, (100, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
最佳答案
在以下代码中,边界是屏幕宽度和高度,因此您最好从一开始就定义它们。
处理此问题的一种方法是防止 x
和 y
坐标低于 0
并高于 x 的宽度
和 y
的高度,不要忘记减去盒子的大小。
我建议使用助推器对游戏玩法进行一些改进,而不是按其他键,最好使用像 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
rect.x += move
if rect.x > width-hbox : rect.x = width - hbox
if keys[pg.K_w]: #to move up
rect.y -= move
if rect.y < 0: rect.y = 0
if keys[pg.K_s]: #to move down
rect.y += move
if rect.y > height - hbox: rect.y = height - vbox
screen.fill((40, 40, 40))
pg.draw.rect(screen, (150, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
关于python - 如何在pygame中设置边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45659626/