Skip to content

Instantly share code, notes, and snippets.

@afonsoaugusto
Last active November 11, 2018 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afonsoaugusto/7c069a6ab0c74e5489600b47cf89d70d to your computer and use it in GitHub Desktop.
Save afonsoaugusto/7c069a6ab0c74e5489600b47cf89d70d to your computer and use it in GitHub Desktop.
import random
import pygame
from pygame.locals import *
SIZE_FRAME = 300
LIMIT_FRAME = SIZE_FRAME-10
def on_grid_random():
x = random.randint(0,LIMIT_FRAME)
y = random.randint(0,LIMIT_FRAME)
return (x//10 * 10, y//10 * 10)
def collision(c1,c2):
return ((c1[0] == c2 [0])and (c1[1] == c2[1]))
def collision_player(c1,player):
return ((c1[0] in [ x[0] for x in player]) and (c1[1] in [ x[1] for x in player] ))
UP = 0
DOWN = 1
RIGHT = 2
LEFT = 3
pygame.init()
screen = pygame.display.set_mode((SIZE_FRAME,SIZE_FRAME))
pygame.display.set_caption('Snake')
snake = [(200,200),(210,200),(220,200)]
snake.append((0,0))
snake_skin = pygame.Surface((10,10))
snake_head_skin = pygame.Surface((10,10))
snake_skin.fill((255,255,255))
snake_head_skin.fill((255,200,255))
apple_pos = (on_grid_random())
apple_skin = pygame.Surface((10,10))
apple_skin.fill((255,0,0))
my_direction = DOWN
clock = pygame.time.Clock()
while True:
clock.tick(25)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == KEYDOWN:
if event.key == K_UP:
my_direction = UP
if event.key == K_DOWN:
my_direction = DOWN
if event.key == K_RIGHT:
my_direction = RIGHT
if event.key == K_LEFT:
my_direction = LEFT
if collision(snake[0],apple_pos):
apple_pos = on_grid_random()
snake.append((0,0))
if (collision_player(snake[0],snake[1:])):
#pygame.quit()
pass
for i in range(len(snake)-1,0,-1):
snake[i] = (snake[i-1][0],snake[i-1][1])
if my_direction == UP:
snake[0] = (snake[0][0], snake[0][1] - 10)
if my_direction == DOWN:
snake[0] = (snake[0][0], snake[0][1] + 10)
if my_direction == RIGHT:
snake[0] = (snake[0][0] + 10, snake[0][1])
if my_direction == LEFT:
snake[0] = (snake[0][0] - 10, snake[0][1])
if snake[0][1] < 0:
snake[0] = (snake[0][0],SIZE_FRAME)
if snake[0][1] > SIZE_FRAME:
snake[0] = (snake[0][0],0)
if snake[0][0] < 0:
snake[0] = (SIZE_FRAME,snake[0][1])
if snake[0][0] > SIZE_FRAME:
snake[0] = (0,snake[0][1])
screen.fill((0,0,0))
screen.blit(apple_skin,apple_pos)
screen.blit(snake_head_skin,snake[0])
for pos in snake[1:]:
screen.blit(snake_skin,pos)
pygame.display.update()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment