简体   繁体   English

我正在做乒乓球比赛,但球出现故障

[英]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".每当我运行我的代码时,球就会传送到“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.我不确定是不是因为我使用的是 Pycharm 而不是 VSCode Python,但除此之外,它应该可以工作。 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.您正在使用的 IDE(pycharm 或 vs 代码)应该对代码本身没有任何影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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