Search code examples
pythonpong

Python Pong Game not increasing point after 1


So I've tried to make a Pong game in Python with turtle, everything is working except one thing. When the player_score reach 1 point its not increasing anymore. And an annoying thing, does anybody know why is the ball slow down when i move the racket?

Here is my code:

I think this part of the code is okay.

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")

The problem is must be here in 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()

Solution

  • You're continually setting the player_score to zero, at the top of the move_ball() function (so, every cycle through the while loop in run()) -- you'll have to initialize it somewhere else and increment it without resetting it.