pygame求解
我要将星星随机地拜访在屏幕上。 以下的源代码: 运行到stars.draw(screen) 报错 AttributeError: 'Star' object has no attribute 'rect' 求解 错哪了,以及如何改。import pygame
from sys import exit
import random
from pygame.sprite import Sprite
from pygame.sprite import Group
class Star(Sprite):
def __init__(self, screen):
super(Star, self).__init__()
self.image = star = pygame.image.load('images\\star.png')
self.screen = screen
self.star_rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.star_rect.center = self.screen_rect.center
def blitme(self):
self.screen.blit(self.image, self.star_rect)
def create_stars(screen, stars):
"""创建星星群"""
star = Star(screen)
screen_rect = screen.get_rect()
number_x = int(screen_rect.width / (2*star.star_rect.width))
number_y = int(screen_rect.height / (2*star.star_rect.height))
random_number_y = random.randint(0, number_y)
random_number_x = random.randint(0, number_x)
for y in range(random_number_y):
for x in range(random_number_x):
star_new = Star(screen)
star_new.star_rect.x = star.star_rect.width + 2*x*star.star_rect.width
star_new.star_rect.y = star.star_rect.height + 2*y*star.star_rect.height
stars.add(star_new)
def main_star():
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("星星闪耀")
stars = Group() # 创建星星的空编组
create_stars(screen, stars) # 将星星放入空编组中
while True:
stars.draw(screen)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
main_star()
已解决。。我将class Star类的时候用的是self.star_rect = self.image.get_rect() 中的star_rect全部改成rect就行了
页:
[1]