Привет, вы все новички в 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()