How To Make Snake In Python

Python is not just a language for scripting or automating the boring stuff. It’s also great for creating quick and dirty prototypes for small games and other fun projects. So today I’m going to show you how to make a very simple snake game in Python using pygame.

First let’s import the necessary modules. We’ll need pygame for well the game part and sys to exit the game when necessary:

import pygame sys

Next let’s initialize pygame and create a window:

pygame.init()

screen = pygame.display.set_mode((640 480))

Now we need to load our assets. In this case we just need a snake head and a snake body image. I’m using black for the head and green for the body but feel free to use whatever colors you want:

snake_head = pygame.image.load(‘snake_head.png’).convert_alpha()

snake_body = pygame.image.load(‘snake_body.png’).convert_alpha()

Before we get into the game loop we need to define some game variables. We’ll need a list to store the snake’s position a variable to store the size of the snake a variable to store the direction the snake is moving in and a variable to keep track of whether or not the game is over:

snake_pos = [(200 200) (210 200) (220 200)]

snake_size = 20

snake_dir = ‘right’

game_over = False

Now we can get into the game loop. First we fill the screen with white then we loop through the snake list and draw each segment at the correct position. After that we check for keyboard input and change the snake’s direction if necessary. Finally we check if the game is over (if the snake hits the edge of the screen or eats itself) and if so we exit the game:

See also  Are Snake Plants Safe For Cats

while not game_over:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_UP and snake_dir != ‘down’:

snake_dir = ‘up’

if event.key == pygame.K_DOWN and snake_dir != ‘up’:

snake_dir = ‘down’

if event.key == pygame.K_LEFT and snake_dir != ‘right’:

snake_dir = ‘left’

if event.key == pygame.K_RIGHT and snake_dir != ‘left’:

snake_dir = ‘right’

if snake_pos[0][0] == 640 or snake_pos[0][1] == 480 or snake_pos[0][0] < 0 or snake_pos[0][1] < 0:

game_over = True

for block in snake_pos[1:]:

if snake_pos[0][0] == block[0] and snake_pos[0][1] == block[1]:

game_over = True

if snake_dir == ‘up’:

snake_pos[0] = (snake_pos[0][0] snake_pos[0][1] – 10)

if snake_dir == ‘down’:

snake_pos[0] = (snake_pos[0][0] snake_pos[0][1] + 10)

if snake_dir == ‘left’:

snake_pos[0] = (snake_pos[0][0] – 10 snake_pos[0][1])

if snake_dir == ‘right’:

snake_pos[0] = (snake_pos[0][0] + 10 snake_pos[0][1])

screen.fill((255 255 255))

for pos in snake_pos:

screen.blit(snake_body pos)

pygame.display.update()

How do you make a snake in Python?

Answer 1:

To make a snake in Python you can use the module “Snake” which is part of the “Arcade Library”.

Leave a Comment