Coding A Snake Game in Python - playproduction.de

Coding A Snake Game in Python

NeuralNine
Views: 34747
Like: 1033
Today we learn how to code a simple snake game in Python.

Get Tabnine for FREE here:

◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
💻 The Algorithm Bible Book:
🐍 The Python Bible Book:
👕 Programming Merch:

🌐 Social Media & Contact 🌐
📱 Website:
📷 Instagram:
🐦 Twitter:
🤵 LinkedIn:
📁 GitHub:

🎵 Outro Music From:

79 Comments

  1. jokes on you tabnine is already my favorite vscode extension

  2. Thanks!
    Can you tell what software do you use to record such video with screen and camera?

  3. Hello, thanks for the tutorial man it's really amazing. I'm facing a problem where after the game is done and it says "Game Over!", the close button doesn't work. I made sure that I used the same code as you but it still persists. Any help, please?
    ( if event.type == pygame.QUIT:

    game_over = True

    game_close = False)

  4. i have a problem… is this code right??? text = score_font.render("Score: " = str(score), True, orange) because vscode is telling me it's wrong…. please help

    EDIT: I just removed ' ' off of the code

  5. this is like the Hello World of Game Programming

  6. I have several problems in the program, but the first one says "Module 'pygame' has no 'init' member.
    I don't know how to fix it

  7. A simple snake game doesn't mean a simple code….lol. I'm a beginner in python and I thought I would try something simple. Don't get me wrong , I enjoyed this video, I just had to reclassify myself as a pre-beginner.

  8. When I run the code it wont open correctly. It just shuts down instantly…

  9. I keep getting this error, help pls:
    Traceback (most recent call last):

    File "C:UsersKhaledPycharmProjectspySnakemain.py", line 24, in <module>

    massage_font = pygame.font.SysFont('ubuntu', 25)

    File "C:UsersKhaledPycharmProjectspySnakevenvlibsite-packagespygamesysfont.py", line 415, in SysFont

    return constructor(fontname, size, set_bold, set_italic)

    File "C:UsersKhaledPycharmProjectspySnakevenvlibsite-packagespygamesysfont.py", line 333, in font_constructor

    font = Font(fontpath, size)

    pygame.error: font not initialized

    Nice vid btw

  10. I'm from Vietnam, thank you so much about the clips that you share and I study so much from them. In the present, I want to study Qt library to design Gui for python.
    Could you create a series about it?

  11. My game window is flashing for a second and then disappears … what should I do now?

  12. I need help please, whenever I import pygame, it tells me that there is an error in the line 1

  13. I don't know what's the issue with my program but my pygame window exit on it's own in just 2/3 secs as soon as I run the program can anyone help

  14. Why is my snake going only in right direction

  15. coulc you please post the code i am having trouble and need to compare to see what i did wrong

  16. Can you tell which software are you using

  17. Really appreciate your videos… yesterday i decided to try programming a sudoku solver and saw that you have posted its video a couple of days back..How do you read my mind?

    Regarding the snake game, i just have one issue with my implementation, the Score is getting overlapped over previous score, so the numbers become unreadable..Any suggestion on what could be the problem? I tried rendering the previous score in Black so as to make it vanish in the background…but that was in vain, still getting numbers overlapped

  18. Every time I try to run my code, it keeps shutting down immediately. I've tried using input("text") but it doesn't work. Can anyone help? P.S I'm using Python 3.9.6

  19. when i touched the target it didnt work, every thing else was fine though

  20. Really love ur vids … U r so descriptive

  21. so i followed the tutorial to the end, and when i tested it didnt respond. rip. ill see if it loads. fingers crossed.

  22. hey bro i am getting error saying that name game_over is not defined pls help me i dont know to solve it

  23. That was so clear. I feel like I learned a lot.

  24. It's atomatically getti closed and showing process finished with exit code 0, can any one help^^

  25. Thank you for this amazing video. Just a quick question… I wrote this in my code but idk why it is showing the following thing:
    message_font = pygame.font.SysFont('calibri', 30)

    score_font = pygame.font.SysFont('calibri', 25)

    font = int(Font(fontpath, size))

    TypeError: int() argument must be a string, a bytes-like object or a number, not 'pygame.font.Font'

    Can somebody help me regarding this

  26. It won't let me import well install the pygame or anything

  27. So i coded everything like on the tutorial but somehow it first opens a python window and then it opens my snake game and then freezes straight after. How do i fix this?
    here are the error msges:

    File "f:CodingPython Projects.pySnake_Game", line 127, in <module>

    run_game()

    File "f:CodingPython Projects.pySnake_Game", line 54, in run_game

    while not game_over:

    UnboundLocalError: local variable 'game_over' referenced before assignment

  28. amazing guy thank you so much, im from vietnam

  29. Thanks a lot mate for this tutorial. Very simple and at the same time, intuitive. Perfect for a beginner like me.
    Wow, wow.

  30. I copied exactly what was in the video and my code is literally not running at all … Everytime click run nothing happens 🙁

  31. When I run it closes suddenly. can anyone help

  32. from cgitb import text

    from email import message

    import pygame

    import time

    import random

    # Init pygame

    pygame.init()

    # Define Colors

    white = (255, 255, 255)

    black = (0, 0, 0)

    red = (255, 0, 0)

    orange = (255, 165, 0)

    width, height = 600, 400

    game_display = pygame.display.set_mode((width, height))

    pygame.display.set_caption("i love snek")

    clock = pygame.time.Clock()

    snake_size = 10

    snake_speed = 15

    message_font = pygame.font.SysFont('ubuntu', 30)

    score_font = pygame.font.SysFont('ubuntu', 25)

    def print_score(score):

    text = score_font.render("Score: " + str(score), True, orange)

    game_display.blit(text, [0,0])

    def draw_snake(snake_size, snake_pixels):

    for pixel in snake_pixels:

    pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])

    def run_game():

    game_over = False

    game_close = False

    x = width / 2

    y = height / 2

    x_speed = 0

    y_speed = 0

    snake_pixels = []

    snake_length = 1

    target_x = round(random.randrange(0, width-snake_size) / 10.0) * 10.0

    target_y = round(random.randrange(0, height-snake_size) / 10.0) * 10.0

    while not game_over:

    while game_close:

    game_display.fill(black)

    game_over_message = message_font.render("Game Over!", True, red)

    game_display.blit(game_over_message, [width / 3, height / 3])

    print_score(snake_length – 1)

    pygame.display.update()

    for event in pygame.event.get():

    if event.type == pygame.KEYDOWN:

    if event.key == pygame.K_1:

    game_over = True

    game_close = False

    if event.key == pygame.K_2:

    run_game()

    if event.type == pygame. QUIT:

    game_over = True

    game_close = False

    for event in pygame.event.get():

    if event.type == pygame.QUIT:

    game_over = True

    if event.type == pygame.KEYDOWN:

    if event.key == pygame.K_LEFT:

    x_speed = -snake_size

    y_speed = 0

    if event.key == pygame.K_RIGHT:

    x_speed = snake_size

    y_speed = 0

    if event.key == pygame.K_UP:

    x_speed = 0

    y_speed = 0

    if event.key == pygame.K_DOWN:

    x_speed = 0

    y_speed = snake_size

    if x >= width or x < 0 or y >= height or y < 0:

    game_close = True

    x += x_speed

    y += y_speed

    game_display.fill(black)

    pygame.draw.rect(game_display, orange, [target_x,target_y,snake_size, snake_size])

    snake_pixels.append([x,y])

    if len(snake_pixels) > snake_length:

    del snake_pixels[0]

    for pixel in snake_pixels[:-1]:

    if pixel == [x, y]:

    game_close = True

    draw_snake(snake_size, snake_pixels)

    print_score(snake_length – 1)

    pygame.display.update()

    if x == target_x and y == target_y:

    target_x = round(random.randrange(0, width-snake_size) / 10.0) * 10.0

    target_y = round(random.randrange(0, height-snake_size) / 10.0) * 10.0

    snake_length += 1

    clock.tick(snake_speed)

    pygame.quit()

    quit()

    run_game()

    IndentationError: expected an indented block after function definition on line 37
    game_over = False

    plz help

  33. File "c:UsersHpDesktopsnek.py", line 56, in <module>

    while not game_over:

  34. i,ve run into a problem, ive written the code and all but when i run the game the food spawns once and after i get the food it doesnt spawn again, why is that?

    code:
    import pygame

    import sys

    import random

    pygame.init()

    w, h = 600, 400

    # game variables

    screen = pygame.display.set_mode((w, h))

    pygame.display.set_caption("SnakeGame")

    clock = pygame.time.Clock()

    cell_size = 10

    snake_v = 15

    msg_font = pygame.font.SysFont('Consolas', 30)

    score_font = pygame.font.SysFont('Consolas', 25)

    def score(score):

    text = score_font.render("Score:"+str(score), True, (255, 165, 0))

    screen.blit(text, [0, 0])

    # snake_p is the snake pixels

    def draw_snake(cell_size, snake_p):

    for x in snake_p:

    pygame.draw.rect(screen, (255, 255, 255), [

    x[0], x[1], cell_size, cell_size])

    def main():

    # game variables

    game_over = False

    running = True

    x = w/2

    y = h/2

    delta_x = 0

    delta_y = 0

    snake_p = []

    snake_len = 1

    food_x = round(random.randrange(0, w-cell_size) / 10.0) * 10.0

    food_y = round(random.randrange(0, h-cell_size) / 10.0) * 10.0

    # main loop

    while not game_over:

    while not running:

    screen.fill((50, 50, 50))

    game_over_msg = msg_font.render("Game Over!", True, (255, 0, 0))

    screen.blit(game_over_msg, [w/3, h/3])

    score(snake_len – 1)

    pygame.display.update()

    for event in pygame.event.get():

    if event.type == pygame.KEYDOWN:

    if event.key == pygame.K_1:

    running = True

    game_over = True

    sys.exit()

    if event.key == pygame.K_2:

    main()

    for event in pygame.event.get():

    if event.type == pygame.QUIT:

    game_over = True

    elif event.type == pygame.KEYDOWN:

    if event.key == pygame.K_UP:

    delta_x = 0

    delta_y = -cell_size

    if event.key == pygame.K_DOWN:

    delta_x = 0

    delta_y = cell_size

    if event.key == pygame.K_LEFT:

    delta_x = -cell_size

    delta_y = 0

    if event.key == pygame.K_RIGHT:

    delta_x = cell_size

    delta_y = 0

    # game_over if the snake bumps into the walls

    if x >= w or x < 0 or y >= h or y < 0:

    running = False

    x += delta_x

    y += delta_y

    screen.fill((50, 50, 50))

    # draw food

    pygame.draw.rect(screen, (255, 165, 0), [

    food_x, food_y, cell_size, cell_size])

    # remove last block each movement

    snake_p.append([x, y])

    if len(snake_p) > snake_len:

    del snake_p[0]

    # end game if snake bumps into self

    for pixel in snake_p[:-1]:

    if pixel == [x, y]:

    running = False

    draw_snake(cell_size, snake_p)

    score(snake_len – 1)

    pygame.display.update()

    if x == food_x and y == food_y:

    food_x = round(random.randrange(0, w-cell_size / 10.0)) * 10

    food_y = round(random.randrange(0, h-cell_size / 10.0)) * 10

    snake_len += 1

    clock.tick(snake_v)

    pygame.quit()

    quit()

    main()

  35. help needed the program runs however, the snake and the food dosent appear on the screen copied code correclty and also im not getting any errors.

  36. my clock.time variable states that it's not defined by pylance, any help

  37. When I crash into myself the game just ends no game over screen. what am I doing wrong

Leave a Reply

Your email address will not be published.