Advertisement
nirajs

snake

Feb 29th, 2024
796
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1.  
  2. from collections import deque
  3. from enum import Enum
  4. from abc import ABC, abstractmethod
  5.  
  6. class Direction(Enum):
  7.     LEFT = "L"
  8.     RIGHT = "R"
  9.     UP = 'U'
  10.     DOWN = 'D'
  11.  
  12.  
  13. class SnakeGameInterface(ABC):
  14.     @abstractmethod
  15.     def move(self, dir: str) -> int:
  16.         pass
  17.  
  18. class SnakeGame(SnakeGameInterface):
  19.  
  20.     def __init__(self, width: int, height: int, foodList: list[list[int]]):
  21.         self.row = width
  22.         self.col = height
  23.         self.foodList = deque(foodList)
  24.         self.snakePath = deque([(0,0)])
  25.         self.score = 0
  26.         self.direction = {
  27.             Direction.LEFT: (-1,0),
  28.             Direction.RIGHT: (0,1),
  29.             Direction.UP: (0,-1),
  30.             Direction.DOWN: (0,1)
  31.         }
  32.  
  33.     def move(self, dir: str) -> int:
  34.         try:
  35.             dx, dy = self.direction[Direction(dir)]
  36.         except:
  37.             raise "Invalid Direction"
  38.         head_x, head_y = self.snakePath[0]
  39.         head = (dx + head_x, dy + head_y)
  40.  
  41.         if (self.collision(head) == True):
  42.             return -1
  43.  
  44.         if (self.foodList) and list(head) == self.foodList[0]:
  45.             self.score += 1
  46.             self.foodList.popleft()
  47.         else:
  48.             self.snakePath.pop()
  49.  
  50.         self.snakePath.appendleft(head)
  51.         return self.score
  52.  
  53.     def collision(self, head) -> bool:
  54.         if (head[0] < 0 or head[0] >= self.row or head[1] < 0 or head[1] >= self.col):
  55.             return True
  56.  
  57.         return False
  58.  
  59.  
  60. width , height = 3,3,
  61. foodList = [[0,1], [0,2]]
  62. snake = SnakeGame(3,3, foodList)
  63. print(snake.move("R"))
  64.  
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement