@@ -33,9 +33,9 @@ class Direction:
33
33
34
34
35
35
class DrawableObject :
36
- EMPTY = 1
37
- APPLE = 2
38
- SNAKE = 3
36
+ EMPTY = ""
37
+ APPLE = "@"
38
+ SNAKE = "#"
39
39
40
40
41
41
class Snake :
@@ -103,6 +103,11 @@ def move(self, direction):
103
103
def eat (self ):
104
104
self .is_eating = True
105
105
106
+ def is_smashed (self ):
107
+ for i in range (1 , len (self .skeleton )):
108
+ if self .head .current_position == self .skeleton [i ].current_position :
109
+ return True
110
+ return False
106
111
107
112
class Apple :
108
113
def __init__ (self , height : int , width : int ):
@@ -123,15 +128,15 @@ class BaseDisplay:
123
128
def __init__ (self , width : int , height : int ):
124
129
self .width = width
125
130
self .height = height
126
- self .matrix = [[False for j in range (width )] for i in range (height )]
131
+ self .matrix = [[DrawableObject . EMPTY for j in range (width )] for i in range (height )]
127
132
128
133
def set_position (self , position : Position , obj ):
129
134
self .matrix [position .y ][position .x ] = obj
130
135
131
136
def clear (self ):
132
137
for i in range (self .height ):
133
138
for j in range (self .width ):
134
- self .matrix [i ][j ] = False
139
+ self .matrix [i ][j ] = DrawableObject . EMPTY
135
140
136
141
def draw (self ):
137
142
raise NotImplementedError ()
@@ -142,12 +147,10 @@ def draw(self):
142
147
print ("" )
143
148
for i in range (self .height ):
144
149
for j in range (self .width ):
145
- if self .matrix [i ][j ] == DrawableObject .SNAKE :
146
- print ("#" , end = "" )
147
- elif self .matrix [i ][j ] == DrawableObject .APPLE :
148
- print ("@" , end = "" )
149
- else :
150
+ if self .matrix [i ][j ] == DrawableObject .EMPTY :
150
151
print ("." , end = "" )
152
+ else :
153
+ print (self .matrix [i ][j ], end = "" )
151
154
print ("" )
152
155
print ("" )
153
156
@@ -183,10 +186,12 @@ def step(self):
183
186
self .display .clear ()
184
187
direction = self .controller .get_direction ()
185
188
self .snake .move (direction )
189
+ if self .snake .is_smashed ():
190
+ raise Exception ()
191
+ for vertebra in self .snake .skeleton :
192
+ self .display .set_position (vertebra .current_position , DrawableObject .SNAKE )
186
193
if self .snake .head .current_position == self .apple .position :
187
194
self .snake .eat ()
188
195
self .apple .respawn (self .display .matrix )
189
- for vertebra in self .snake .skeleton :
190
- self .display .set_position (vertebra .current_position , DrawableObject .SNAKE )
191
196
self .display .set_position (self .apple .position , DrawableObject .APPLE )
192
197
self .display .draw ()
0 commit comments