Created
October 21, 2016 20:26
-
-
Save jsbueno/b3db990f182c53e2ab59eeadfe2c5962 to your computer and use it in GitHub Desktop.
Simple Snake Game using Pygame - used in the workshop in Guarulhos at 2016-10-21
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import pygame | |
import random | |
# jsobueno@gmail.com | |
TAMANHO = (640, 480) | |
T = 640 / 32 | |
TX = 640 / T | |
TY = 480 / T | |
cor_comida = (0, 255, 0) | |
class GameOver(Exception): | |
pass | |
def inicio(): | |
global tela | |
tela = pygame.display.set_mode(TAMANHO) | |
def apaga(x, y): | |
pygame.draw.rect(tela, (0,0,0) , (x * T, y * T, T, T)) | |
def principal(): | |
x, y = 0, 0 | |
vx = 1; vy = 0 | |
cor = (255, 0, 0) | |
velocidade = 4 | |
contador = 0 | |
comprimento = 5 | |
corpo = [] | |
com_x = com_y = None | |
while True: | |
pygame.event.pump() | |
teclas = pygame.key.get_pressed() | |
if teclas[pygame.K_ESCAPE]: | |
raise GameOver | |
if teclas[pygame.K_RIGHT]: | |
vx = 1; vy = 0 | |
if teclas[pygame.K_LEFT]: | |
vx = -1; vy = 0 | |
if teclas[pygame.K_UP]: | |
vy = -1; vx =0 | |
if teclas[pygame.K_DOWN]: | |
vy = 1; vx = 0 | |
if contador % velocidade == 0: | |
x += vx | |
y += vy | |
if (x, y) in corpo: | |
raise GameOver | |
corpo.append((x, y)) | |
pygame.draw.rect(tela, cor, (x * T, y * T, T, T)) | |
if x == com_x and y == com_y: | |
comprimento += 5 | |
com_x = com_y = None | |
if random.random() < 0.05: | |
if com_x is not None: | |
apaga(com_x, com_y) | |
com_x = random.randrange(0, TX) | |
com_y = random.randrange(0, TY) | |
pygame.draw.rect(tela, cor_comida, (com_x * T, com_y * T, T, T)) | |
if x > TX or y > TY or x < 0 or y < 0: | |
raise GameOver | |
if len(corpo) > comprimento: | |
final = corpo.pop(0) | |
apaga(final[0], final[1]) | |
pygame.display.flip() | |
pygame.time.delay(30) | |
contador += 1 | |
inicio() | |
try: | |
principal() | |
except GameOver: | |
print("O jogador morreu ou desistiu") | |
pygame.quit() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment