Python 在pygame中执行for循环后,图像不会保留在屏幕上

Python 在pygame中执行for循环后,图像不会保留在屏幕上,python,loops,class,pygame,draw,Python,Loops,Class,Pygame,Draw,我一直在尝试修改此代码,以便在子弹击中敌人后,player.png图像显示在位置x=60和y=48。但是图像并没有保持固定,它只是出现和消失。我不知道代码中错误或缺失元素的确切位置,但我怀疑其中一个原因是在draw\u reaction函数中我的for循环部分被误用 我的图像 我的MWE代码: import pygame import random # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255

我一直在尝试修改此代码,以便在子弹击中敌人后,
player.png
图像显示在位置
x=60
y=48
。但是图像并没有保持固定,它只是出现和消失。我不知道代码中错误或缺失元素的确切位置,但我怀疑其中一个原因是在
draw\u reaction
函数中我的
for
循环部分被误用

我的图像

我的MWE代码:

import pygame
import random

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# --- Classes


class Block(pygame.sprite.Sprite):
    """ This class represents the block. """
    def __init__(self, color):
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.Surface([20, 15])
        self.image.fill(color)

        self.rect = self.image.get_rect()


class Player(pygame.sprite.Sprite):
    """ This class represents the Player. """

    def __init__(self):
        """ Set up the player on creation. """
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.Surface([20, 20])
        self.image.fill(RED)

        self.rect = self.image.get_rect()

    def update(self):
        """ Update the player's position. """
        # Get the current mouse position. This returns the position
        # as a list of two numbers.
        pos = pygame.mouse.get_pos()

        # Set the player x position to the mouse x position
        self.rect.x = pos[0]


class Bullet(pygame.sprite.Sprite):
    """ This class represents the bullet . """
    def __init__(self):
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.Surface([4, 10])
        self.image.fill(BLACK)

        self.rect = self.image.get_rect()

    def update(self):
        """ Move the bullet. """
        self.rect.y -= 3


# --- Create the window

# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])

# --- Sprite lists

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# List of each block in the game
block_list = pygame.sprite.Group()

# List of each bullet
bullet_list = pygame.sprite.Group()

# --- Create the sprites

for i in range(0,1,2):
    # This represents a block
    block = Block(BLUE)

    # Set a random location for the block
    block.rect.x = random.randrange(screen_width)
    block.rect.y = random.randrange(350)

    # Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)

# Create a red player block
player = Player()
all_sprites_list.add(player)
player_image = pygame.image.load("player.png").convert() 
# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

score = 0
player.rect.y = 370

# -------- Main Program Loop -----------
while not done:
    # --- Event Processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.MOUSEBUTTONDOWN:
            # Fire a bullet if the user clicks the mouse button
            bullet = Bullet()
            # Set the bullet so it is where the player is
            bullet.rect.x = player.rect.x
            bullet.rect.y = player.rect.y
            # Add the bullet to the lists
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)

    # --- Game logic

    # Call the update() method on all the sprites


    # Calculate mechanics for each bullet
    for bullet in bullet_list:

        # See if it hit a block
        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

        # For each block hit, remove the bullet and add to the score
        for block in block_hit_list:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score += 1
            print(score)

        # Remove the bullet if it flies up off the screen
        if bullet.rect.y < -10:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
    def draw_reaction():
        for bullet in bullet_list:
            block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
            for block in block_hit_list:
                screen.blit(player_image, [60, 48]) 
    all_sprites_list.update() 
    # --- Draw a frame

    # Clear the screen
    screen.fill(WHITE)
    draw_reaction()
    # Draw all the spites
    all_sprites_list.draw(screen)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 20 frames per second
    clock.tick(60)

