1

So basically, I´m buildig the scoring system for a pong game. The global variable s_a is 0 and supposed to change after the ball goes out of bounce.

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)

The ball resets itself and changes direction like supposed to, however the variable doesn´t update. Did I miss something?

kreszy
  • 37
  • 5
  • 4
    Does this answer your question? https://stackoverflow.com/questions/423379/using-global-variables-in-a-function if not, maybe there's some kind of logic error in your program, its hard to say as you haven't included all the relevant code – Hymns For Disco Dec 22 '19 at 13:06
  • This code looks fine from a glance. You need to provide a [mre]. Maybe your main loop is running in a different scope? – wjandrea Dec 22 '19 at 17:51
  • 1
    Maybe better question would be- how do you know, that ```s_a``` is not updated? You don't print it inside your ```while``` loop? Where exactly are you validating, that it's still ```0```? – Grzegorz Skibinski Dec 22 '19 at 18:44

3 Answers3

0

Yes Please write Global before you updating the value, like global s_a

  • Program now fails to run. I´ve alos tried `global s_a` `s_a +=1`, but it still fails. Any suggestions? – kreszy Dec 22 '19 at 14:11
0

Try clear the screen then write to it, you don't need global variables, they're usually a bad idea:

while True:
    win.update()
    time.sleep(1/60)
    ball.setx(ball.xcor() + ball.dx)
    if ball.xcor() > 380:
        s_a += 1
        current_score = "Player A: {} | Player B: 0".format(s_a)
        s_s.clear()
        s_s.write(current_score, align="center", font=("Courier", 16, "normal"))
        ball.goto(0, 0)
BpY
  • 403
  • 5
  • 12
0

Your code is OK. You should just re-print the scores on the screen. I mean add

current_score = "Player A: {} | Player B: 0".format(s_a)
s_s.clear()
s_s.write(current_score, align="center", font=("Courier", 16, "normal"))

after updating s_a before last line.

Seyfi
  • 1,832
  • 1
  • 20
  • 35