2013-03-20 33 views
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() 
+0

你的繪製鬼魂功能在哪裏?我只看到鬼圖像列表。 – 2013-03-20 07:48:51

回答

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() 
+0

非常感謝 – user2184744 2013-03-20 11:42:07

相關問題