简体   繁体   中英

I am making a pong game but the ball is malfunctioning

I just started making a pong game for a beginner project that I decided to try, and I've been getting some problems. Whenever I run my code, the ball just teleports to near "paddle_a".

import turtle
wn = turtle.Screen()
wn.title("Pong by AyyEffKayy")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer()

# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.penup()
paddle_a.goto(-350, 0)
paddle_a.shapesize(stretch_wid=5, stretch_len=1)

# Paddle B

paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.penup()
paddle_b.goto(350, 0)
paddle_b.shapesize(stretch_wid=5, stretch_len=1)

# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2

# functions
def paddle_a_up():
    y = paddle_a.ycor()
    y += 20
    paddle_a.sety(y)

def paddle_a_down():
    y = paddle_a.ycor()
    y -= 20
    paddle_a.sety(y)

def paddle_b_up():
    y = paddle_b.ycor()
    y += 20
    paddle_b.sety(y)

def paddle_b_down():
    y = paddle_b.ycor()
    y -= 20
    paddle_b.sety(y)

# key listening
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")

# ball movement
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)

# border checking
if ball.ycor() > 290:
    ball.sety(290)
    ball.dy *= -1

if ball.xcor() > -290:
    ball.setx(-290)
    ball.dx *= -1

# game loop
while True:
    wn.update()

I'm not sure if it's because I'm using Pycharm instead of VSCode Python, but other than that, it should work. Any help?

You are only calling the functions to move the ball once. Write something like this:

# game loop
while True:
    wn.update()
    time.sleep(.1)
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)

But you still need to implement collision with the paddles: :)

You are also not checking collision with the sides sides yet, that is just done once, outside the loop, and not for all sides. And the code to make the ball turn is a bit wonky too. Good luck: :)

The IDE you are using (pycharm or vs code) should have no effect one the code itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM