Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import random
- snakeColor = (255,255,255)
- foodColor = (255,255,0)
- width = 600
- height = 600
- grid = 20
- direction = 'up'
- openWindow = True
- canvas = pygame.display.set_mode((width,height))
- pygame.display.set_caption('Snake')
- class Square():
- def __init__(self, x, y, color):
- self.x = x
- self.y = y
- self.color = color
- def show(self):
- pygame.draw.rect(canvas, self.color, (self.x * grid, self.y * grid, grid, grid), 0)
- class Food():
- def __init__(self, color):
- self.color = color
- def showFoodRandomly(self):
- self.x = random.randrange(0, width, grid)
- self.y = random.randrange(0, height, grid)
- pygame.draw.rect(canvas, self.color, (self.x, self.y, grid, grid), 0)
- class Snake():
- def __init__(self):
- self.x = 1
- self.y = 1
- self.speed = 1
- self.color = snakeColor
- def updateSnake(self):
- if direction == 'up':
- self.y = self.y - self.speed * grid
- if direction == 'down':
- self.y = self.y + self.speed * grid
- if direction == 'left':
- self.x = self.x - self.speed * grid
- if direction == 'right':
- self.x = self.x + self.speed * grid
- def showSnake(self):
- pygame.draw.rect(canvas, self.color, (self.x, self.y, grid, grid), 0)
- def keyPressed():
- if (pygame.key.name == 'K_UP'):
- direction = 'up'
- elif (pygame.key.name == 'K_DOWN'):
- direction = 'down'
- elif (pygame.key.name == 'K_RIGHT'):
- direction = 'right'
- elif (pygame.key.name == 'K_LEFT'):
- direction = 'left'
- food = Food(foodColor)
- food.showFoodRandomly()
- s = Snake()
- pygame.display.flip()
- while openWindow == True:
- keyPressed()
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- openWindow = False
- else:
- s.updateSnake()
- s.showSnake()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement