[Python] Why isn't there a screen that pops up to show the snake game?

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    Why isn't there a screen that pops up to show the snake game? I don't see the issue with my code. Here is my code if it can help.

    from turtle import Screen, Turtle

    from snake import Snake

    import time


    screen = Screen()

    screen.setup(width=600, height=600)

    screen.bgcolor("black")

    screen.title("My Snake Game")

    screen.tracer(0)

    snake = Snake()

    screen.listen()

    screen.onkey(snake.move_up, "Up")

    screen.onkey(snake.move_down,"Down")

    screen.onkey(snake.move_left, "Left")

    screen.onkey(snake.move_right,"Right")

    game_is_on = True

    while game_is_on:

    screen.update()

    time.sleep(0.1)

    snake.move()

    screen.exitonclick()


    Also there is a side file that I've created called snake.py that I use in the main.py file, here it is :

    from turtle import Turtle

    STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]

    MOVE_DISTANCE = 20

    UP = 90

    DOWN = 270

    LEFT = 180

    RIGHT = 0

    class Snake:

    def __init__(self):
    self.segments = []
    self.create_snake()
    self.head = self.segments[0]
    def create_snake(self):
    for position in STARTING_POSITIONS:
    new_segment = Turtle("square")
    new_segment.color("white")
    new_segment.penup()
    new_segment.goto(position)
    self.segments.append(new_segment)


    def move(self):
    for seg_num in range(len(self.segments) - 1, 0, -1):
    new_x = self.segments[seg_num - 1].xcor()
    new_y = self.segments[seg_num - 1].ycor()
    self.segments[seg_num].goto(new_x, new_y)
    self.head.forward(MOVE_DISTANCE)

    def move_left(self):
    if self.head.heading() != RIGHT:
    self.head.setheading(LEFT)

    def move_right(self):
    if self.head.heading() != LEFT:
    self.head.setheading(RIGHT)

    def move_up(self):
    if self.head.heading() != DOWN:
    self.head.setheading(UP)

    def move_down(self):
    if self.head.heading() != UP:
    self.head.setheading(DOWN)

    Continue reading...

Compartilhe esta Página