我是 python/pygame 的新手,我正在尝试进行 boids 模拟,但似乎无法创建边框,以便 boids 不会超出窗口。这是我到目前为止所做的。
#importing the needed modules and libraries
import pygame, sys, random, pygame.math
#Initialize pygame and pygame time
pygame.init()
clock = pygame.time.Clock()
#This is some screen settings, giving the screen size.
screen_width = 1000
screen_height = 750
screen = pygame.display.set_mode((screen_width, screen_height))
#Making the background, loading it and scaling the background to fit the screen.
background = pygame.image.load("Background.jpg")
background = pygame.transform.scale(background, (screen_width, screen_height))
#Make parent-class for boids and hoiks
class Moving_Object(pygame.sprite.Sprite):
def __init__(self, picture_load, X_pos, Y_pos): #speed_x, speed_y
super().__init__()
#Creating picture_load to make it easier to load image. Creating a rectangle around image
self.image = pygame.image.load(picture_load)
self.image = pygame.transform.scale(self.image, (40, 40))
#Make rectangle around image
self.rect = self.image.get_rect()
self.rect.center = [X_pos, Y_pos]
self.speed_x = random.randint(-3,3)
self.speed_y = random.randint(-3,3)
def border(self):
if self.rect.right >= screen_width or self.rect.left <= 0:
self.speed_x *= -1
if self.rect.bottom >= screen_height or self.rect.top <= 0:
self.speed_y *= -1
if self.rect.collidrect(boid):
print("yesir")
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
#making moving_object group and adding boids & hoiks
moving_object_group = pygame.sprite.Group()
for boid in range(50):
new_boid = Moving_Object("Logo.png", random.randrange(0, screen_width), random.randrange(0, screen_height))
moving_object_group.add(new_boid)
for hoiks in range(10):
new_hoik = Moving_Object('skullObstacle.png',random.randrange(0, screen_width), random.randrange(0, screen_height))
moving_object_group.add(new_hoik)
"""游戏厕所,它保持窗口打开并检查事件并调用不同的类和方法""" while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.退出() sys.exit()
pygame.display.flip()
screen.blit(background, (0,0))
moving_object_group.draw(screen)
moving_object_group.update()
clock.tick(60)