Skip to content

Instantly share code, notes, and snippets.

@Aveek-Saha
Created August 9, 2020 12:10
Show Gist options
  • Save Aveek-Saha/b7d0a3a923281b16781f537f87ef11f6 to your computer and use it in GitHub Desktop.
Save Aveek-Saha/b7d0a3a923281b16781f537f87ef11f6 to your computer and use it in GitHub Desktop.
An implementation of Snake in python I made because I was bored
import pygame
import random
# Colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
# Width and height of each segment of the snake
BLOCK_SIZE = 20
pygame.init()
win_height = 600
win_width = 600
window = pygame.display.set_mode([win_height, win_width])
pygame.display.set_caption("Snek")
x = 200
y = 200
x1 = 0
y1 = 0
snake_len = 0
block_list = []
head = [x, y, BLOCK_SIZE, BLOCK_SIZE]
block_list.append(head)
def food_pos():
food_x = round(random.randrange(0, win_width - BLOCK_SIZE) /
BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, win_height - BLOCK_SIZE) /
BLOCK_SIZE) * BLOCK_SIZE
return food_x, food_y
food_x, food_y = food_pos()
close = False
clock = pygame.time.Clock()
while not close:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1 = -BLOCK_SIZE
y1 = 0
elif event.key == pygame.K_RIGHT:
x1 = BLOCK_SIZE
y1 = 0
elif event.key == pygame.K_UP:
y1 = -BLOCK_SIZE
x1 = 0
elif event.key == pygame.K_DOWN:
y1 = BLOCK_SIZE
x1 = 0
x += x1
y += y1
if snake_len < len(block_list):
block_list.pop()
head = [x, y, BLOCK_SIZE, BLOCK_SIZE]
block_list.insert(0, head)
window.fill(BLACK)
pygame.draw.rect(window, GREEN, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
if x > win_width or y > win_height or x < 0 or y < 0:
close = True
for block in block_list:
pygame.draw.rect(window, WHITE, block)
pygame.display.update()
for block in block_list[1:]:
if block == head:
close = True
if food_x == x and food_y == y:
food_x, food_y = food_pos()
snake_len += 1
clock.tick(10)
pygame.quit()
quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment