Advertisement
tutorfree

Snake_Game

Nov 14th, 2019
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. import pygame
  2. import random
  3. from pygame.locals import *
  4. from sys import exit
  5.  
  6. pygame.init()
  7.  
  8. screen = pygame.display.set_mode((640, 480), 0, 32)
  9. pygame.display.set_caption("Snake em Python com Pygame")
  10.  
  11. # Definindo a nossa cobra
  12. snake_pos = [(300, 300), (310, 300), (320, 300)]
  13. snake = pygame.Surface((10, 10))
  14. snake.fill((0, 255, 0))
  15.  
  16.  
  17. def posicao_aleatoria():
  18.     x = random.randint(0, 630)
  19.     y = random.randint(0, 470)
  20.     return (x//10 * 10, y//10 * 10)
  21.  
  22.  
  23. def colisao(objetoA, objetoB):
  24.     return (objetoA[0] == objetoB[0]) and (objetoA[1] == objetoB[1])
  25.  
  26.  
  27. # Definindo a nossa maçã
  28. apple_position = posicao_aleatoria()
  29. apple = pygame.Surface((10, 10))
  30. apple.fill((255, 0, 0))
  31.  
  32. direcao = 3 # Esquerda
  33.  
  34. running = True
  35.  
  36. clock = pygame.time.Clock()
  37.  
  38. while running:
  39.     clock.tick(10)
  40.  
  41.     for event in pygame.event.get():
  42.         if event.type == QUIT:
  43.             pygame.quit()
  44.             exit()
  45.    
  46.         if event.type == KEYDOWN:
  47.             if event.key == K_UP:
  48.                 direcao = 0
  49.             if event.key == K_DOWN:
  50.                 direcao = 1
  51.             if event.key == K_RIGHT:
  52.                 direcao = 2
  53.             if event.key == K_LEFT:
  54.                 direcao = 3
  55.  
  56.     if colisao(snake_pos[0], apple_position):
  57.         apple_position = posicao_aleatoria()
  58.         snake_pos.append((0,0))
  59.  
  60.     for i in range(len(snake_pos) - 1, 0, -1):
  61.         snake_pos[i] = (snake_pos[i-1][0], snake_pos[i-1][1])
  62.  
  63.     if direcao == 0:
  64.         snake_pos[0] = (snake_pos[0][0], snake_pos[0][1] - 10)
  65.     if direcao == 1:
  66.         snake_pos[0] = (snake_pos[0][0], snake_pos[0][1] + 10)
  67.     if direcao == 2:
  68.         snake_pos[0] = (snake_pos[0][0] + 10, snake_pos[0][1])
  69.     if direcao == 3:
  70.         snake_pos[0] = (snake_pos[0][0] - 10, snake_pos[0][1])
  71.    
  72.     screen.fill((0, 0, 0))
  73.     screen.blit(apple, apple_position)
  74.     for pos in snake_pos:
  75.         screen.blit(snake, pos)
  76.  
  77.     pygame.display.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement