2015-06-14 114 views
1

我需要訪問類中的全局對象來更改它的圖像。這裏的代碼:如何訪問類內部的全局對象?

import pygame 
from livewires import games 
from livewires import color 
import time 
import random 

games.init(screen_width = 640, screen_height = 480, fps = 50) 

class Cursor(games.Sprite): 
    """The pokemon based cursor!""" 

    def __init__(self, image, x ,y): 
     super().__init__(image=image, x=x, y=y) 



    def update(self): 


     self.x = games.mouse.x 
     self.y = games.mouse.y 
     self.check_collide() 

    def check_collide(self): 
     for sprite in self.overlapping_sprites: 
      sprite.handle_collide() 



class Play_Button(games.Sprite): 
    """The 'Play' button on the menu.""" 

    def __init__(self , image, x ,y): 
     super().__init__(image=image, x=x, y=y) 

    def handle_collide(self): 
     global play_obj 

     play_image2 = games.load_image("playbtn2.png", transparent = True) 
     play_obj.value = play_image2 
     print("COME ON!") 


class P1C_Button(games.Sprite): 

    def __init__(self, image, x, y): 
     super().__init__(image=image, x=x, y=y) 

class Logo(games.Sprite): 

    def handle_collide(self): 
     print("Collision ignored.") 



play_image = games.load_image("playbtn.png", transparent = True) 
play_obj = Play_Button(image = play_image, 
       x = games.screen.width/2, 
       y = games.screen.height/2) 
games.screen.add(play_obj) 


logo_image = games.load_image("FamilyMon.png", transparent = True) 
logo_obj = Logo(image = logo_image, 
       x = games.screen.width/2, 
       y = 75) 
games.screen.add(logo_obj) 

white_image = games.load_image("white.png", transparent = False) 
games.screen.background = white_image 

cursor_image = games.load_image("cursor.png", transparent = True) 
cursor_obj = Cursor(image = cursor_image, 
        x = games.mouse.x, 
        y = games.mouse.y) 
games.screen.add(cursor_obj) 
games.mouse.is_visible = False 
games.screen.event_grab = True 

games.screen.mainloop() 

這是'Play_Button'的handle_collide方法中的重要部分。它試圖訪問創建的對象'play_obj',但代碼似乎什麼都不做。當鼠標設置的Play_Button的handle_collide沒有。我已經盡力了,所以如果這看起來像一個愚蠢的問題,而不是抱歉,因爲我是新的。

+0

嘗試在「Play_Button」的'handle_collide'內打印類型(play_obj)'。它說什麼? –

+0

「sys.stdout」上出現「COME ON!」,或者「nothing」是否意味着你也看不到打印的字符串? –

+0

正在打印字符串。 – Lixerman99

回答

2

您不應該首先使用全局變量。

您只能創建一個Play_Button對象,所以全球play_obj總是is self。您可以讓該對象設置自己的字段:

self.value = play_image2 
+1

謝謝!還要感謝bshuster13! – Lixerman99

2

我試圖理解爲什麼這樣做以下列方式不能滿足你

def handle_collide(self): 
    play_image2 = games.load_image("playbtn2.png", transparent = True) 
    self.value = play_image2 
    print("COME ON!") 

... 

從我看到的,只有一個Play_Button實例,它要在collide發生改變自己的形象。那麼爲什麼不使用self.value