问题描述
我想知道如何在使用 pygame 撞到“墙”时改变正方形的方向。下面是我的代码:
"""
Date: Nov 4,2020
Description: Animating Shapes with pygame
"""
import pygame
def main():
'''This function defines the 'mainline logic' for our game.'''
# I - INITIALIZE
pygame.init()
# disPLAY
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption("Crazy Shapes Animation")
# ENTITIES
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255)) # white background
# Make a red 25 x 25 Box
red_Box = pygame.Surface((25,25))
red_Box = red_Box.convert()
red_Box.fill((255,0))
# A - ACTION (broken into ALTER steps)
# ASSIGN
clock = pygame.time.Clock()
keepGoing = True
red_Box_x = 0 # Assign starting (x,y)
red_Box_y = 200 # for our red Box
# LOOP
while keepGoing:
# TIMER
clock.tick(30)
# EVENT HANDLING
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
# change x coordinate of Box
red_Box_x += 5
# check boundaries,to reset Box to left-side
if red_Box_x > screen.get_width():
red_Box_x = 0
# REFRESH (update window)
screen.blit(background,(0,0))
screen.blit(red_Box,(red_Box_x,red_Box_y)) # blit Box at new (x,y) location
pygame.display.flip()
# Close the game window
pygame.quit()
# Call the main function
main()
当它碰到最右侧的墙壁时,我希望它反转方向并返回最左侧的墙壁。然后它继续无限地撞击墙壁。这是一个学校作业,我在网上找不到任何解决方案,所以如果你能帮助我就好了!
解决方法
为运动使用变量 (move_x
) 而不是常量。当物体撞墙时反转变量的值 (move_x *= -1
):
def main():
# [...]
move_x = 5
# LOOP
while keepGoing:
# [...]
# change x coordinate of box
red_box_x += move_x
# check boundaries,to reset box to left-side
if red_box_x >= screen.get_width():
red_box_x = screen.get_width()
move_x *= -1
if red_box_x <= 0:
red_box_x = 0
move_x *= -1
# [...]