Python screen crashes after I use screen.tracer(0)

36 Views Asked by At

This is my code:

from turtle import Screen, Turtle

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

starting_position =[(0, 0), (-20, 0), (-40,  0)]
segments = []
game_is_on = True
for position in starting_position:
    new_segment = Turtle("square")
    new_segment.color("white")
    new_segment.penup()
    new_segment.goto(position)
    segments.append(new_segment)
screen.update()
while game_is_on:
    for seg in segments:
        seg.forward(20)

screen.exitonclick()

I wrote another code to draw a hrist painting and is crashed as well.

I am trying to build a snake game. After I use the screen.tracer(0), the screen freezes and I cant do nothing. The screen closes only if I forcefully closed it.

That`s the screen:

1

There are 1 best solutions below

0
ggorlen On

while True: is an infinite loop. The CPU is slammed trying to run this as fast as it can (top output on Ubuntu for your original code):

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND  
1361630 greg      20   0   43976  22868  11136 R 100.3   0.1   0:08.17 python3 

CPU is maxed out at 100%.

Instead of while True:, use ontimer, which runs at a fairly consistent speed and gives time between frames for the process and CPU to do other things:

from turtle import Screen, Turtle


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

starting_position = [(0, 0), (-20, 0), (-40,  0)]
segments = []
game_is_on = True

for position in starting_position:
    new_segment = Turtle("square")
    new_segment.color("white")
    new_segment.penup()
    new_segment.goto(position)
    segments.append(new_segment)


def tick():
    if not game_is_on:
        return

    for seg in segments:
        seg.forward(20)

    screen.update()
    screen.ontimer(tick, 1000 // 5)  # ~5 FPS


tick()
screen.exitonclick()  # side benefit: now this is reachable

Now top is happy:

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND  
1362623 greg      20   0   41924  21300  11520 S   0.3   0.1   0:00.20 python3

See also Turtle animation is so fast in python. The answer is the same but the question is a bit different, because in that question, the code is calling .update() in the while True: loop, while in this question, .update() isn't called in the loop