所以我有一个函数可以阻止精灵移出屏幕:`
def move_extent(self, x, y):
if self.rect.right > 700:
self.rect.right = 700
elif self.rect.left < 0:
self.rect.left = 0
elif self.rect.y < 275:
self.rect.y = 275
elif self.rect.y > 275:
self.rect.y = 275`
它使精灵不会移过x坐标,而且大多数情况下都是y坐标。但是如果精灵位于最左边或最右边(0或700 x),它仍会上升或下降。
主要是游戏循环:
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
protag.moveLeft(3)
if keys[pygame.K_d]:
protag.moveRight(3)
if keys[pygame.K_w]:
protag.moveUp(3)
if keys[pygame.K_s]:
protag.moveDown(3)
all_sprites_list.update()
screen.blit(background, (0, 0))
all_sprites_list.draw(screen)
move_extent(protag, x_coord, y_coord)
pygame.display.flip()
clock.tick(60)
pygame.quit()
答案 0 :(得分:1)
几乎:)将您的测试更改为:
def move_extent(self, x, y): # x and y are never used?
if self.rect.right > 700:
self.rect.right = 700
if self.rect.left < 0:
self.rect.left = 0
if self.rect.y < 275: # why y twice? this will limit y to be 275
self.rect.y = 275 # and x is never checked ...
if self.rect.y > 275: # why y twice? this will limit y to be 275
self.rect.y = 275`
目前使用的是您之前的if
,其他所有测试都不会再进行测试了。
您可以将此缩短为:
def move_extent(self, x, y):
self.rect.right = min(700,self.rect.right) # take whatever is lower
self.rect.left = max( 0, self.rect.left) # take whatever is higher
self.rect.y = 275 # fix y at 275
https://docs.python.org/3/library/functions.html#max https://docs.python.org/3/library/functions.html#min