🌐
GitHub
gist.github.com › wynand1004 › ec105fd2f457b10d971c09586ec44900
A Simple Snake Game made in Python 3 · GitHub
A Simple Snake Game made in Python 3. GitHub Gist: instantly share code, notes, and snippets.
🌐
101 Computing
101computing.net › home › python challenges › snake game using python
Snake Game Using Python - 101 Computing
August 9, 2024 - The games ends when the player either redirects the snake over the edges of the screen or when the snakes eats/crosses over its own tail. Let’s first use a structure diagram to recap the key components of this game: To implement this game we will use Object Oriented Programming. We will use the Python Turtle library to create the Graphical User Interface of this game.
Discussions

Snake game in a single line of python
PEP: "Screaming noises" More on reddit.com
🌐 r/Python
153
855
August 21, 2020
Snake game in Python using Turtle graphics - Stack Overflow
So I've been working on a few games in Python (battleships, tic-tac-toe etc.) and this week's project is Snake. I've got a basic set-up going; the snake can move and eats the food but I haven't programmed in collision detection or going off the edge yet. The problem is response time. If you run the code ... More on stackoverflow.com
🌐 stackoverflow.com
Pygame Code: Snake Game
Code for Pygame: Snake Game. import pygame from pygame.locals import * class Snake: def ___init__(self,parent_screen): self.parent_screen = parent_screen self.block = pygame.image.load("resources/block.jpg").convert() self.x =100 self.y =100 def draw (self): self.parent_screen.fill((110, 110, ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
December 6, 2022
Making a Snake Game Without Following a Tutorial
Figuring that part out yourself is a good exercise. You'll often need to think through all the constituent parts of a project yourself, so you might as start practicing that skill now. I'd just start. You'll make mistakes and odd design decisions as you learn what you don't know and didn't think of, but that isn't really a problem if the purpose is learning. More on reddit.com
🌐 r/learnpython
9
6
October 12, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › python › snake-game-in-python-using-pygame-module
Snake Game in Python - Using Pygame module - GeeksforGeeks
Finally, we set up two boolean ... be analyzed for player input. The code sets up a basic game window with a snake positioned at (100, 50) on the X-axis and (window_x, window_y) on the Y-axis....
Published   July 23, 2025
🌐
Edureka
edureka.co › blog › snake-game-with-pygame
How To Write Python Code for Snake Game using Pygame?
March 11, 2025 - Snake Game in Python using Pygame which is free and open-source Python library used to create games.Create snake,add food,increase snakesize,score,etc.
🌐
Towards Data Science
towardsdatascience.com › home › latest › implementing the snake game in python
Implementing the Snake Game in Python | Towards Data Science
February 12, 2026 - First of all, we will import the Turtle module, specifically its Screen and Turtle classes. ... The Turtle Module is a built-in Python package that allows one to draw shapes, lines, patterns, and animations on a screen through code.
🌐
Reddit
reddit.com › r/python › snake game in a single line of python
r/Python on Reddit: Snake game in a single line of python
August 21, 2020 -

This is a fully functional game of snake in a single line of python using pygame. I did this mostly as a challenge to myself to see how compact I can make code, similar to code golf. I got it down to less than 3K characters, but I could easily get much less by shortening variable names.

source code

edit: some bug fixes made it go over 3K chars

🌐
Python Engineer
python-engineer.com › posts › snake-game-in-python
Snake Game In Python - Python Beginner Tutorial - Python Engineer
import curses from random import randint # setup window curses.initscr() win = curses.newwin(20, 60, 0, 0) # y,x win.keypad(1) curses.noecho() curses.curs_set(0) win.border(0) win.nodelay(1) # -1 # snake and food snake = [(4, 10), (4, 9), (4, 8)] food = (10, 20) win.addch(food[0], food[1], '#') # game logic score = 0 ESC = 27 key = curses.KEY_RIGHT while key != ESC: win.addstr(0, 2, 'Score ' + str(score) + ' ') win.timeout(150 - (len(snake)) // 5 + len(snake)//10 % 120) # increase speed prev_key = key event = win.getch() key = event if event != -1 else prev_key if key not in [curses.KEY_LEFT,
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-a-snake-game-using-turtle-in-python
Create a Snake-Game using Turtle in Python - GeeksforGeeks
February 18, 2026 - The Snake Game is a classic arcade game first released in 1976 by Gremlin Industries and published by Sega. The goal is simple to control the snake using arrow keys, collect food to grow longer and avoid hitting the walls or yourself. We’ll build this game in Python using the following modules:
Find elsewhere
🌐
Medium
medium.com › @wepypixel › step-by-step-guide-python-code-for-snake-game-development-3e0ec9f7522e
Step-by-Step Guide: Python Code for Snake Game Development | by Stilest | Medium
June 7, 2023 - Set the delay for the game (the speed at which the snake moves). Initialize the score and high-score variables. import turtle import time import random delay = 0.1 # Score score = 0 high_score = 0 · Set up the game window using the python’s turtle module.
🌐
The Python Code
thepythoncode.com › article › make-a-snake-game-with-pygame-in-python
How to Make a Snake Game in Python - The Python Code
Learn how to build a classic snake game using Pygame in Python. This detailed step-by-step tutorial explains how to initialize Pygame, generate food for the snake, draw game objects, update the snake's position, handle user input, and manage the game loop. Suitable for beginner to intermediate ...
🌐
Geekedu
geekedu.org › blogs › python-game-for-kids-python-snake-game
Python Game for Kids: Python Snake Game | Coding for Kids Free
Regardless of your proficiency with Python, this project is a great way to learn more about making functional programs by creating a fun and simple game to play with friends. ... This is a beginner-level project for those who are new to Python. Before starting this project, you should already have experience with functions, if-statements, and the Python Turtle library, as these are the concepts that you will use and build upon as you code this project. This program focuses on creating simple graphics using Turtle, and creating functions that can be used to control the snake as well as other elements of gameplay.
🌐
ItsMyBot
itsmybot.com › home › python programming › how to create a snake game in python: step-by-step guide
How to Create a Snake Game in Python: Step-by-Step Guide
April 22, 2026 - # Increase speed based on score snake_speed = 15 + (Length_of_snake // 5) clock.tick(snake_speed) # Rest of the code... ... Once your game is complete and thoroughly tested, consider deploying it so others can play it. Use tools like PyInstaller to convert your Python script into a standalone executable.
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
CodeWithCurious
codewithcurious.com › home › snake game using python with source code
Snake Game Using Python With Source Code - CodeWithCurious
September 22, 2024 - In this project, we have created a snake game using a python module named “Pygame”. Basically, in this game, the user will control the movement of the snake through the keyboard arrows and direct the snake in the direction of food, as the ...
Top answer
1 of 3
7

Whenever you use while True: (sans break) in turtle code, you're defeating the event hander. You should instead use an ontimer() event to run your code compatibly with the event handler. Below is my rewrite of your code to do this along with some other functional and style tweaks:

from turtle import Turtle, Screen
import random
import time

SIZE = 20

class Square:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def drawself(self, turtle):
        """ draw a black box at its coordinates, leaving a small gap between cubes """

        turtle.goto(self.x - SIZE // 2 - 1, self.y - SIZE // 2 - 1)

        turtle.begin_fill()
        for _ in range(4):
            turtle.forward(SIZE - SIZE // 10)
            turtle.left(90)
        turtle.end_fill()

class Food:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.is_blinking = True

    def changelocation(self):
        # I haven't programmed it to spawn outside the snake's body yet
        self.x = random.randint(0, SIZE) * SIZE - 200
        self.y = random.randint(0, SIZE) * SIZE - 200

    def drawself(self, turtle):
        # similar to the Square drawself, but blinks on and off
        if self.is_blinking:
            turtle.goto(self.x - SIZE // 2 - 1, self.y - SIZE // 2 - 1)
            turtle.begin_fill()
            for _ in range(4):
                turtle.forward(SIZE - SIZE // 10)
                turtle.left(90)
            turtle.end_fill()

    def changestate(self):
        # controls the blinking
        self.is_blinking = not self.is_blinking

class Snake:
    def __init__(self):
        self.headposition = [SIZE, 0]  # keeps track of where it needs to go next
        self.body = [Square(-SIZE, 0), Square(0, 0), Square(SIZE, 0)]  # body is a list of squares
        self.nextX = 1  # tells the snake which way it's going next
        self.nextY = 0
        self.crashed = False  # I'll use this when I get around to collision detection
        self.nextposition = [self.headposition[0] + SIZE * self.nextX, self.headposition[1] + SIZE * self.nextY]
        # prepares the next location to add to the snake

    def moveOneStep(self):
        if Square(self.nextposition[0], self.nextposition[1]) not in self.body: 
            # attempt (unsuccessful) at collision detection
            self.body.append(Square(self.nextposition[0], self.nextposition[1])) 
            # moves the snake head to the next spot, deleting the tail
            del self.body[0]
            self.headposition[0], self.headposition[1] = self.body[-1].x, self.body[-1].y 
            # resets the head and nextposition
            self.nextposition = [self.headposition[0] + SIZE * self.nextX, self.headposition[1] + SIZE * self.nextY]
        else:
            self.crashed = True  # more unsuccessful collision detection

    def moveup(self):  # pretty obvious what these do
        self.nextX, self.nextY = 0, 1

    def moveleft(self):
        self.nextX, self.nextY = -1, 0

    def moveright(self):
        self.nextX, self.nextY = 1, 0

    def movedown(self):
        self.nextX, self.nextY = 0, -1

    def eatFood(self):
        # adds the next spot without deleting the tail, extending the snake by 1
        self.body.append(Square(self.nextposition[0], self.nextposition[1]))
        self.headposition[0], self.headposition[1] = self.body[-1].x, self.body[-1].y
        self.nextposition = [self.headposition[0] + SIZE * self.nextX, self.headposition[1] + SIZE * self.nextY]

    def drawself(self, turtle):  # draws the whole snake when called
        for segment in self.body:
            segment.drawself(turtle)

class Game:
    def __init__(self):
        # game object has a screen, a turtle, a basic snake and a food
        self.screen = Screen()
        self.artist = Turtle(visible=False)
        self.artist.up()
        self.artist.speed("slowest")

        self.snake = Snake()
        self.food = Food(100, 0)
        self.counter = 0  # this will be used later
        self.commandpending = False  # as will this

        self.screen.tracer(0)  # follow it so far?

        self.screen.listen()
        self.screen.onkey(self.snakedown, "Down")
        self.screen.onkey(self.snakeup, "Up")
        self.screen.onkey(self.snakeleft, "Left")
        self.screen.onkey(self.snakeright, "Right")

    def nextFrame(self):
        self.artist.clear()

        if (self.snake.nextposition[0], self.snake.nextposition[1]) == (self.food.x, self.food.y):
            self.snake.eatFood()
            self.food.changelocation()
        else:
            self.snake.moveOneStep()

        if self.counter == 10:
            self.food.changestate()  # makes the food flash slowly
            self.counter = 0
        else:
            self.counter += 1

        self.food.drawself(self.artist)  # show the food and snake
        self.snake.drawself(self.artist)
        self.screen.update()
        self.screen.ontimer(lambda: self.nextFrame(), 100)

    def snakeup(self):
        if not self.commandpending: 
            self.commandpending = True
            self.snake.moveup()
            self.commandpending = False

    def snakedown(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.movedown()
            self.commandpending = False

    def snakeleft(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveleft()
            self.commandpending = False

    def snakeright(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveright()
            self.commandpending = False

game = Game()

screen = Screen()

screen.ontimer(lambda: game.nextFrame(), 100)

screen.mainloop()

Does this provide the kind of response for which you're looking?

2 of 3
0

It probably is a challenge to make a speedy game this way (but that's not all bad). I think that listen() should go after the onkey()s.

You should also look at getting rid of all the duplicated code. It might seem easy short term to just copy/paste then alter. But if you have to make major changes (like after asking on a forum) it will be tedious and error prone to alter.

PS (EDIT) also your Snake.moveOneStep() method makes a new instance of Square just to check for self collision, this seems extravagant for the sake of elegance. Better to just keep a list of locations that python (ho, ho) can check through. (Quite apart from this probably not working. Try print(Square(1,2) in [Square(1,2)]))

def check_self_collision(self, x, y):
  for s in self.body:
    if s.x == x and s.y == y:
      return False
  return True

def moveOneStep(self):
    if self.check_self_collision(self.nextposition[0], self.nextposition[1]): 
        # attempt (unsuccessful) at collision detection
        self.body.append(Square(self.nextposition[0], self.nextposition[1])) 
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Pygame Code: Snake Game - Python
December 6, 2022 - Code for Pygame: Snake Game. import pygame from pygame.locals import * class Snake: def ___init__(self,parent_screen): self.parent_screen = parent_screen self.block = pygame.image.load("resources/block.jpg").convert() self.x =100 self.y =100 ...
🌐
Project Gurukul
projectgurukul.org › home › python snake game – create snake game program
Python Snake Game - Create Snake Game Program - Project Gurukul
January 14, 2021 - We will use python to build the logic of the game and for the interface part, we will use tkinter because it is easy to use. The prerequisites are as follows: Basic concepts of Python, Tkinter · Please download source code of python snake game project: Snake Game Python Code
🌐
Medium
medium.com › @sjalexandre › python-tutorial-unit-30-d9f88595a64b
Python Tutorial — Building the Game Snake | Medium
August 15, 2023 - Use Print Statements: Print statements can help you understand what’s happening in your code and identify issues. Handle Errors Gracefully: Use try-except blocks to handle potential errors and provide helpful error messages. Play the Game: Play the game multiple times to identify any bugs or areas for improvement. Now it’s time to put everything together and create the Snake game.
🌐
Medium
medium.com › byte-sized-code › making-a-simple-snake-game-in-python-part-1-42eb2890f0eb
Making a simple Snake game in python (part 1) | by Arpit Omprakash | Byte-Sized-Code | Medium
June 1, 2020 - The final function uses the random package in python to return a random location for the food when we ask for it. The code is pretty self-explanatory. We make sure that the food stays inside the screen by generating a position that is inside the screen (x between 0 and screen_width and y between 0 and screen_height). As the name of the game is “snake...
🌐
DEV Community
dev.to › nevulo › making-a-simple-snake-game-in-python-3dbm
Making a simple Snake game in Python - DEV Community
February 27, 2022 - So, inside the game loop, we want to check if the length of the snake_blocks we have stored is greater than the snake_length, and remove the first block if so. This will stop our snake from infinitely growing! # Ensure the snake is only as big as the length we've set, delete the end blocks if len(snake_blocks) > snake_length: del snake_blocks[0] Replace the draw.rect call to update your snake with the code below to loop through each of the snake blocks and draw a rectangle on the screen.