Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame,random
- pygame.init()
- gameDisplay= pygame.display.set_mode((800,600))
- surface = pygame.Surface(gameDisplay.get_size())
- surface = surface.convert()
- surface.fill((255,255,255))
- gameDisplay.blit(surface,(0,0))
- pygame.display.set_caption('Snake')
- clock = pygame.time.Clock()
- RECTANGLE_SIZE = 10
- FPS = 24
- UP = [0,-1]
- DOWN = [0,1]
- LEFT = [-1,0]
- RIGHT = [1,0]
- class Snake():
- def __init__(self):
- self.positions = [[400,200]]
- self.lastMove = random.choice([UP,DOWN,LEFT,RIGHT])
- self.length = 1
- def setDirection(self,direction):
- if len(self.positions) > 1 and [direction[0] * -1, direction[1] * -1] == self.lastMove:
- return
- else:
- self.lastMove = direction
- def move(self):
- head = self.positions[0]
- newHead = [(head[0] + self.lastMove[0]*RECTANGLE_SIZE) % 800, (head[1] + self.lastMove[1]*RECTANGLE_SIZE) % 600]
- if len(self.positions) > 2 and newHead in self.positions[2:]:
- self.gameOver()
- elif newHead[0] in [0,800] or newHead[1] in [0,600]:
- self.gameOver()
- else:
- self.positions.insert(0,newHead)
- if len(self.positions) > self.length:
- self.positions.pop()
- def draw(self,surface):
- for position in self.positions:
- rectangle = pygame.Rect((position[0], position[1]), (RECTANGLE_SIZE, RECTANGLE_SIZE))
- pygame.draw.rect(surface, (0,0,0), rectangle)
- def gameOver(self):
- self.positions = [[400,200]]
- self.lastMove = random.choice([UP,DOWN,LEFT,RIGHT])
- self.length = 1
- class Food():
- def __init__(self):
- position_x = random.randint(1,(800/RECTANGLE_SIZE)-1) * RECTANGLE_SIZE
- position_y = random.randint(1,(600/RECTANGLE_SIZE)-1) * RECTANGLE_SIZE
- self.position = [position_x,position_y]
- def newPosition(self):
- position_x = random.randint(1,(800/RECTANGLE_SIZE)-1) * RECTANGLE_SIZE
- position_y = random.randint(1,(600/RECTANGLE_SIZE)-1) * RECTANGLE_SIZE
- self.position = [position_x,position_y]
- def draw(self,surface):
- rectangle = pygame.Rect((self.position[0], self.position[1]), (RECTANGLE_SIZE, RECTANGLE_SIZE))
- pygame.draw.rect(surface, (255,0,0), rectangle)
- def hasBeenEaten(self, snake):
- if self.position == snake.positions[0]:
- snake.length += 1
- self.newPosition()
- snake = Snake()
- food = Food()
- running = True
- while running:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = False
- elif event.type == pygame.KEYDOWN:
- if event.key == pygame.K_UP:
- snake.setDirection(UP)
- elif event.key == pygame.K_DOWN:
- snake.setDirection(DOWN)
- elif event.key == pygame.K_LEFT:
- snake.setDirection(LEFT)
- elif event.key == pygame.K_RIGHT:
- snake.setDirection(RIGHT)
- surface.fill((255,255,255))
- snake.move()
- food.hasBeenEaten(snake)
- snake.draw(surface)
- food.draw(surface)
- pygame.display.update()
- gameDisplay.blit(surface, (0,0))
- clock.tick(FPS)
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement