我编写了一个程序,该程序创建4个精灵作为在pygame曲面内反弹的矩形。在精灵的更新过程中更新位置。当我运行该程序时,仅出现1-3个矩形,而出现的矩形是随机的。我添加了一条打印语句,可以看到每个精灵都在更新。
代码如下:
# import pygame library so we can use it!
import pygame
import random
import mygame_colors
# run initialization code on the library
pygame.init()
# setup display dimensions
display_width = 1200
display_height = 600
FPS = 30
gameSurface = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Window Caption!')
colors = (mygame_colors.RED,mygame_colors.GREEN,mygame_colors.WHITE,mygame_colors.BLUE)
# game code that needs to run only once
class Enemy(pygame.sprite.Sprite):
def __init__(self, number):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10*(number+1), 10))
self.number = number
# self.color = (random.randint(100,255),random.randint(100,255),random.randint(100,255))
self.color = colors[x]
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.center = (random.randint(0,display_width), random.randint(0,display_width))
self.x_speed = random.randint(-30,30)
if self.x_speed == 0:
self.x_speed += 1
self.y_speed = random.randint(-30,30)
if self.y_speed == 0:
self.y_speed += 1
def update(self,*args):
super().update(self,*args)
self.rect.x += self.x_speed
self.rect.y += self.y_speed
x,y = self.rect.center
if x > display_width or x < 0:
self.x_speed *= -1
if y > display_height or y < 0:
self.y_speed *= -1
print ("%s %s: %s,%s,%s"%(self.number,self.color,self.rect.x,self.rect.y,self.image))
# create game clock
clock = pygame.time.Clock()
# create a sprite group to keep track of sprites
all_sprites = pygame.sprite.Group()
for x in range(4):
player = Enemy(x)
all_sprites.add(player)
# fill entire screen with color
gameSurface.fill(mygame_colors.BLACK)
# main game loop
running = True # when running is True game loop will run
while running == True:
# get input events and respond to them
# if event is .QUIT
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
clock.tick(FPS)
# game code that repeats every frame
# clear display (redraw background)
gameSurface.fill(mygame_colors.BLACK)
# update
all_sprites.update() # draw all sprites
all_sprites.draw(gameSurface)
# pygame.draw.rect(gameSurface, r_color, [rectX, rectY, 25, 25])
# pygame.draw.circle(gameSurface,r_color,(int(rectX),int(rectY)),25)
# gameSurface.blit(image1, [rectX, rectY])
# update and redraw entire screen
pygame.display.flip()
# pygame.display.update()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(pygameColors.GREEN)
self.rect = self.image.get_rect()
self.rect.center = (display_width / 2, display_height / 2)
答案 0 :(得分:1)
某些矩形是随机放置在窗口之外的,因为矩形位于display_width
* display_width
而不是display_width
* display_height
的区域中:
更改矩形的位置以解决此问题:
self.rect.center = (random.randint(0,display_width), random.randint(0,display_width))
self.rect.center = (random.randint(0,display_width), random.randint(0,display_height))