python - 在乒乓球中将球弹到墙上和桨上

标签 python pygame pong

大家好,我对Python很陌生,我正在努力检测墙壁(屏幕的边缘)并让我的球在撞到墙上时弹跳。我已经搜索过如何使用,但大多数人使用海龟或其他我无法使用的东西,所以它没有多大帮助。我得到了如何检测墙壁的算法,但只是不知道如何正确编写代码。下面是我的代码,如果有人能给我任何关于如何为此编写代码的想法,我将非常感激。

这是我从第 62 行不断收到的确切错误消息。 错误消息:

builtins.AttributeError: 'Ball' object has no attribute 'get_rect'
line 62 -> self.ballrect = self.ball.get_rect()

这是完整的代码

import pygame
from random import randint


# User-defined functions

def main():
   # initialize all pygame modules (some need initialization)
   pygame.init()
   # create a pygame display window
   pygame.display.set_mode((500, 400))
   # set the title of the display window
   pygame.display.set_caption('Pong')   
   # get the display surface
   w_surface = pygame.display.get_surface() 
   # create a game object
   game = Game(w_surface)
   # start the main game loop by calling the play method on the game object
   game.play() 
   # quit pygame and clean up the pygame window
   pygame.quit() 


# User-defined classes

class Game:
   # An object in this class represents a complete game.

   def __init__(self, surface):
      # Initialize a Game.
      # - self is the Game to initialize
      # - surface is the display window surface object

      # === objects that are part of every game that we will discuss
      self.surface = surface
      self.bg_color = pygame.Color('black')

      self.FPS = 60
      self.game_Clock = pygame.time.Clock()
      self.close_clicked = False
      self.continue_game = True

      # === game specific objects    
      self.ball = Ball('white', 5, [250, 200], [1, 2], self.surface)
      self.max_frames = 150
      self.frame_counter = 0

   def play(self):
      # Play the game until the player presses the close box.
      # - self is the Game that should be continued or not.

      while not self.close_clicked:  # until player clicks close box
         # play frame
         self.handle_events()         
         self.draw()   
         self.ballrect = self.ball.get_rect()
         self.ballrect = ballrect.move(speed)
         if self.ballrect.left < 0 or self.ballrect.right > 500:
            speed[0] = -speed[0]
         if self.ballrect.top < 0 or self.ballrect.bottom > 400:
            speed[1] = -speed[1]          
         if self.continue_game:
            self.update()
            self.decide_continue()
         self.game_Clock.tick(self.FPS) # run at most with FPS Frames Per Second 



   def handle_events(self):
      # Handle each user event by changing the game state appropriately.
      # - self is the Game whose events will be handled

      events = pygame.event.get()
      for event in events:
         if event.type == pygame.QUIT:
            self.close_clicked = True

   def draw(self):
      # Draw all game objects.
      # - self is the Game to draw

      self.surface.fill(self.bg_color) # clear the display surface first
      pygame.draw.rect(self.surface, (255, 255, 255), (75, 190, 5, 20))
      pygame.draw.rect(self.surface, (255, 255, 255), (420, 190, 5, 20))       
      self.ball.draw()
      pygame.display.update() # make the updated surface appear on the display


   def update(self):
      # Update the game objects for the next frame.
      # - self is the Game to update

      self.ball.move()
      self.frame_counter += self.frame_counter 




   def decide_continue(self):
      # Check and remember if the game should continue
      # - self is the Game to check

      if self.frame_counter > self.max_frames:
         self.continue_game = False


class Ball:
   # An object in this class represents a Dot that moves 

   def __init__(self, ball_color, ball_radius, ball_center, ball_velocity, 
                surface):
      # Initialize a Dot.
      # - self is the Dot to initialize
      # - color is the pygame.Color of the dot
      # - center is a list containing the x and y int
      #   coords of the center of the dot
      # - radius is the int pixel radius of the dot
      # - velocity is a list containing the x and y components
      # - surface is the window's pygame.Surface object

      self.color = pygame.Color(ball_color)
      self.radius = ball_radius
      self.center = ball_center
      self.velocity = ball_velocity
      self.surface = surface



   def move(self):
      # Change the location of the Dot by adding the corresponding 
      # speed values to the x and y coordinate of its center
      # - self is the Dot

      for i in range(0,2):
         self.center[i] = (self.center[i] + self.velocity[i])
   def update(self):
      self.rect.x += self.velocity[0]
      self.rect.y += self.velocity[1]

   def bounce(self):
      self.velocity[0] = -self.velocity[0]
      self.velocity[1] = randint(-8,8)


   def draw(self):
      # Draw the dot on the surface
      # - self is the Dot

      pygame.draw.circle(self.surface, self.color, self.center, self.radius)






main()

最佳答案

You Ball 类需要一个 rect 属性。

class Ball:
   # An object in this class represents a Dot that moves 

   def __init__(self, ball_color, ball_radius, ball_center, ball_velocity, 
                surface):
      # Initialize a Dot.
      # - self is the Dot to initialize
      # - color is the pygame.Color of the dot
      # - center is a list containing the x and y int
      #   coords of the center of the dot
      # - radius is the int pixel radius of the dot
      # - velocity is a list containing the x and y components
      # - surface is the window's pygame.Surface object

      self.color = pygame.Color(ball_color)
      self.radius = ball_radius
      self.center = ball_center
      self.velocity = ball_velocity
      self.surface = surface

      # create a Rect with width and height equal to radius,
      # then place it at the center of the ball
      self.rect = pygame.Rect(0, 0, self.radius, self.radius)
      self.rect.center = self.center

此外,在更新中,您需要再次将 self.rect.center 设置为 self.center,否则它将保持原样。 或者您完全摆脱 self.center 并只使用 self.rect.center 因为这是多余的信息。

关于python - 在乒乓球中将球弹到墙上和桨上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511444/

相关文章:

python - Pygame 碰撞检测无法按我想要的方式工作

python - Pygame:细胞重新合并在一起

java - 乒乓 Racket 不停地晃动,不停留在一个位置上

python - 如何将球反射到 Racket 上

java - 为什么我的碰撞检测无法正常工作?

python - 如何使用 python3 -i 加载脚本,但没有 name == main run?

python - 如何使算法更快?

python - 如何防止使用相同值创建新 SQLAlchemy 对象的 UUID 主键

python - 如何将 pygame 应用程序转换为 iOS 应用程序

python - 具有两列的组合框