-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path353. Design Snake Game.py
executable file
·73 lines (63 loc) · 2.2 KB
/
353. Design Snake Game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'''
use row and column instead of x and y
'''
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
"""
self.rows = height
self.cols = width
self.food = food
self.snakeSet = set([(0, 0)])
self.snake = deque([(0, 0)])
self.nextfood = 0
self.head = (0, 0)
def move(self, direction: str) -> int:
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
"""
# move one unit
r, c= self.head
if direction == 'L':
c -= 1
elif direction == 'R':
c += 1
elif direction == 'U':
r -= 1
else: # 'D'
r += 1
# if new head is not valid
if r < 0 or r >= self.rows or c < 0 or c >= self.cols:
return -1
# if food is not avaliable
if self.nextfood == len(self.food):
tail = self.snake.popleft()
self.snakeSet.remove(tail)
else:
# if food is available
fr, fc = self.food[self.nextfood] # get position of food
# if equal, move to next food
if (r, c) == (fr, fc):
self.nextfood += 1
else:
# remove tail if not equal
tail = self.snake.popleft()
self.snakeSet.remove(tail)
if (r, c) in self.snakeSet:
return -1
# if valid, update snake
self.head = (r, c)
self.snake.append((r, c))
self.snakeSet.add((r, c))
return len(self.snake) - 1
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)