defrun(self): # Game loop whilenot self.exit: # Set tick dt = self.clock.get_time() / 1000 self.clock.tick(self.ticks)
# Event queue for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.exit = True pygame.quit()
Surface and Rect
Surface 和 Rect 对象是 PyGame 的基础对象。Surface 对象可以被理解为空白画布,我们在 Surface 对象上填充想要的图案,Screen 其实也是一个 Surface 对象。而 Rect 对象则代表了 Surface 对象
的位置及其包含的区域。在后续的汽车对象中,为了显示及刷新车辆的坐标,我们需要用到 Surface 和 Rect 对象。下面代码是一个简单的例子:
1 2 3 4 5
# Create the surface and pass in a tuple with its length and width surf = pygame.Surface((50, 50)) # Give the surface a color to differentiate it from the background surf.fill((255, 255, 255)) rect = surf.get_rect()
# Vehicle contains parameters of vehicles and provides # a method to update the status of vehicles. classVehicle(pygame.sprite.Sprite): def__init__(self, x, y, image_path, angle=0.0, length=4, max_steering=30, max_acceleration=5.0): # Call Sprite __init__ function super(Vehicle, self).__init__()
# Pygame parameters self.image = self.ori_image = pygame.image.load(image_path) # Use origin image for rotation self.rect = self.image.get_rect()
# Pure pursuit for trajectory purepursuit = PurePursuit()
# Game loop whilenot self.exit: # Set tick dt = self.clock.get_time() / 1000 self.clock.tick(self.ticks)
# Event queue for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.exit = True # Set velocity of obstacle obstacle.velocity.x = 3 # Path Plan and purepursuit