我正在通过制作一个简单的游戏来学习 pygame。 这是代码: 主要脚本:
import pygame
from gracz2 import SpriteGenerator
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
pygame.init()
pygame.display.set_caption("Super Gra!")
screen_height = 720
screen_width = 1280
screen = pygame.display.set_mode((screen_width, screen_height))
all_sprites_list = pygame.sprite.Group()
playerSprite = SpriteGenerator(1,150,150)
playerSprite.rect.x = (screen_width/2 - 75)
playerSprite.rect.y = 550
all_sprites_list.add(playerSprite)
clock = pygame.time.Clock()
mainloop = True
playtime = 0
while mainloop:
for event in pygame.event.get():
# User presses QUIT-button.
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
# User presses ESCAPE-Key
if event.key == pygame.K_ESCAPE:
mainloop = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerSprite.moveLeft(8)
if keys[pygame.K_RIGHT]:
playerSprite.moveRight(8)
milliseconds = clock.tick(60)
playtime += milliseconds / 1000.0
all_sprites_list.update()
pygame.display.set_caption("Czas gry: " + str(round(playtime,1)) + " sekund")
# Refresh the screen
screen.fill(BLACK)
all_sprites_list.draw(screen)
screen.blit(playerSprite.image, (playerSprite.rect.x,playerSprite.rect.y))
pygame.display.flip()
print(all_sprites_list.sprites())
print(all_sprites_list)
print(playerSprite.rect.x)
print(playerSprite.rect.y)
pygame.quit()
和另一个名为“gracz2.py”的文件:
import pygame
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
class SpriteGenerator(pygame.sprite.Sprite):
#This class represents a player. It derives from the "Sprite" class in Pygame.
def __init__(self, type, width, height):
# Call the parent class (Sprite) constructor
super().__init__()
# Pass in the color of the player, and its x and y position, width and height.
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
if type == 1:
self.image = pygame.image.load("sprite-ufo.gif").convert_alpha()
elif type == 2:
self.image = pygame.image.load("sprite-bomb.jpg").convert_alpha()
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
def moveRight(self, pixels):
self.rect.x += pixels
def moveLeft(self, pixels):
self.rect.x -= pixels
它可以在一个文件中完成,但这样代码对我来说更具可读性。
在第 50 行左右,我调用 all_sprites_list.draw(screen)
据我了解,这应该位 block 删除 all_sprites_list
中包含的所有 Sprite 。但它什么也没做。
我必须使用screen.blit(playerSprite.image, (playerSprite.rect.x,playerSprite.rect.y))
手动位图 Sprite 。
因为我稍后要添加生成大量 Sprite ,所以我无法手动将它们全部传输。
为什么不all_sprites_list.draw(screen)
按预期工作?
这可能是代码中的一个愚蠢错误,但我现在尝试查找一个多小时,但无法找到它。
最佳答案
事实证明,当我重新启动电脑时,draw() 函数工作正常。 我首先不知道是什么原因造成的,很抱歉在没有遵循 IT 故障排除第一条规则的情况下提问(重新启动并重试) PS:谢谢furas的回答
关于python - pygame,如何使用 sprite.Group.draw() 绘制所有 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562155/