Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from enum import Enum
- import random
- class Move(Enum):
- # Direction where the player can go
- Still = 0, 0
- Up = 0, -1
- Down = 0, 1
- Right = 1, 0
- Left = -1, 0
- class Game:
- def __init__(self, width, height):
- # Definition of basic direction (right side here)
- self.heading = Move.Right
- # Definition of the width and height of game board
- self.width = width
- self.height = height
- self.size = width * height
- # We place the snake in the middle of the game board
- self.snake = [
- (int(width / 2), int(height / 2)),
- (int(width / 2) - 1, int(height / 2))
- ]
- # We place the food in the first quarter of the game board
- self.food = (int(width / 4), int(height / 4))
- # Indication that the game is launch
- self.live = True
- def chose_next_pos(self, move):
- # When the snake is going to a direction, we defined the position of snake head
- # We take the new position
- if move != Move.Still:
- self.heading = move
- # Now we have the position of snake head
- pos_x, pos_y = self.snake[0]
- # We take the position of different axis :
- head_x, head_y = self.heading.value
- # Calcul of the next position :
- pos_x = pos_x + head_x
- pos_y = pos_y + head_y
- # And return it :
- return (pos_x, pos_y)
- def run_one_frame(self, move=Move.Still):
- # This function is going to refresh the game
- # If the game is over we didn't do anything
- if self.live is False:
- print("Game is already over...")
- return
- # Here we are going to add some code for the game
- next_pos = self.chose_next_pos(move)
- # Put the new position of the snake
- # self.snake.insert(0, next_pos)
- pos_x, pos_y = next_pos
- if self.is_blocked_by_wall(pos_x, pos_y) is True:
- return
- if self.is_apple_here(pos_x, pos_y):
- print('Ate an apple!')
- self.spawn_new_food()
- if len(self.snake) is self.size:
- print('You won!')
- else:
- # Remove a block, at the tail of the snake, to make it go forward.
- self.snake.pop()
- if self.is_in_snake(pos_x, pos_y) is True:
- # Stop the game
- self.live = False
- else:
- # Add the head of the snake
- self.snake.insert(0, (pos_x, pos_y))
- def is_blocked_by_wall(self, pos_x, pos_y):
- if pos_x < 0 or pos_x >= self.width or pos_y < 0 or pos_y >= self.height:
- print('I am blocked...')
- return(True)
- return(False)
- def is_apple_here(self, pos_x, pos_y):
- food_x, food_y = self.food
- if pos_x is food_x and pos_y is food_y:
- return True
- return False
- def spawn_new_food(self):
- pos_x = random.randint(0, self.width - 1)
- pos_y = random.randint(0, self.height - 1)
- while self.is_in_snake(pos_x, pos_y) is True:
- pos_x = random.randint(0, self.width - 1)
- pos_y = random.randint(0, self.height - 1)
- self.food = (pos_x, pos_y)
- def is_in_snake(self, pos_x, pos_y):
- for node in self.snake:
- node_x, node_y = node
- if node_x is pos_x and node_y is pos_y:
- return True
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement