Exitonclick() not working when I add a while loop

Hi everyone,
Just wondering why exitonclick() is working perfectly with turtle in pycharm until I add a while loop. After this exitonclick stops working.

Impossible to know unless you post your code. Please paste as text
between triple backticks:

 ```
 your code
 goes here
 ```

Thanks,
Cameron Simpson cs@cskk.id.au

‘’’
import time
from turtle import Screen
from food import Food
from scoreboard import Scoreboard
from snake import Snake

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor(“black”)
screen.title(“My Snake Game”)
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, “Up”)
screen.onkey(snake.down, “Down”)
screen.onkey(snake.left, “Left”)
screen.onkey(snake.right, “Right”)

game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
snake.move()

if snake.head.distance(food) < 15:
    food.refresh()
    scoreboard.increase_score()

if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
    game_is_on = False
    scoreboard.game_over()

for segment in snake.segments:
    if segment == snake.head:
        pass
    elif snake.head.distance(segment) < 10:
        game_is_on = False
        scoreboard.game_over()

screen.exitonclick()
‘’’

Thank you Cameron,
This is the main file. Would you need the other files that I am importing from?

Just a note: those are triple ASCII single quote marks, which don’t work
as code fences. See how only the indented part of your code is fixed
width? You want triple backticks, these:

 ```

On my keyboard that’s at top left under the tilde (~), but it may
vary. There’s also a control on the composition window looking like
</> which inserts a set of code fences for you.

Anyway, to your code:

 screen.listen()
 screen.onkey(snake.up, "Up")
 screen.onkey(snake.down, "Down")
 screen.onkey(snake.left, "Left")
 screen.onkey(snake.right, "Right")

 game_is_on = True
 while game_is_on:
     screen.update()
     time.sleep(0.1)
     snake.move()
     [...... snip ....]

 screen.exitonclick()

The reason this is ineffective is that the screen.exitonclick()
function is not called until after the while-loop completes. So while
the loop is running, exitonclick has not been called yet.

Try moving it to before the while-loop.

Cheers,
Cameron Simpson cs@cskk.id.au

Unfortunately this did not work

import time
from turtle import Screen
from food import Food
from scoreboard import Scoreboard
from snake import Snake


screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")



game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    if snake.head.distance(food) < 15:
        food.refresh()
        scoreboard.increase_score()

    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
        game_is_on = False
        scoreboard.game_over()

    for segment in snake.segments[1:]:
        if snake.head.distance(segment) < 10:
            game_is_on = False
            scoreboard.game_over()

screen.exitonclick()

C:\Users\User\PycharmProjects\pythonProject\snake_game\venv\Scripts\python.exe C:/Users/User/PycharmProjects/pythonProject/snake_game/main.py
Traceback (most recent call last):
File “C:\Users\User\PycharmProjects\pythonProject\snake_game\main.py”, line 17, in
scoreboard = Scoreboard()
File “C:\Users\User\PycharmProjects\pythonProject\snake_game\scoreboard.py”, line 13, in init
self.update_scoreboard()
File “C:\Users\User\PycharmProjects\pythonProject\snake_game\scoreboard.py”, line 16, in update_scoreboard
self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)
File “C:\Users\User\AppData\Local\Programs\Python\Python310\lib\turtle.py”, line 3433, in write
end = self._write(str(arg), align.lower(), font)
File “C:\Users\User\AppData\Local\Programs\Python\Python310\lib\turtle.py”, line 3404, in _write
item, end = self.screen._write(self._position, txt, align, font,
File “C:\Users\User\AppData\Local\Programs\Python\Python310\lib\turtle.py”, line 595, in _write
item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align],
KeyError: ‘centre’

Process finished with exit code 1

This is the error message

This code still has exitonclick after the while-loop.

This traceback raises its exception inside the scoreboard.py file, which you have not shown us. I’ll remind you that our American friends spell “centre” as “center”, which may be relevant to the alignment KeyError :slight_smile:

1 Like

Cameron Simpson you are the absolute man. It’s working. So you are telling me the code would not run all because of “centre” not being “center”?

Well, the KeyError is a result of accessing a dict (or other
mapping) with a value which isn’t present. Look at the stack trace from
your error:

 C:\Users\User\PycharmProjects\pythonProject\snake_game\venv\Scripts\python.exe C:/Users/User/PycharmProjects/pythonProject/snake_game/main.py
 Traceback (most recent call last):
   File "C:\Users\User\PycharmProjects\pythonProject\snake_game\main.py", line 17, in <module>
     scoreboard = Scoreboard()
   File "C:\Users\User\PycharmProjects\pythonProject\snake_game\scoreboard.py", line 13, in __init__
     self.update_scoreboard()
   File "C:\Users\User\PycharmProjects\pythonProject\snake_game\scoreboard.py", line 16, in update_scoreboard
     self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)
   File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 3433, in write
     end = self._write(str(arg), align.lower(), font)
   File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 3404, in _write
     item, end = self.screen._write(self._position, txt, align, font,
   File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 595, in _write
     item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align],
 KeyError: 'centre'

This clearly shows a failure to look up the string 'centre' on the
last line.

The line above that is the line of code being executed when the failure
happened. The exception is almost certainly from the anchor[align]
part of the expression because KeyError is a lookup error, and that is
the only lookup.

Looking further back in the recited lines, the value for align seems
to come from your call:

 self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)

which suggests that the value of ALIGNMENT may be incorrect.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like