Skip to content

Commit d07f9be

Browse files
committed
game design
1 parent 62678d2 commit d07f9be

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

353 Design Snake Game.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Design a Snake game that is played on a device with screen size = width x height.
3+
"""
4+
from collections import deque
5+
6+
__author__ = 'Daniel'
7+
8+
9+
class SnakeGame(object):
10+
def __init__(self, width, height, food):
11+
"""
12+
Initialize your data structure here.
13+
@param width - screen width
14+
@param height - screen height
15+
@param food - A list of food positions
16+
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
17+
:type width: int
18+
:type height: int
19+
:type food: List[List[int]]
20+
"""
21+
self.w = width
22+
self.h = height
23+
self.food = deque(food)
24+
self.body = deque([(0, 0)])
25+
self.dirs = {
26+
'U': (-1, 0),
27+
'L': (0, -1),
28+
'R': (0, 1),
29+
'D': (1, 0),
30+
}
31+
self.eat = 0
32+
33+
def move(self, direction):
34+
"""
35+
Moves the snake.
36+
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
37+
@return The game's score after the move. Return -1 if game over.
38+
Game over when snake crosses the screen boundary or bites its body.
39+
:type direction: str
40+
:rtype: int
41+
"""
42+
x, y = self.body[0]
43+
dx, dy = self.dirs[direction]
44+
x += dx
45+
y += dy
46+
fx, fy = self.food[0] if self.food else (-1, -1)
47+
if x == fx and y == fy:
48+
self.food.popleft()
49+
self.eat += 1
50+
else:
51+
self.body.pop()
52+
if (x, y) in self.body or not (0 <= x < self.h and 0 <= y < self.w):
53+
# possible to use set to accelerate check
54+
return -1
55+
56+
self.body.appendleft((x, y))
57+
return self.eat
58+
59+
60+
# Your SnakeGame object will be instantiated and called as such:
61+
# obj = SnakeGame(width, height, food)
62+
# param_1 = obj.move(direction)
63+
64+
if __name__ == "__main__":
65+
game = SnakeGame(3, 2, [[1, 2], [0, 1]])
66+
for char, expect in zip('RDRULU', [0, 0, 1, 1, 2, -1]):
67+
assert game.move(char) == expect

0 commit comments

Comments
 (0)