【问题标题】:How do I delete an image after a collision in pygame?如何在pygame中发生碰撞后删除图像?
【发布时间】:2018-01-14 23:01:13
【问题描述】:

我正在使用 python 制作一个涉及通电的游戏。有一个随机生成的机会,它会在屏幕上显示它的图像。一旦玩家的身体(本场景中的船长)与它发生碰撞,它就会从列表中随机选择一个强化道具。我正在检查与图像位置(相同大小)的矩形的碰撞并尝试删除矩形,并在发生碰撞时删除图像。我怎样才能做到这一点?到目前为止,这是我的尝试,但是,我一直收到错误消息:“列表分配索引超出范围”并且它突出显示了以下行:del PowerYList [Spot]。谁能告诉我我做错了什么?

if random.randint(1,2500) == 2500:
            PowerY = random.randint(125,585)
            PowerRect = Rect(930, PowerY, 50,50)
            PowerYList.append(PowerY)
            PowerRects.append(PowerRect)


        for X in PowerYList:
            Screen.blit(PowerUp, (930, X))

        Radius = 0   
        for X in PowerRects:
            if X.colliderect(Rect(942, CaptainY, 15, 30)) == True:
                Power = random.choice(PowerUps)
                Power = "Nuke"

                Spot = PowerRects.index(X)
                del X
                del PowerYList[Spot]

                if Power == "Health":
                    if Health <= 85:
                        Health += 15
                    else:
                        Health += 100-Health

                elif Power == "Nuke":
                    Radius = 0 
                    for Y in range(1,50):
                        draw.circle(Screen, ORANGE, (500, 350), Radius+50)
                        draw.circle(Screen, RED, (500,350), Radius)
                        Radius += 5

                    Gigabits = []
                    Gigabits_Heads = []
                    Gigabit_Health = []
                    S_Gigabits = []
                    S_Gigabits_Heads = []
                    S_Gigabit_Health = []

【问题讨论】:

  • 我似乎看不到您的代码中的 Spot 是什么。
  • 提供Minimum, Complete and Verifiable 示例将帮助其他人帮助您。通常,您希望将背景图像(或填充)从刚刚删除的对象的矩形中填充。你还要做很多手工工作,我建议你使用sprites 和精灵组
  • 阅读PEP 8 -- Style Guide for Python Code。 IE。对于变量我们使用lower_case_names,对于我们使用CamelCaseNames的类。
  • 总是将完整的错误消息(Traceback)放在有问题的地方(作为文本,而不是屏幕截图)。还有其他有用的信息。
  • 为什么在PowerRects 中搜索Spot 并仅从PowerYList 中删除Spot?如果你从PowerYList 中删除元素,那么它必须比PowerRects 更短,并且你必须得到索引错误。您必须从两者中删除或在PowerYList 中搜索Spot

标签: python image pygame collision-detection


【解决方案1】:

这是我构建的一个示例,用于演示与鼠标碰撞时精灵的移除。其他方法见答案like this

import random
import pygame

screen_width, screen_height = 640, 480
def get_random_position():
    """return a random (x,y) position in the screen"""
    return (random.randint(0, screen_width - 1),  #randint includes both endpoints.
            random.randint(0, screen_height - 1)) 

def get_random_named_color(allow_grey=False):
    """return one of the builtin colors"""
    if allow_grey:
        return random.choice(all_colors)
    else:
        return random.choice(non_grey)

def non_grey(color):
    """Return true if the colour is not grey/gray"""
    return "grey" not in color[0] and "gray" not in color[0]

all_colors = list(pygame.colordict.THECOLORS.items())  
# convert color dictionary to a list for random selection once
non_grey = list(filter(non_grey, all_colors))

class PowerUp(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        width, height = 12, 10
        self.color, color = get_random_named_color()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        # Fetch the rectangle object that has the dimensions of the image
        # Update the position by setting the values of rect.x and rect.y
        self.rect = self.image.get_rect().move(*get_random_position())

    def update(self):
        """move to a random position"""
        self.rect.center = get_random_position()

if __name__ == "__main__":
    pygame.init()
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Sprite Collision Demo')
    clock = pygame.time.Clock() #for limiting FPS
    FPS = 60
    exit_demo = False

    #create a sprite group to track the power ups.
    power_ups = pygame.sprite.Group()
    for _ in range(10):
        # create a new power up and add it to the group.
        power_ups.add(PowerUp())

    # main loop
    while not exit_demo:
        for event in pygame.event.get():            
            if event.type == pygame.QUIT:
                exit_demo = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    exit_demo = True
                elif event.key == pygame.K_SPACE:
                    power_ups.update()
            elif event.type == pygame.MOUSEBUTTONUP:
                for _ in range(10):
                    power_ups.add(PowerUp())
        # check for collision
        for p in power_ups:
            if p.rect.collidepoint(pygame.mouse.get_pos()):
                power_ups.remove(p)
                print(f"Removed {p.color} power up")

        screen.fill(pygame.Color("black")) # use black background
        power_ups.draw(screen)
        pygame.display.update()
        clock.tick(FPS)
    pygame.quit()
    quit()

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    相关资源
    最近更新 更多