Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- from enum import Enum
- from abc import ABC, abstractmethod
- class Direction(Enum):
- LEFT = "L"
- RIGHT = "R"
- UP = 'U'
- DOWN = 'D'
- class SnakeGameInterface(ABC):
- @abstractmethod
- def move(self, dir: str) -> int:
- pass
- class SnakeGame(SnakeGameInterface):
- def __init__(self, width: int, height: int, foodList: list[list[int]]):
- self.row = width
- self.col = height
- self.foodList = deque(foodList)
- self.snakePath = deque([(0,0)])
- self.score = 0
- self.direction = {
- Direction.LEFT: (-1,0),
- Direction.RIGHT: (0,1),
- Direction.UP: (0,-1),
- Direction.DOWN: (0,1)
- }
- def move(self, dir: str) -> int:
- try:
- dx, dy = self.direction[Direction(dir)]
- except:
- raise "Invalid Direction"
- head_x, head_y = self.snakePath[0]
- head = (dx + head_x, dy + head_y)
- if (self.collision(head) == True):
- return -1
- if (self.foodList) and list(head) == self.foodList[0]:
- self.score += 1
- self.foodList.popleft()
- else:
- self.snakePath.pop()
- self.snakePath.appendleft(head)
- return self.score
- def collision(self, head) -> bool:
- if (head[0] < 0 or head[0] >= self.row or head[1] < 0 or head[1] >= self.col):
- return True
- return False
- width , height = 3,3,
- foodList = [[0,1], [0,2]]
- snake = SnakeGame(3,3, foodList)
- print(snake.move("R"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement