Python 乒乓游戏在 1 点后不增加点数

Python Pong Game not increasing point after 1

所以我尝试用 turtle 在 Python 中制作 Pong 游戏,除一件事外一切正常。当 player_score 达到 1 点时,它不再增加。还有一个烦人的事情,有谁知道为什么我移动球拍时球变慢了?

这是我的代码:

我觉得这部分代码没问题

from turtle import *

# Creating screen
court = Screen()
court.title("Bricket Pong v 0.2")
court.setup(width=800, height=600)
court.bgcolor('black')
court.tracer(0)

# Creating ball
ball = Turtle()
ball.shape("circle")
ball.color("green")
ball.penup()
ball.setpos(0, 0)

# Creating ball movement speed
def init():
    global ball, want_continue
    ball.step_x = 0.5
    ball.step_y = 0.5
    ball.setpos(0, 0)
    want_continue = True


def on_quit():
    global want_continue
    want_continue = False


court.onkey(on_quit, "q")
court.listen()

# Creating point screen
point = Turtle()
point.speed(0)
point.color('blue')
point.penup()
point.hideturtle()
point.goto(0,260)
point.write("Player: 0 ",align="center",font=('Monaco',24,"normal"))


racket = Turtle()
racket.hideturtle()
racket.shape("square")
racket.color("white")
racket.penup()
racket.goto(0, -285)
racket.shapesize(1, 3)
racket.showturtle()

# Creating arrows to move the racket
def racket_left():
    x =racket.xcor()
    x = x - 15
    racket.setx(x)


def racket_right():
    x = racket.xcor()
    x = x + 15
    racket.setx(x)

court.listen()

court.onkeypress(racket_left, "Left")
court.onkeypress(racket_right, "Right")

问题一定是在move_ball def.

# Creating borders to the ball
def move_ball():
    global ball
    player_score = 0
    if ball.xcor() > 390 or ball.xcor() < -390:
        ball.step_x *= -1

    if ball.ycor() > 290:
        ball.step_y *= -1

    if ball.ycor() < -290:
        ball.setpos(0, 0)
        ball.step_y *= -1
        player_score= 0
        point.clear()
        point.write("Player: {} ".format(player_score), align="center", font=('Monaco', 24, "normal"))


    ball.setx(ball.xcor() + ball.step_x)
    ball.sety(ball.ycor() + ball.step_y)

#Racket ball border
    if (ball.ycor() < - 265) and ball.ycor() > - 275 \
            and (racket.xcor() + 30 > ball.xcor() > racket.xcor() - 30) :
        ball.step_y = ball.step_y * -1
        player_score += 1 
        point.clear()
        point.write("Player: {}".format(player_score),align="center",font=('Monaco',24,"normal"))

def run():
    global ball, want_continue
    while want_continue:
        move_ball()
        court.update()





#
init()
run()

court.bye()

您在 move_ball() 函数的顶部不断将 player_score 设置为零(因此,在 run() 中通过 while 循环的每个循环) -- 你必须在别处初始化它并在不重置它的情况下递增它。

要解决您的问题,您可以在 碰撞函数 之前定义例如 score_a = 0score_b = 0,然后在每次球碰撞时更新分数。 您可以将 格式化字符串 显示为 print(f"Player A: {score_a} Player B: {score_b}")print("Player A: {} Player B: {}".format)

小球碰撞变慢的问题是代码方式的问题。球的移动是通过将一些 int 值添加到球的当前 (x,y) 坐标来完成的。每次屏幕更新时都会添加此值。循环在一帧中尽可能多地更新位置。但是由于每秒 CPU 速度变化,球似乎移动不一致。

要获得更一致的行为,您可以在循环中添加足够长的暂停,以抵消计算时间的可变性并避免绘制无用的帧。您可以使用 time

执行此操作
import time

# Initialization
...

while True:
   time.sleep(1 / 60)

   # The rest of your game logic
   ...