-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.py
More file actions
61 lines (49 loc) · 2.09 KB
/
board.py
File metadata and controls
61 lines (49 loc) · 2.09 KB
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
import apple
import snake
import random
# board holds a snake and an apple and can check for collisions/grow the snake if necessary
class Board:
def __init__(self, width, height, snakeCoord, snakeLength, snakeDirection):
self.width = width
self.height = height
# set snake
self.snake = snake.Snake(snakeCoord[0], snakeCoord[1], snakeLength, snakeDirection)
# set apple at random location not on snake
self.apple = apple.Apple(random.randint(0, self.width - 1), random.randint(0, self.height - 1))
while self.apple.get_coord() in self.snake.get_body():
self.apple.set_coord(random.randint(0, self.width - 1), random.randint(0, self.height - 1))
self.score = 0
def __place_apple(self):
self.apple.set_coord(random.randint(0, self.width - 1), random.randint(0, self.height - 1))
while self.apple.get_coord() in self.snake.get_body():
self.apple.set_coord(random.randint(0, self.width - 1), random.randint(0, self.height - 1))
def __is_on_apple(self):
# check if snake is on apple
if self.snake.get_head() == self.apple.get_coord():
self.score += 1
return True
return False
def __is_past_wall(self):
# check if snake is on wall
if self.snake.get_head()[0] >= self.width or self.snake.get_head()[0] < 0 or self.snake.get_head()[1] >= self.height or self.snake.get_head()[1] < 0:
return True
return False
def change_direction(self, direction):
self.snake.change_direction(direction)
# return true if board is still in a valid state, false if game is over
def move(self):
onApple = self.__is_on_apple()
self.snake.move(onApple)
if onApple:
self.__place_apple()
# check for game over
if self.__is_past_wall() or self.snake.ate_itself():
return False
else:
return True
def get_score(self):
return self.score
def get_width(self):
return self.width
def get_height(self):
return self.height