Advertisement
Guest User

dfsdf

a guest
Jul 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. import pygame
  2. import random
  3.  
  4. snakeColor = (255,255,255)
  5. foodColor = (255,255,0)
  6. width = 600
  7. height = 600
  8. grid = 20
  9. direction = 'up'
  10.  
  11. openWindow = True
  12.  
  13. canvas = pygame.display.set_mode((width,height))
  14. pygame.display.set_caption('Snake')
  15.  
  16. class Square():
  17.     def __init__(self, x, y, color):
  18.         self.x = x
  19.         self.y = y
  20.         self.color = color
  21.  
  22.     def show(self):
  23.         pygame.draw.rect(canvas, self.color, (self.x * grid, self.y * grid, grid, grid), 0)
  24.  
  25. class Food():
  26.     def __init__(self, color):
  27.         self.color = color
  28.  
  29.     def showFoodRandomly(self):
  30.         self.x = random.randrange(0, width, grid)
  31.         self.y = random.randrange(0, height, grid)
  32.         pygame.draw.rect(canvas, self.color, (self.x, self.y, grid, grid), 0)
  33.  
  34. class Snake():
  35.     def __init__(self):
  36.         self.x = 1
  37.         self.y = 1
  38.         self.speed = 1
  39.         self.color = snakeColor
  40.  
  41.     def updateSnake(self):
  42.         if direction == 'up':
  43.             self.y = self.y - self.speed * grid
  44.         if direction == 'down':
  45.             self.y = self.y + self.speed * grid
  46.         if direction == 'left':
  47.             self.x = self.x - self.speed * grid
  48.         if direction == 'right':
  49.             self.x = self.x + self.speed * grid
  50.  
  51.     def showSnake(self):
  52.         pygame.draw.rect(canvas, self.color, (self.x, self.y, grid, grid), 0)
  53.  
  54.  
  55. def keyPressed():
  56.     if (pygame.key.name == 'K_UP'):
  57.         direction = 'up'
  58.     elif (pygame.key.name == 'K_DOWN'):
  59.         direction = 'down'
  60.     elif (pygame.key.name == 'K_RIGHT'):
  61.         direction = 'right'
  62.     elif (pygame.key.name == 'K_LEFT'):
  63.         direction = 'left'
  64.  
  65.  
  66.  
  67. food = Food(foodColor)
  68. food.showFoodRandomly()
  69. s = Snake()
  70.    
  71.  
  72.  
  73. pygame.display.flip()
  74. while openWindow == True:
  75.     keyPressed()
  76.     for event in pygame.event.get():
  77.         if event.type == pygame.QUIT:
  78.             openWindow = False
  79.         else:
  80.             s.updateSnake()
  81.             s.showSnake()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement