Advertisement
nirajs

snake

Jan 27th, 2024
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. class SnakeGame:
  2.  
  3.     def __init__(self, width: int, height: int, foods: List[List[int]]):
  4.         self.maxRow = height
  5.         self.maxCol = width
  6.         self.foodList = []
  7.         self.currentX = 0
  8.         self.currentY = 0
  9.         self.score = 0
  10.  
  11.         for food in foods:
  12.             x, y = food
  13.             self.foodList.append((x,y))
  14.  
  15.         self.dir = {
  16.             'L': (0, -1),
  17.             'R': (0, 1),
  18.             'D': (1, 0),
  19.             'U': (-1, 0)
  20.         }
  21.        
  22.  
  23.     def move(self, direction: str) -> int:
  24.  
  25.         x = self.currentX + self.dir[direction][0]
  26.         y = self.currentY + self.dir[direction][1]
  27.         if (self.checkBoundary(self.maxRow, self.maxCol, x, y) == False):
  28.             return -1
  29.  
  30.         self.currentX = x
  31.         self.currentY = y
  32.         if self.score < len(self.foodList) and self.foodList[self.score][0] == x and self.foodList[self.score][1] == y:
  33.             self.score += 1
  34.             return self.score
  35.         else:
  36.             return self.score
  37.  
  38.  
  39.     def checkBoundary(self, r, c, posx, posy):
  40.         if ( 0 <= posx < r and 0 <= posy < c):
  41.             return True
  42.         else:
  43.             return False
  44.        
  45.  
  46.  
  47. # Your SnakeGame object will be instantiated and called as such:
  48. # obj = SnakeGame(width, height, food)
  49. # param_1 = obj.move(direction)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement