2013-04-20 5 views
1

Я пытаюсь создать игру «сумасшедшего понга» для класса. требования должны дублировать мяч после подпрыгивания. Это издание также требует, чтобы было 3 типа шариков, один из которых регулярно сжимал весло, а другой увеличивал весло. Мой код до сих пор:Ошибка объекта класса Python

from livewires import games, color, random 
import decimal 


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

score = games.Text(value = 0, size = 25, color = color.black, 
           top = 460, right = games.screen.width - 10) 
games.screen.add(score) 

class Paddle(games.Sprite): 
    """ 
    A paddle controlled by player to catch falling pizzas. 
    """ 
    SMALL = 1 
    MEDIUM = 2 
    LARGE = 3 
    images = {SMALL : games.load_image("paddle.bmp"), 
       MEDIUM : games.load_image("paddlemid.bmp"), 
       LARGE : games.load_image("paddleBig.bmp") } 

    def __init__(self, size): 
     """ Initialize Paddle object. """ 
     super(Paddle, self).__init__(image = Paddle.images[size], 
            y = games.mouse.y, 
            bottom = games.screen.width) 

     self.size = size 

    def update(self): 
     """ Move to mouse x position. """ 
     self.y = games.mouse.y 

     if self.top < 0: 
      self.top = 0 

     if self.bottom > games.screen.height: 
      self.bottom = games.screen.height 

     self.check_catch() 
     self.check_catch_grow() 

    def check_catch(self): 
     """ Check if ball bounces """ 

     for BouncingBall in self.overlapping_sprites: 
      BouncingBall.handle_bounce() 
    def check_catch_grow(self): 
     """ Check if ball bounces """ 

     for GrowBall in self.overlapping_sprites: 
      self.destroy() 

      new_paddle = Paddle(3) 
      games.screen.add(new_paddle) 
      GrowBall.handle_bounce() 


    def check_catch_shrink(self): 
     """ Check if ball bounces """ 

     for ShrinkBall in self.overlapping_sprites: 
      self.destroy() 
      ShrinkBall.handle_bounce() 

class BouncingBall(games.Sprite): 
    """ 
    A ball that bounces around the screen and duplicates on paddle bounce. 
    """ 
    image = games.load_image("bouncingBall.bmp") 
    speed = 1 

    def __init__(self, x, y, dx, dy): 
     """ Initialize a ball object. """ 
     super(BouncingBall, self).__init__(image = BouncingBall.image, 
            x = x, y = y,dx = decimal.Decimal(random.randrange(50,300))/100 , dy = decimal.Decimal(random.randrange(1, 3))) 

    def update(self): 
     """ Check if bottom edge has reached screen bottom. """ 
##  if self.right > games.screen.height or self.left < 0: 
##   self.dx = -self.dx 

     if self.bottom > games.screen.height or self.top < 0: 
      self.dy = -self.dy 

     if self.right > games.screen.width: 
      self.dx = -self.dx 
     if self.left < 0: 
      self.destroy() 
      self.end_game() 

    def handle_bounce(self): 
     global score 

     self.destroy() 
     new_ball = BouncingBall(x = self.x + 1, y = self.y, dx = -self.dx, dy = self.dy) 
     dup_ball = BouncingBall(x = self.x + 1, y = self.y, dx = random.randrange(1,3), dy = random.randrange(1,3)) 
     score.value += 10 
     score.right = games.screen.width - 10 




     # self.dx = -self.dx 
##  self.dy = -self.dy 

     games.screen.add(new_ball) 
     games.screen.add(dup_ball) 

    def end_game(self): 
     """ End the game. """ 

     end_message = games.Message(value = "Game Over", 
            size = 90, 
            color = color.red, 
            x = games.screen.width/2, 
            y = games.screen.height/2, 
            lifetime = 5 * games.screen.fps, 
            after_death = games.screen.quit) 
     games.screen.add(end_message) 

class ShrinkBall(games.Sprite): 
    """ 
    A ball that bounces around the screen and duplicates on paddle bounce. 
    Makes Paddle Small 
    """ 
    image = games.load_image("shrinkBall.bmp") 
    speed = 1 

    def __init__(self, x, y, dx, dy): 
     """ Initialize a ball object. """ 
     super(BouncingBall, self).__init__(image = BouncingBall.image, 
            x = x, y = y,dx = decimal.Decimal(random.randrange(50,300))/100 , dy = decimal.Decimal(random.randrange(1, 3))) 

    def update(self): 
     """ Check if bottom edge has reached screen bottom. """ 
##  if self.right > games.screen.height or self.left < 0: 
##   self.dx = -self.dx 

     if self.bottom > games.screen.height or self.top < 0: 
      self.dy = -self.dy 

     if self.right > games.screen.width: 
      self.dx = -self.dx 
     if self.left < 0: 
      self.destroy() 
      self.end_game() 

    def handle_bounce(self): 
     global score 
     new_paddle = Paddle(1) 
     games.screen.add(new_paddle) 
     self.destroy() 
     new_ball = ShrinkBall(x = self.x + 1, y = self.y, dx = -self.dx, dy = self.dy) 
     dup_ball = BouncingBall(x = self.x + 1, y = self.y, dx = random.randrange(1,3), dy = random.randrange(1,3)) 
     score.value += 10 
     score.right = games.screen.width - 10 




     # self.dx = -self.dx 