pygame.quit()
导入pygame
随机输入
#定义一些颜色
黑色=(0,0,0)
白色=(255,255,255)
红色=(255,0,0)
蓝色=(0,0255)
#---班级
类块(pygame.sprite.sprite):
“”“此类表示块。”“”
定义初始化(自身,颜色):
#调用父类(Sprite)构造函数
super()。\uuuu init\uuuuu()
self.image=pygame.Surface([20,15])
self.image.fill(颜色)
self.rect=self.image.get_rect()
职业玩家(pygame.sprite.sprite):
“”“此类代表玩家。”“”
定义初始化(自):
“”“在创建时设置播放机。”“”
#调用父类(Sprite)构造函数
super()。\uuuu init\uuuuu()
self.image=pygame.Surface([20,20])
self.image.fill(红色)
self.rect=self.image.get_rect()
def更新(自我):
“”“更新玩家的位置。”“”
#获取当前鼠标位置。这将返回位置
#作为两个数字的列表。
pos=pygame.mouse.get_pos()
#将播放器x位置设置为鼠标x位置
self.rect.x=pos[0]
类子弹(pygame.sprite.sprite):
“”“此类表示项目符号。”“”
定义初始化(自):
#调用父类(Sprite)构造函数
super()。\uuuu init\uuuuu()
self.image=pygame.Surface([4,10])
self.image.fill(黑色)
self.rect=self.image.get_rect()
def更新(自我):
“移动子弹。”
自校正y-=3
#---创建窗口
#初始化Pygame
pygame.init()
#设置屏幕的高度和宽度
屏幕宽度=700
屏幕高度=400
screen=pygame.display.set_模式([屏幕宽度,屏幕高度])
#---精灵列表
#这是每个精灵的列表。所有区块和球员区块以及。
所有精灵列表=pygame.sprite.Group()
#游戏中每个方块的列表
block_list=pygame.sprite.Group()
#每个项目符号的列表
bullet\u list=pygame.sprite.Group()
#---创造精灵
对于范围(0,1,2)内的i:
#这表示一个块
块=块(蓝色)
#设置块的随机位置
block.rect.x=random.randrange(屏幕宽度)
block.rect.y=random.randrange(350)
#将块添加到对象列表中
块列表。添加(块)
所有精灵列表。添加(块)
#创建一个红色玩家块
player=player()
所有精灵列表。添加(玩家)
player_image=pygame.image.load(“player.png”).convert()
#循环,直到用户单击关闭按钮。
完成=错误
#用于管理屏幕更新的速度
clock=pygame.time.clock()
分数=0
player.rect.y=370
#-----主程序循环-----------
虽然没有这样做:
#---事件处理
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
完成=正确
elif event.type==pygame.MOUSEBUTTONDOWN:
#如果用户单击鼠标按钮,则发射子弹
bullet=bullet()
#将子弹放在球员所在的位置
bullet.rect.x=player.rect.x
bullet.rect.y=player.rect.y
#将项目符号添加到列表中
所有精灵列表。添加(项目符号)
项目符号列表。添加(项目符号)
#---游戏逻辑
#对所有精灵调用update()方法
#计算每颗子弹的力学性能
对于项目符号列表中的项目符号:
#看看它是否撞到了一个街区
block\u hit\u list=pygame.sprite.spritecollide(bullet,block\u list,True)
#对于每一次拦网命中,移除子弹并增加分数
对于block_命中列表中的block_:
项目符号列表。删除(项目符号)
所有精灵列表。删除(项目符号)
分数+=1
打印(分数)
#如果子弹飞出屏幕,请将其取出
如果项目符号矩形y<-10:
项目符号列表。删除(项目符号)
所有精灵列表。删除(项目符号)
def draw_reaction():
对于项目符号列表中的项目符号:
block\u hit\u list=pygame.sprite.spritecollide(bullet,block\u list,True)
对于block_命中列表中的block_:
blit(播放器图像[60,48])
所有精灵列表。更新()
#---画一个框架
#清除屏幕
屏幕填充(白色)
牵引反应()
#拔掉所有的唾沫
所有精灵列表。绘制(屏幕)
#继续,用我们绘制的内容更新屏幕。
pygame.display.flip()
#---限制为每秒20帧
时钟滴答(60)
pygame.quit()
编辑更新:每次游戏重新开始时,游戏中只有一个敌人出现在随机位置


编辑更新2:我知道在大多数游戏中,碰撞后敌人会从屏幕上消失。这也发生在我的代码中。但是对于我的一个特殊需求,我需要这样一个结果,在子弹与敌人碰撞后,一个图像(player.png)保持不变。

这个问题是由
draw\u reaction()
函数引起的,它只在子弹与一个块碰撞的绝对时间内绘制
player\u图像。因此,它显示单个帧的图像(60分之一秒),但在下一个循环中,碰撞不再发生(子弹被移除),因此它永远不会被绘制

有很多种方法可以解决这个问题,但是我不确定显示这个位图的目的,所以它们可能不如
class PlayerShip( pygame.sprite.Sprite ):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load( "player.png" ) #.convert() 
        self.rect  = self.image.get_rect()
        self.rect.topleft = ( 60, 48 ) 
player_sprite = PlayerShip()
def draw_reaction():
    for bullet in bullet_list:
        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
        for block in block_hit_list:
            # TODO: ensure it's not showing already
            all_sprites_list.add( player_sprite )      # add the player sprite 
            break                                      # only add once