1

当鼠标按钮向上时,我正在尝试创建一个功能,它将鬼的图片更改为一个图像。

问题是,我不知道该调用什么(因此 ??? 在脚本中)。这很难,因为幽灵是通过循环创建的。任何人都可以帮忙吗?也许我需要把鬼魂变成精灵?你也能帮忙吗?

import pygame
import random
import sys

class Ball:
    def __init__(self,X,Y,imagefile):
        self.velocity = [3,3]
        self.ball_image = pygame.image.load (imagefile). convert() ### i want this image to change
        self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
        self.sound = pygame.mixer.Sound ('Thump.wav')

if __name__ =='__main__':
    width = 800
    height = 600
    background_colour = 0,0,0
    GHOST_IMAGE = ["images/blue-right.png", "images/red-right.png", "images/orange-right.png", "images/pink-right.png"]
    GHOST_IMAGETWO = ["images/blue-left.png", "images/red-left.png", "images/orange-left.png", "images/pink-left.png"]
    pygame.init()
    frame = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Bouncing Ball animation")
    num_balls = 4
    ball_list = []
    for i in range(num_balls):
        ball_list.append( Ball(random.randint(0, width),random.randint(0, height), (GHOST_IMAGE[i]) ))
    while True:
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                sys.exit(0)
            elif event.type == pygame.MOUSEBUTTONUP:
                ??? = pygame.image.load("images/vulnerable.png").convert() ###i know that this is where and what i need to change it to, but dont know what instance name to call upon.
        frame.fill(background_colour)
        for ball in ball_list:
            if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
                ball.sound.play()
                ball.velocity[0] = -1 * ball.velocity[0]


            if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
                ball.sound.play()
                ball.velocity[1] = -1 * ball.velocity[1]

            ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
            frame.blit (ball.ball_image, ball.ball_boundary)
        pygame.display.flip()
4

1 回答 1

0

一种方法是迭代ball_list并更改每个球:

elif event.type == pygame.MOUSEBUTTONUP:
    image = pygame.image.load("images/vulnerable.png").convert()
    for ball in ball_list:
        ball.ball_image = image

另一种方法是直接在Ball类中实现图像更改行为:

class Ball:
    def __init__(self,X,Y,imagefile):
        self.vulnerable = False
        self.velocity = [3,3]
        self.normal_ball_image = pygame.image.load (imagefile). convert()
        self.v_ball_image = pygame.image.load("images/vulnerable.png").convert()
        self.ball_image = self.normal_ball_image
        self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
        self.sound = pygame.mixer.Sound ('Thump.wav')

    def toggle(self):
        self.vulnerable = not self.vulnerable
        self.ball_image = self.v_ball_image if self.vulnerable else self.normal_ball_image

在你的循环中:

elif event.type == pygame.MOUSEBUTTONUP:
    for ball in ball_list:
        ball.toggle()
于 2013-03-20T07:48:13.790 回答