因此,基本上,我正在构建乒乓球比赛的计分系统。全局变量s_a为0,应该在球反弹后改变。
import turtle
import time
win = turtle.Screen()
win.title("Pong")
win.bgcolor("black")
win.setup(width=800, height=600)
win.tracer(0)
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
s_a = 0
s_s = turtle.Turtle()
s_s.speed(0)
s_s.hideturtle()
s_s.goto(0, 0)
s_s.penup()
s_s.color("white")
current_score = "Player A: {} | Player B: 0".format(s_a)
s_s.write(current_score, align="center", font=("Courier", 16, "normal"))
while True:
win.update()
time.sleep( 1 / 60 )
ball.setx(ball.xcor() + ball.dx)
if ball.xcor() > 380:
s_a += 1
ball.goto(0,0)
球会像预期的那样重置自身并改变方向,但是变量不会更新。我错过了什么吗?
答案 0 :(得分:0)
是的,请在更新值之前输入Global,
像global s_a
答案 1 :(得分:0)
尝试清除屏幕然后写入屏幕,您不需要全局变量,它们通常是个坏主意:
pkg load statistics
答案 2 :(得分:0)
您的代码确定。您应该只在屏幕上重新打印分数。我的意思是添加
current_score = "Player A: {} | Player B: 0".format(s_a)
s_s.clear()
s_s.write(current_score, align="center", font=("Courier", 16, "normal"))
在更新s_a
之后,最后一行之前。