[Python] How can I fix the ; AttributeError when using a CLASS in Python. Even though i...

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    Below is my code, but it gives me an attribute error even though i have the attribute variable initialized. When I tried to access it inside a method of the class, it raised an attribute error. Here is the error it got. in my terminal: AttributeError: 'Ball' object has no attribute 'move_x'

    To provide more details, when I import the Ball class from the ball file inside the main file and run the code, this is when it gives me the error. Look at the code below to have an idea, please. Any help or suggestion will make my day.

    from turtle import Turtle
    import random

    class Ball(Turtle):
    direction = [0, 90, 180, 270]
    def __int__(self):
    super().__init__()
    self.shape("circle")
    self.color("red")
    self.shapesize(stretch_len=0.5, stretch_wid=0.5)
    self.penup()
    self.goto(0, 0)
    self.move_x = 10
    self.y_move = 10
    self.move_speed = 0.1

    def create_ball(self):
    self.showturtle()
    self.setheading(random.choice(Ball.direction))

    def move_ball(self):
    random_x = self.xcor() + self.move_x
    random_y = self.ycor() + self.y_move
    self.goto(random_x, random_y)

    def bounce_ball_x(self):
    self.move_x *= -1
    self.move_speed *= 0.9

    def bounce_ball_y(self):
    self.y_move *=-1


    ***Main file

    from turtle import Turtle, Screen
    import time
    from paddle import Paddle
    from bricks import Brick
    from ball import Ball
    import random

    turtle = Turtle()
    screen = Screen()
    screen.title("Breakout Game")
    screen.setup(width=920, height=700)
    turtle.hideturtle()
    screen.bgcolor("black")
    screen.tracer(0, 0)

    paddle = Paddle()
    brick = Brick()
    screen.listen()
    ball = Ball()

    screen.onkeypress(paddle.move_left, "Left")
    screen.onkeypress(paddle.move_right, "Right")

    game_is_on = True

    def show_bricks():
    position_x = 500
    position_y = 400
    colors = ["blue", "orange", "purple", "green"]
    choose_color = -1

    for i in range(1, 97):
    color = colors[choose_color]
    brick.create_bricks( position_x, position_y, color)
    position_x -= 100
    if i % 12 == 0:
    position_x = 500
    position_y -= 50

    if i % 24 == 0:
    choose_color += 1

    show_bricks()

    while game_is_on:
    screen.update()
    ball.move_ball()

    if ball.ycor() > 330 or ball.ycor() < -330:
    ball.bounce_ball_x()

    if ball.xcor() > 430 or ball.xcor() < -430:
    ball.bounce_ball_y()

    if paddle.is_at_finish_line():
    paddle.bounce()

    screen.exitonclick()

    Continue reading...

Compartilhe esta Página