Search code examples
python-3.xpython-turtle

I get an error, but I don't find it (Python)


I'm trying to create a game with turtle. It consists in moving a paddle and don't make the ball fall. I'm a beginner. This is the program:

import turtle

width,height = 800, 600
score = 0

wn = turtle.Screen()
wn.title('Breakout')
wn.bgcolor('black')
wn.setup(width,height)
wn.tracer()

# Paddle
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape('square')
paddle.shapesize(stretch_wid=5, stretch_len=1)
paddle.color('white')
paddle.penup()
paddle.left(90)
paddle.goto(0, -287)

# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.goto(0,0)
ballx = 3
bally = -3

# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write('Score: 0', align='center', font=('Courier', 24, 'normal'))

# Paddle movement
def paddle_right():
    x = paddle.xcor()
    x -= 20
    paddle.setx(x)

def paddle_left():
    x = paddle.xcor()
    x += 20
    paddle.setx(x)

wn.listen()
wn.onkeypress(paddle_right, 'a')
wn.onkeypress(paddle_left, 'd')


while True:
    wn.update()
    
    ball.setx(ball.xcor() + ballx)
    ball.sety(ball.ycor() + bally)

    # Borders
    if ball.xcor() > 390:
        ball.setx(390)
        ballx *= -1

    if ball.xcor() < -390:
        ball.setx(-390)
        ballx *= -1

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

    if ball.ycor() < -290:
        ball.goto(0, 0)
        bally *= -1
        score -= 1
        pen.clear()
        pen.write('Score: {}'.format(score), align='center', font=('Courier', 24, 'normal')

    # Paddle and ball collision
    elif (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle.ycor() + 40 and ball.ycor() > paddle.ycor() - 40):
        ball.setx(340)
        ballx *= -1

I get error for the last lines of code. Hier it is:

elif (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle.ycor() + 40 and ball.ycor() > paddle.ycor() - 40):
       ^
SyntaxError: invalid syntax
[Finished in 0.2s with exit code 1]

I don't even know if what I wrote in the last lines of code is right. Want to make the ball return if it hits the paddle. Verison of python: 3.7.3


Solution

  • You missed a closing parenthesis in this line

    pen.write('Score: {}'.format(score), align='center', font=('Courier', 24, 'normal'))