##  self.dy = -self.dy 

     games.screen.add(new_ball) 
     games.screen.add(dup_ball) 

    def end_game(self): 
     """ End the game. """ 

     end_message = games.Message(value = "Game Over", 
            size = 90, 
            color = color.red, 
            x = games.screen.width/2, 
            y = games.screen.height/2, 
            lifetime = 5 * games.screen.fps, 
            after_death = games.screen.quit) 
     games.screen.add(end_message) 


class GrowBall(games.Sprite): 
    """ 
    A ball that bounces around the screen and duplicates on paddle bounce. 
    Makes paddle larger 
    """ 
    image = games.load_image("growBall.bmp") 
    speed = 1 

    def __init__(self, x, y, dx, dy): 
     """ Initialize a ball object. """ 
     super(GrowBall, self).__init__(image = GrowBall.image, 
            x = x, y = y,dx = decimal.Decimal(random.randrange(50,300))/100 , dy = decimal.Decimal(random.randrange(1, 3))) 

    def update(self): 
     """ Check if bottom edge has reached screen bottom. """ 
##  if self.right > games.screen.height or self.left < 0: 
##   self.dx = -self.dx 

     if self.bottom > games.screen.height or self.top < 0: 
      self.dy = -self.dy 

     if self.right > games.screen.width: 
      self.dx = -self.dx 
     if self.left < 0: 
      self.destroy() 
      self.end_game() 

    def handle_bounce(self): 
     global score 

     self.destroy() 
     new_ball = GrowBall(x = self.x + 1, y = self.y, dx = -self.dx, dy = self.dy) 
     dup_ball = BouncingBall(x = self.x + 1, y = self.y, dx = random.randrange(1,3), dy = random.randrange(1,3)) 
     score.value += 10 
     score.right = games.screen.width - 10 




     # self.dx = -self.dx 
##  self.dy = -self.dy 

     games.screen.add(new_ball) 
     games.screen.add(dup_ball) 

    def end_game(self): 
     """ End the game. """ 

     end_message = games.Message(value = "Game Over", 
            size = 90, 
            color = color.red, 
            x = games.screen.width/2, 
            y = games.screen.height/2, 
            lifetime = 5 * games.screen.fps, 
            after_death = games.screen.quit) 
     games.screen.add(end_message) 

def main(): 
    wall_image = games.load_image("background.bmp", transparent = False) 
    games.screen.background = wall_image 

    the_ball = GrowBall(x = 400, y = 200, dx = 1, dy = 1) 
    games.screen.add(the_ball) 

    the_paddle = Paddle(2) 
    games.screen.add(the_paddle) 

    games.mouse.is_visible = False 

    games.screen.event_grab = True 
    games.screen.mainloop() 

main() 

Я попытался получить помощь в своем классе и не получил ответов. Я понимаю, что мой код грязный, и я уверен, что он несет в себе довольно много избытков. Когда я запускаю программу, я бегу в ошибку, гласящим:

Traceback (most recent call last): 
    File "C:\crazypong 2.0.py", line 257, in <module> 
    main() 
    File "C:\crazypong 2.0.py", line 255, in main 
    games.screen.mainloop() 
    File "C:\Python27\lib\site-packages\livewires\games.py", line 307, in mainloop 
    object._tick() 
    File "C:\Python27\lib\site-packages\livewires\games.py", line 504, in _tick 
    self.update() 
    File "C:\crazypong 2.0.py", line 44, in update 
    self.check_catch() 
    File "C:\crazypong 2.0.py", line 51, in check_catch 
    BouncingBall.handle_bounce() 
AttributeError: 'Paddle' object has no attribute 'handle_bounce' 
+1

'self.overlapping_sprites' похоже, имеет объект, который не имеет метода' handle_bounce'. – Blender

ответ

1

Я не могу найти точное livewires модуль, который вы используете, но это, кажется, что self.overlapping_spritesвключает в Paddle экземпляр в списке спрайтов. Вы можете игнорировать его тестированием на self:

for BouncingBall in self.overlapping_sprites: 
    if isinstance(BouncingBall, Paddle): continue 
    BouncingBall.handle_bounce() 

Если это не работает, то больше, чем просто текущая лопасть, перечисленная в этом списке; вам нужно будет поделиться соответствующим кодом модуля livewires, чтобы определить это более подробно.

+0

Это не сработало, и код слишком длинный для вопроса выше. –

+0

Обновлен для фильтрации * всех объектов 'Paddle'. Наверное, вы сталкиваетесь с * другим * веслом? –

+0

Прогресс был достигнут. Мне просто нужно немного подправить несколько вещей, но большое спасибо за помощь! –

Смежные вопросы