试图结束Python 3的循环



嗨,我有一个使用乌龟模块的非常基本的乒乓球游戏,我正试图添加一个游戏结束并显示一个获胜者,但在向主循环添加一个中断后,它似乎保持了循环,但中断了。。。

#Main game loop
while score_p_1<5 or score_p_2<5:
window.update()
#ball movement
ball.setx(ball.xcor() + ball.vx)
ball.sety(ball.ycor() + ball.vy)
#border detection
if ball.xcor()>300:
score_p_1 += 1
ball.setpos(0,0)
ball.vx *= -1
score_display.clear()
score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2),move=False,align="center", font=("Arial", 12, "normal"))
if ball.xcor()<-300:
score_p_2 += 1
ball.setpos(0,0)
ball.vx *= -1
#need to add to update
score_display.clear()
score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2),move=False,align="center", font=("Arial", 12, "normal"))
if ball.ycor()>290:
ball.vy = -0.05
if ball.ycor()<-290:
ball.vy = 0.05
#colision
if ball.distance(paddle1) < 25:
ball.vx = 0.05
if ball.distance(paddle2) < 25:
ball.vx = -0.05
if paddle1.ycor()>=270:
paddle1.setpos(-250,260)
if paddle1.ycor()<=-270:
paddle1.setpos(-250,-260)
if paddle2.ycor()>=270:
paddle2.setpos(250,260)
if paddle2.ycor()<=-270:
paddle2.setpos(250,-260)
#Game end
if score_p_1>=5:
break
score_display.clear()
score_display.write("Player 1 is the Winner!", font=("Arial", 20, "normal"))

这本身不是对问题的回答,而是对风格的友好改变,以避免重复并澄清正在发生的事情:

# Main game loop.
while score_p_1 < 5 or score_p_2 < 5:
window.update()
# Process ball movement.
ball.setx(ball.xcor() + ball.vx)
ball.sety(ball.ycor() + ball.vy)
# Scoring detection.
if ball.xcor() > 300 or ball.xcor() < -300:
# Who scored?
if ball.xcor() > 300:
score_p_1 += 1
elif ball.xcor() < -300:
score_p_2 += 1
# Reset.
ball.setpos(0, 0)
ball.vx *= -1
score_display.clear()
score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2), move=False, align="center", font=("Arial", 12, "normal"))
# Bouncing against walls.
if abs(ball.ycor()) > 290:
ball.vy = -0.05 * np.sign(ball.ycor())
# Ball/paddle collision.
for paddle in (paddle1, paddle2):
if ball.distance(paddle) < 25:
ball.vx = +0.05 if paddle is paddle1 else -0.05
# Wall/paddle collision.
for paddle in (paddle1, paddle2):
x = -250 if paddle is paddle1 else +250
y = np.clip(paddle.ycor(), -260, +260) # <- Ensures the paddles stay in [-260, +260].
paddle.setpos(x, y)
# Game end. No need for a break, it's already in the while condition.
if score_p_1 >= 5:
winner = 1
elif score_p_2 >= 5:
winner = 2
score_display.clear()
score_display.write(f"Player {winner} is the Winner!", font=("Arial", 20, "normal"))

最新更新