Skip to content

Instantly share code, notes, and snippets.

@javascripto
Created January 31, 2019 09:37
Show Gist options
  • Select an option

  • Save javascripto/3a2432a64ea61cb6957897ea3ce7c8e0 to your computer and use it in GitHub Desktop.

Select an option

Save javascripto/3a2432a64ea61cb6957897ea3ce7c8e0 to your computer and use it in GitHub Desktop.
Snake básico com pygame
#!/usr/bin/python3
import pygame
from pygame.locals import *
from random import randint
def on_grid_random():
x = randint(0, 290)
y = randint(0, 290)
return (x//10 * 10, y//10 * 10)
def colision(c1, c2):
return (c1[0] == c2[0]) and (c1[1] == c2[1])
class Colors(object):
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class Snake(object):
def __init__(self):
self.body = [(200, 200), (210, 200), (220, 200)]
self.skin = pygame.Surface((10, 10))
pygame.init()
screen = pygame.display.set_mode((300, 300))
pygame.display.set_caption('Snake')
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
snake = Snake()
snake.skin.fill(Colors.WHITE)
apple_pos = on_grid_random()
apple = pygame.Surface((10, 10))
apple.fill(Colors.RED)
my_direction = LEFT
clock = pygame.time.Clock()
while True:
clock.tick(15)
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 colision(snake.body[0], apple_pos):
apple_pos = on_grid_random()
snake.body.append((0,0))
for i in range(len(snake.body) -1, 0, -1):
snake.body[i] = (snake.body[i-1][0], snake.body[i-1][1])
if my_direction == UP:
snake.body[0] = (snake.body[0][0], snake.body[0][1] - 10)
if my_direction == DOWN:
snake.body[0] = (snake.body[0][0], snake.body[0][1] + 10)
if my_direction == RIGHT:
snake.body[0] = (snake.body[0][0] + 10, snake.body[0][1])
if my_direction == LEFT:
snake.body[0] = (snake.body[0][0] - 10, snake.body[0][1])
screen.fill((0,0,0))
screen.blit(apple, apple_pos)
for pos in snake.body:
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