2017-04-01 85 views
0

我正在創建一個pacman遊戲,到目前爲止,所有的東西都是從鬼魂那裏開始工作的,當一個幽靈撞在牆上時,這個類的貝婁被稱爲。然而,如你所見,self.a會返回一個str,但我需要將它應用於我的幽靈精靈,Ghost1,Ghost2等。所以它調用Ghost1.a並且幽靈會相應地移動。Pygame Pacman幽靈,隨機改變方向

任何幫助將不勝感激,謝謝。

class Ghost_move(object): 
    def __init__(self,g_speed): 
     super(Ghost_move, self).__init__() 
     self.left=".rect.x-=g_speed" 
     self.right=".rect.x+=g_speed" 
     self.up=".rect.y-=g_speed" 
     self.down=".rect.y+=g_speed" 
     self.direction=self.left,self.right,self.up,self.down 
     self.a=random.choice(self.direction) 
+0

爲什麼你甚至需要super()? – abccd

+0

我沒有,崇高的文本創建一個新的類時自動添加它,我只是忘了刪除它 – Jack

+0

這是一個可怕的想法,字符串中保存文字,只是使用多個if語句或東西 – abccd

回答

1

正如abccd已經指出的那樣,把源代碼放到你想要執行的字符串中是一個壞主意。距離您最近的解決方案是定義leftright,up,down的功能。然後,你可以存儲方向的功能,並執行一個隨機選擇的一個:

class Ghost_move(object): 
    def __init__(self,g_speed): 
     super(Ghost_move, self).__init__() 
     self.g_speed = g_speed 
     self.directions = self.left, self.right, self.up, self.down 
     self.a = random.choice(self.directions) 
    def left(self): 
     self.rect.x -= self.g_speed 
    def right(self): 
     self.rect.x += self.g_speed 
    def up(self): 
     self.rect.y -= self.g_speed 
    def down(self): 
     self.rect.y += self.g_speed 

現在self.a是,你可以調用一個函數。例如ghost1.a()會在四個方向之一中隨機移動ghost1。但要小心,因爲a只設置一次,因此ghost1.a()總是將該鬼影移向相同的方向,並且每次調用它時都不會隨機選擇一個方向。


一種不同的方法是用向量來做到這一點:

class Ghost_move(object): 
    def __init__(self,g_speed): 
     super(Ghost_move, self).__init__() 
     self.left = (-g_speed, 0) 
     self.right = (g_speed, 0) 
     self.up = (0, -g_speed) 
     self.down = (0, g_speed) 
     self.directions = self.left, self.right, self.up, self.down 
     self.random_dir = random.choice(self.directions) 
    def a(): 
     self.rect.x += self.random_dir[0] 
     self.rect.y += self.random_dir[1] 

用法和以前一樣,你只需調用a()的鬼。