Skip to content
Newer
Older
100644 1331 lines (1146 sloc) 48.8 KB
b68496b @djrahl first commit
authored Jul 3, 2012
1 #!/usr/bin/env python
2 # a snakey clone using pygame
3
4 import random, pygame, sys
5 from pygame.locals import *
6
7 WINDOWWIDTH = 640
8 WINDOWHEIGHT = 480
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
9 FPS = 12
b68496b @djrahl first commit
authored Jul 3, 2012
10 CELLSIZE = 20
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
11 BUFFER = CELLSIZE * 1 # number of cells to exclude from grid height; displays in-game info
b68496b @djrahl first commit
authored Jul 3, 2012
12 assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
13 assert (WINDOWHEIGHT - BUFFER) % CELLSIZE == 0, "Window height must be a multiple of cell size."
b68496b @djrahl first commit
authored Jul 3, 2012
14 CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
15 CELLHEIGHT = int((WINDOWHEIGHT - BUFFER) / CELLSIZE)
b68496b @djrahl first commit
authored Jul 3, 2012
16
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
17 # colors
b68496b @djrahl first commit
authored Jul 3, 2012
18 WHITE = (255, 255, 255)
19 BLACK = (0, 0, 0)
20 RED = (255, 0, 0)
21 GREEN = (0, 255, 0)
22 BLUE = (0, 0, 255)
23 DARKGRAY = (40, 40, 40)
24 HONEYDEW = (240, 255, 240)
25 MINTGREEN = (189, 252, 201)
26 SEAGREEN = (84, 255, 159)
27 EMERALDGREEN = (0, 201, 87)
28 FORESTGREEN = (34, 139, 34)
29 COBALTGREEN = (61, 145, 64)
30 GREENYELLOW = (173, 255, 47)
31 OLIVEGREEN = (107, 142, 35)
32 IVORY = (205, 205, 193)
33 LIGHTYELLOW = (238, 238, 209)
34 YELLOW = (238, 238, 0)
35 KHAKI = (255, 246, 143)
36 GOLDENROD = (218, 165, 32)
37 CORAL = (255, 127, 80)
38 SIENNA = (255, 130, 71)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
39 ORANGE = (255, 127, 0)
b68496b @djrahl first commit
authored Jul 3, 2012
40 PURPLE = (142, 56, 142)
41 MAROON = (255, 52, 179)
42 BGCOLOR = BLACK
43
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
44 # for consistency in direction types
b68496b @djrahl first commit
authored Jul 3, 2012
45 UP = 'up'
46 DOWN = 'down'
47 LEFT = 'left'
48 RIGHT = 'right'
49
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
50 # for consistency in snake names
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
51 SNAKEY = 'snakey'
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
52 WIGGLES = 'wiggles'
53 GIGGLES = 'giggles'
54 LINUS = 'linus'
55
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
56 # index of snake's head
57 HEAD = 0
b68496b @djrahl first commit
authored Jul 3, 2012
58
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
59 # minimum and maximum frames fruit remains on screen
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
60 POISONTIMER = (100,200)
61 ORANGETIMER = (35,65)
62 RASPBERRYTIMER = (30,45)
63 BLUEBERRYTIMER = (20,40)
64 LEMONTIMER = (100,100)
65
66 POISONBONUS = 7
67 ORANGEBONUS = 8
68 RASPBERRYBONUS = 9
69 BLUEBERRYBONUS = 10
70 LEMONBONUS = 11
b68496b @djrahl first commit
authored Jul 3, 2012
71
72
73 class Snake:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
74 """
75 Snake class houses all information for a particular snake.
76 player - if snake is the player. Player snake is also referenced directly when player snake object is created.
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
77 name - name of snake.
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
78 alive - if snake is alive. Rather than delete, this allows snake to slowly shrink to the point of where it died.
79 coords - a list of dictionaries containing coordinates 'x' and 'y'. A special global variable HEAD (0).
80 direction - where snake moves for every game iteration ('left', 'up', etc).
81 color - body of snake's color.
82 colorBorder - outline of body.
83 growth - when a snake is to grow, this is stored in this buffer so that every game iteration can add one growth, only.
84 multiplier - all fruit eaten which cause points to be scored are multiplied by this.
85 multipliertimer - number of game iterations multiplier stays in effect.
86 score - the number of points snake has accumulated.
87 """
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
88 def __init__(self, n=SNAKEY, c=False, sc=GREEN, sb=COBALTGREEN):
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
89 self.name = n
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
90 if self.name == SNAKEY:
91 self.player = True
92 else:
93 self.player = False
b68496b @djrahl first commit
authored Jul 3, 2012
94 self.alive = True
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
95
96 if c == False:
97 self.coords = getStartPosition(1)
98 else:
99 self.coords = c
b68496b @djrahl first commit
authored Jul 3, 2012
100 # ensure snake length
101 assert len(self.coords) > 1
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
102
103 # determine direction -- currently only supports right or left
104 if self.coords[0]['x'] > self.coords[1]['x']:
105 self.direction = RIGHT
106 else:
107 self.direction = LEFT
b68496b @djrahl first commit
authored Jul 3, 2012
108 self.color = sc
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
109 self.colorCurrent = self.color
b68496b @djrahl first commit
authored Jul 3, 2012
110 self.colorBorder = sb
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
111 self.colorBorderCurrent = self.colorBorder
b68496b @djrahl first commit
authored Jul 3, 2012
112 self.growth = 0
113 self.multiplier = 1
114 self.multipliertimer = 0
115 self.score = 0
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
116 self.fruitEaten = {'apple':0, 'poison':0, 'orange':0, 'raspberry':0, 'blueberry':0, 'lemon':0}
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
117
118 def updateScore(self, points_input):
119 """
120 This updates score of snake, factoring multiplier.
121 """
122 self.score = self.score + (points_input * self.multiplier)
123
124 def updateGrowth(self, growth_input):
125 """
126 This updates growth "owed" to snake, allowing amount to stack.
127 """
128 self.growth = self.growth + growth_input
129
130 def updateMultiplier(self, multiplier_input, timer_input):
131 """
132 This updates multiplier value and time (game iterations) multiplier is active. Only time stacks.
133 """
134 # multiplier value does not stack, but time does
135 self.multiplier = multiplier_input
136 self.multipliertimer = self.multipliertimer + timer_input
137
138 def boundsCollision(self):
139 """
140 This returns True if snake (head) is ever out of grid parameters.
141 """
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
142 # check if out of bounds -- offset on on 'y' for buffer.
143 if self.coords[HEAD]['x'] == -1 or self.coords[HEAD]['x'] == CELLWIDTH or self.coords[HEAD]['y'] == -1 + (BUFFER / CELLSIZE) or self.coords[HEAD]['y'] == CELLHEIGHT + (BUFFER / CELLSIZE):
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
144 return True
145 else:
146 return False
147
148 def snakeCollision(self, snake):
149 """
150 This returns True if snake (head) collides with any part of a given snake (outside of own head if checking against self).
151 """
152 if self is snake:
153 # exclude head if checked against self
154 for snakebody in snake.coords[1:]:
155 if snakebody['x'] == self.coords[HEAD]['x'] and snakebody['y'] == self.coords[HEAD]['y']:
156 return True
157 else:
158 for snakebody in snake.coords:
159 if snakebody['x'] == self.coords[HEAD]['x'] and snakebody['y'] == self.coords[HEAD]['y']:
160 return True
161 # no collision
162 return False
163
164 def fruitCollision(self, fruit):
165 """
166 This returns True if snake (head) has collided with a given fruit.
167 """
168 if self.coords[HEAD]['x'] == fruit.coords['x'] and self.coords[HEAD]['y'] == fruit.coords['y']:
169 return True
170 else:
171 return False
172
173 def move(self):
174 """
175 This will update coords for snake, moving it one cell in given direction.
176 It also factors in and updates growth if any growth is "owed" snake (one per game iteration).
177 If snake is dead, will only remove the last segment of snake and ignore direction / not move snake.
178 """
179 if self.alive:
180 # delete last segment first.
181 if self.growth < 0:
182 self.growth = self.growth + 1
183 if len(self.coords) > 3:
184 # implement negative growth by removing last two segments
185 del self.coords[-2:]
186 else:
187 # snake is too short -- remove last segment as normal
188 del self.coords[-1]
189 elif self.growth > 0:
190 self.growth = self.growth - 1
191 # implement positive growth by not deleting last segment
192 else:
193 # no growth factor, delete last segment
194 del self.coords[-1]
195
196 # determine new head coordinates by direction
197 if self.direction == UP:
198 newhead = {'x': self.coords[HEAD]['x'], 'y': self.coords[HEAD]['y'] - 1}
199 elif self.direction == DOWN:
200 newhead = {'x': self.coords[HEAD]['x'], 'y': self.coords[HEAD]['y'] + 1}
201 elif self.direction == LEFT:
202 newhead = {'x': self.coords[HEAD]['x'] - 1, 'y': self.coords[HEAD]['y']}
203 elif self.direction == RIGHT:
204 newhead = {'x': self.coords[HEAD]['x'] + 1, 'y': self.coords[HEAD]['y']}
205
206 # insert new head segment
207 self.coords.insert(HEAD, newhead)
208
209 # dead snake -- remove last segment as long as it isn't the last
210 elif len(self.coords) > 1:
211 del self.coords[-1]
212
213 def drawSnake(self):
214 """
215 Responsible for drawing snake image to screen.
216 """
217 for coord in self.coords:
218 x = coord['x'] * CELLSIZE
219 y = coord['y'] * CELLSIZE
220 snakeSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
221 pygame.draw.rect(DISPLAYSURF, self.colorBorderCurrent, snakeSegmentRect)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
222 snakeInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
223 pygame.draw.rect(DISPLAYSURF, self.colorCurrent, snakeInnerSegmentRect)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
224
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
225 def drawScore(self, position, allsnake):
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
226 """
227 Responsible for drawing snake score to screen.
228 """
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
229 scoreSurf = BASICFONT.render('%s: %s' % (self.name, self.score), True, self.colorCurrent)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
230 scoreRect = scoreSurf.get_rect()
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
231 scoreRect.topleft = (getPosition(position, allsnake), 1)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
232 DISPLAYSURF.blit(scoreSurf, scoreRect)
233
234
235 class Opponent(Snake):
236 """
237 Derived from Snake class, this adds functionality for determining direction.
238 """
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
239 def __init__(self, n='bot', c=False, sc=COBALTGREEN, sb=GOLDENROD, r=20, p=10):
240 Snake.__init__(self, n, c, sc, sb)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
241 self.avoidBoundaries = True
c134769 @djrahl fixed key input bug
authored Jul 24, 2012
242 self.randomness = r
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
243 self.preferSameDirection = p
244
245 def updateDirection(self, grid):
246 # all directions have value adjusted
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
247 nextDirection = {LEFT:0, RIGHT:0, UP:0, DOWN:0}
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
248
249 # coords of own snake head
250 x = self.coords[HEAD]['x']
251 y = self.coords[HEAD]['y']
252
253 # opposite direction kills snake
254 if self.direction == LEFT:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
255 nextDirection[RIGHT] = nextDirection[RIGHT] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
256 elif self.direction == RIGHT:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
257 nextDirection[LEFT] = nextDirection[LEFT] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
258 elif self.direction == UP:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
259 nextDirection[DOWN] = nextDirection[DOWN] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
260 elif self.direction == DOWN:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
261 nextDirection[UP] = nextDirection[UP]- 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
262
263 # avoid boundaries
264 if self.avoidBoundaries == True:
265 if x == 0:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
266 nextDirection[LEFT] = nextDirection[LEFT] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
267 if x == CELLWIDTH - 1:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
268 nextDirection[RIGHT] = nextDirection[RIGHT] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
269 if y == (BUFFER / CELLSIZE):
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
270 nextDirection[UP] = nextDirection[UP] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
271 if y == CELLHEIGHT + (BUFFER / CELLSIZE) - 1:
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
272 nextDirection[DOWN] = nextDirection[DOWN] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
273
274 # prefer same direction
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
275 nextDirection[self.direction] = nextDirection[self.direction] + self.preferSameDirection
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
276
277 # avoid immediate snakes
278 if grid.has_key((x-1,y)) and (grid[(x-1,y)] == 'snake'):
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
279 nextDirection[LEFT] = nextDirection[LEFT] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
280 if grid.has_key((x+1,y)) and (grid[(x+1,y)] == 'snake'):
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
281 nextDirection[RIGHT] = nextDirection[RIGHT] - 100
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
282 if grid.has_key((x,y-1)) and (grid[(x,y-1)] == 'snake'):
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
283 nextDirection[UP] = nextDirection[UP] - 100
284 if grid.has_key((x,y+1)) and (grid[(x,y+1)] == 'snake'):
285 nextDirection[DOWN] = nextDirection[DOWN] - 100
286
287 # favor direction of apple -- this approach will need to be replaced eventually
288 for cell in grid:
289 if grid[cell] == 'apple':
290 # get x and y differences and favor direction of apple inversely proportionate to distance
291 x_difference = cell[0] - x
292 y_difference = cell[1] - y
293 if x_difference > 0:
294 nextDirection[RIGHT] = nextDirection[RIGHT] + (CELLWIDTH - x_difference)
295 else:
296 nextDirection[LEFT] = nextDirection[LEFT] + (CELLWIDTH - x_difference)
297 if y_difference < 0:
298 nextDirection[UP] = nextDirection[UP] + (CELLHEIGHT - y_difference)
299 else:
300 nextDirection[DOWN] = nextDirection[DOWN] + (CELLHEIGHT - y_difference)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
301
302 # factor in randomness
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
303 for d in nextDirection:
304 nextDirection[d] = nextDirection[d] + random.randint(0,self.randomness)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
305
306 # report if debugging
307 if DEBUG == True:
308 print self.name
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
309 print nextDirection
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
310
311 # update snake direction to direction with highest score
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
312 self.direction = max(nextDirection, key=nextDirection.get)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
313
314 def updateScore(self, points_input):
315 Snake.updateScore(self, points_input)
316
317 def updateGrowth(self, growth_input):
318 Snake.updateGrowth(self, growth_input)
319
320 def updateMultiplier(self, multiplier_input, timer_input):
321 Snake.updateMultiplier(self, multiplier_input, timer_input)
322
323 def boundsCollision(self):
324 return Snake.boundsCollision(self)
325
326 def snakeCollision(self, snake):
327 return Snake.snakeCollision(self, snake)
328
329 def fruitCollision(self, fruit):
330 return Snake.fruitCollision(self, fruit)
331
332 def move(self):
333 Snake.move(self)
334
335 def drawSnake(self):
336 Snake.drawSnake(self)
337
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
338 def drawScore(self, position, allsnake):
339 Snake.drawScore(self, position, allsnake)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
340
b68496b @djrahl first commit
authored Jul 3, 2012
341
342 class Fruit:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
343 """
344 Fruit class houses all information for fruit objects. Base class is not meant to be instantiated, but rather provide base methods shared by all fruit.
345 """
346 def __init__(self):
347 self.timer = 0
348
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
349 def getRandomLocation(self, allfruit, allsnake, game):
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
350 """
351 Returns random coordinates (for fruit to be placed). Ensures that coordinates are not occupied by fruit or snake head.
352 Will keep fruit away from edges (outside 20%) if in an "easy mode" determined in Tally object.
353 """
b68496b @djrahl first commit
authored Jul 3, 2012
354 while True:
355 conflict = False
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
356 if game.checkEasyTrigger():
b68496b @djrahl first commit
authored Jul 3, 2012
357 x = random.randint(int(CELLWIDTH/5), CELLWIDTH - int(CELLWIDTH/5) - 1)
358 y = random.randint(int(CELLHEIGHT/5), CELLHEIGHT - int(CELLHEIGHT/5) - 1)
359 else:
360 x = random.randint(0, CELLWIDTH - 1)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
361 y = random.randint((BUFFER / CELLSIZE), CELLHEIGHT - 1)
b68496b @djrahl first commit
authored Jul 3, 2012
362 # ensure coordinates are not already occupied by fruit
363 for fruit in allfruit:
364 if fruit.coords['x'] == x and fruit.coords['y'] == y:
365 conflict = True
366 # ensure coordinates are not already occupied by snake head
367 for snake in allsnake:
368 if snake.coords[HEAD]['x'] == x and snake.coords[HEAD]['y'] == y:
369 conflict = True
370 if conflict == False:
371 return {'x':x, 'y':y}
372
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
373 def updateTimer(self):
374 """
375 Returns true and decrements if there is still time left for fruit to be on screen.
376 """
b68496b @djrahl first commit
authored Jul 3, 2012
377 if self.timer > 0:
378 self.timer = self.timer - 1
379 return True
380 else:
381 return False
382
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
383 def drawFruit(self):
384 """
385 Responsible for drawing fruit image to screen.
386 """
387 x = self.coords['x'] * CELLSIZE
388 y = self.coords['y'] * CELLSIZE
389 fruitRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
390 pygame.draw.rect(DISPLAYSURF, self.color, fruitRect)
391
392
393 class Apple(Fruit):
394 """
395 Apples are a unique fruit in that they never leave the screen and once one is eaten, it is always replaced with another.
396 They also add points and one growth
397 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
398 def __init__(self, allfruit, allsnake, game):
399 self.coords = Fruit.getRandomLocation(self, allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
400 self.color = RED
401 self.points = 10
402 self.growth = 1
403
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
404 def isEaten(self, snake, game):
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
405 snake.fruitEaten['apple'] = snake.fruitEaten['apple'] + 1
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
406 game.fruitEaten['apple'] = game.fruitEaten['apple'] + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
407 snake.updateScore(self.points)
408 snake.updateGrowth(self.growth)
409
410 def drawFruit(self):
411 Fruit.drawFruit(self)
412
413
414 class Poison(Fruit):
415 """
416 Poison will shorten a snake (by adding a negative growth value) and reduce points.
417 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
418 def __init__(self, allfruit, allsnake, game):
419 self.coords = Fruit.getRandomLocation(self, allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
420 self.timer = random.randint(POISONTIMER[0], POISONTIMER[1])
421 self.color = GREEN
422 self.points = -25
423 self.growth = -3
424
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
425 def isEaten(self, snake, game):
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
426 snake.fruitEaten['poison'] = snake.fruitEaten['poison'] + 1
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
427 game.fruitEaten['poison'] = game.fruitEaten['poison'] + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
428 snake.updateScore(self.points)
429 snake.updateGrowth(self.growth)
430
431 def updateTimer(self):
432 return Fruit.updateTimer(self)
433
434 def drawFruit(self):
435 Fruit.drawFruit(self)
436
437
438 class Orange(Fruit):
439 """
440 Orange will grow snake substantially and are worth points.
441 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
442 def __init__(self, allfruit, allsnake, game):
443 self.coords = Fruit.getRandomLocation(self, allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
444 self.timer = random.randint(ORANGETIMER[0], ORANGETIMER[1])
445 self.color = ORANGE
446 self.points = 50
447 self.growth = 3
448
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
449 def isEaten(self, snake, game):
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
450 snake.fruitEaten['orange'] = snake.fruitEaten['orange'] + 1
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
451 game.fruitEaten['orange'] = game.fruitEaten['orange'] + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
452 snake.updateScore(self.points)
453 snake.updateGrowth(self.growth)
454
455 def updateTimer(self):
456 return Fruit.updateTimer(self)
457
458 def drawFruit(self):
459 Fruit.drawFruit(self)
460
461
462 class Raspberry(Fruit):
463 """
464 Raspberry will set snake's multiplier to two for a period of time.
465 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
466 def __init__(self, allfruit, allsnake, game):
467 self.coords = Fruit.getRandomLocation(self, allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
468 self.timer = random.randint(RASPBERRYTIMER[0], RASPBERRYTIMER[1])
469 self.color = PURPLE
470 self.multiplier = 2
471 self.multipliertimer = 100
472
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
473 def isEaten(self, snake, game):
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
474 snake.fruitEaten['raspberry'] = snake.fruitEaten['raspberry'] + 1
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
475 game.fruitEaten['raspberry'] = game.fruitEaten['raspberry'] + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
476 snake.updateMultiplier(self.multiplier, self.multipliertimer)
477
478 def updateTimer(self):
479 return Fruit.updateTimer(self)
480
481 def drawFruit(self):
482 Fruit.drawFruit(self)
483
484
485 class Blueberry(Fruit):
486 """
487 Blueberry will reduce the frame rate (slowing down game iterations) for a period of time.
488 It is also worth a lot of points.
489 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
490 def __init__(self, allfruit, allsnake, game):
491 self.coords = Fruit.getRandomLocation(self, allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
492 self.timer = random.randint(BLUEBERRYTIMER[0], BLUEBERRYTIMER[1])
493 self.color = BLUE
494 self.score = 100
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
495 self.slowtimer = 80
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
496
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
497 def isEaten(self, snake, game):
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
498 snake.fruitEaten['blueberry'] = snake.fruitEaten['blueberry'] + 1
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
499 game.fruitEaten['blueberry'] = game.fruitEaten['blueberry'] + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
500 snake.updateScore(self.score)
501
502 def updateTimer(self):
503 return Fruit.updateTimer(self)
504
505 def drawFruit(self):
506 Fruit.drawFruit(self)
507
508
509 class Lemon(Fruit):
ff23b3c @djrahl Worked on AI.
authored Jul 25, 2012
510 """
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
511 TBD... currently worth 1000 points.
512 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
513 def __init__(self, allfruit, allsnake, game):
514 self.coords = Fruit.getRandomLocation(self, allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
515 self.timer = random.randint(LEMONTIMER[0], LEMONTIMER[1])
516 self.color = YELLOW
517 self.score = 1000
518
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
519 def isEaten(self, snake, game):
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
520 snake.fruitEaten['lemon'] = snake.fruitEaten['lemon'] + 1
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
521 game.fruitEaten['lemon'] = game.fruitEaten['lemon'] + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
522 snake.updateScore(self.score)
523
524 def updateTimer(self):
525 return Fruit.updateTimer(self)
526
527 def drawFruit(self):
528 Fruit.drawFruit(self)
529
530
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
531 class GameData:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
532 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
533 Responsible for dynamics for a particular game instance.
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
534 fruitEaten - a dictionary containing a numeric tally of each fruit eaten.
535 speedTrigger - the frequency (based on apples consumed) in which gamespeed is increased by one.
536 bonusTrigger - the frequency (based on apples consumed) in which a bonus game - runBonus() - is launched.
537 easyTrigger - a threshold (apples consumed); once reached fruit can be placed anywhere on screen (as opposed to away from edges).
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
538 apples - number of apples on screen.
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
539 typeMin - the minimum value in determining bonus game type.
540 typeMax - the maximum value in determining bonus game type.
541 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
542 def __init__(self, st=20, bt=10, et=20, a=1, tmin=1, tmax=10):
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
543 self.fruitEaten = {'apple':0, 'poison':0, 'orange':0, 'raspberry':0, 'blueberry':0, 'lemon':0}
544 self.speedTrigger = st
545 self.bonusTrigger = bt
546 self.easyTrigger = et
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
547 self.apples = a
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
548 self.typeMin = tmin
549 self.typeMax = tmax
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
550 self.basespeed = FPS
551 self.currentspeed = self.basespeed
552 self.slowtimer = 0
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
553
554 def checkSpeedTrigger(self):
555 """
556 Returns true if number of apples consumed modulo speedTrigger equals zero.
557 """
558 if self.fruitEaten['apple'] % self.speedTrigger == 0:
559 return True
560 else:
561 return False
562
563 def checkBonusTrigger(self):
564 """
565 Returns true if number of apples consumed modulo bonusTrigger equals zero.
566 """
567 if self.fruitEaten['apple'] % self.bonusTrigger == 0:
568 return True
569 else:
570 return False
571
572 def checkEasyTrigger(self):
573 """
574 Returns true if number of apples consumed is less than or equal to easyTrigger.
575 """
576 if self.fruitEaten['apple'] <= self.easyTrigger:
577 return True
578 else:
579 return False
580
581 def runBonus(self):
582 """
583 Returns a list containing fruit (as strings) to be added to game from bonus game.
584 An integer (determined randomly between typeMin and typeMax) corresponds to bonus game run.
585 A basic set-up would randomly choose between 1 and 10; 6 through 10 initiating a fruit specific bonus.
586 Default will contain an assortment of fruit.
587 """
588 bonus = []
589 type = random.randint(self.typeMin, self.typeMax)
590 if type == LEMONBONUS:
591 bonus.append('lemon')
592 elif type == POISONBONUS:
593 counter = random.randint(20,35)
594 while counter > 0:
595 bonus.append('poison')
596 counter = counter - 1
597 elif type == ORANGEBONUS:
598 counter = random.randint(20,35)
599 while counter > 0:
600 bonus.append('orange')
601 counter = counter - 1
602 elif type == RASPBERRYBONUS:
603 counter = random.randint(20,35)
604 while counter > 0:
605 bonus.append('raspberry')
606 counter = counter - 1
607 elif type == BLUEBERRYBONUS:
608 counter = random.randint(20,30)
609 while counter > 0:
610 bonus.append('blueberry')
611 counter = counter - 1
612 else: # default bonus
613 counter = random.randint(0,3)
614 while counter > 0:
615 bonus.append('poison')
616 counter = counter - 1
617 counter = random.randint(5,20)
618 while counter > 0:
619 bonus.append('orange')
620 counter = counter - 1
621 counter = random.randint(1,4)
622 while counter > 0:
623 bonus.append('raspberry')
624 counter = counter - 1
625 counter = random.randint(0,2)
626 while counter > 0:
627 bonus.append('blueberry')
628 counter = counter - 1
629 return bonus
630
b68496b @djrahl first commit
authored Jul 3, 2012
631
632 class Button():
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
633 """
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
634 A clickable button that is rendered on screen.
635 """
b68496b @djrahl first commit
authored Jul 3, 2012
636 def __init__(self, text, x, y):
637 self.text = text
638 startSurf = BUTTONFONT.render(self.text, True, GREEN, DARKGRAY)
639 self.rect = startSurf.get_rect()
640 self.rect.center = x,y
641
642 def display(self):
643 startSurf = BUTTONFONT.render(self.text, True, GREEN, DARKGRAY)
644 DISPLAYSURF.blit(startSurf, self.rect)
645
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
646 def pressed(self, mouse):
b68496b @djrahl first commit
authored Jul 3, 2012
647 if mouse[0] > self.rect.topleft[0]:
648 if mouse[1] > self.rect.topleft[1]:
649 if mouse[0] < self.rect.bottomright[0]:
650 if mouse[1] < self.rect.bottomright[1]:
651 return True
652 else: return False
653 else: return False
654 else: return False
655 else: return False
656
657
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
658 class SelectButton(Button):
659 """
660 Selected by color. Clicking will turn active state to True.
661 """
662 def __init__(self, text, x, y, a=False):
663 Button.__init__(self, text, x, y)
664 self.active = a
665
666 def display(self):
667 if self.active == True:
668 startSurf = BUTTONFONT.render(self.text, True, COBALTGREEN, GOLDENROD)
669 else:
670 startSurf = BUTTONFONT.render(self.text, True, GREEN, DARKGRAY)
671
672 DISPLAYSURF.blit(startSurf, self.rect)
673
674 def pressed(self, mouse):
675 return Button.pressed(self, mouse)
676
677 def setActive(self, buttonlist):
678 for button in buttonlist:
679 if button == self:
680 self.active = True
681 else:
682 button.active = False
683
684
b68496b @djrahl first commit
authored Jul 3, 2012
685 def main():
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
686 global FPSCLOCK, DISPLAYSURF, BASICFONT, BUTTONFONT, DEBUG
687
688 # for debugging
689 if len(sys.argv) < 2:
690 DEBUG = False
691 else:
692 DEBUG = True
b68496b @djrahl first commit
authored Jul 3, 2012
693
694 pygame.init()
695 FPSCLOCK = pygame.time.Clock()
696 DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
697 BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
9504e62 @djrahl added party mode.
authored Jul 25, 2012
698 BUTTONFONT = pygame.font.Font('freesansbold.ttf', 30)
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
699 pygame.display.set_caption('Snakey Party')
b68496b @djrahl first commit
authored Jul 3, 2012
700
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
701 titleFont = pygame.font.Font('freesansbold.ttf', 64)
702 titleSurf = titleFont.render('Snakey Party', True, WHITE, FORESTGREEN)
703 titleRect = titleSurf.get_rect()
9504e62 @djrahl added party mode.
authored Jul 25, 2012
704 titleRect.center = (WINDOWWIDTH / 2, WINDOWHEIGHT * 2/8)
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
705
9504e62 @djrahl added party mode.
authored Jul 25, 2012
706 arcadebutton = Button('(a)rcade mode', WINDOWWIDTH / 2, WINDOWHEIGHT * 3/8)
707 duelbutton = Button('(d)uel mode', WINDOWWIDTH / 2, WINDOWHEIGHT * 4/8)
708 partybutton = Button('(p)arty mode', WINDOWWIDTH / 2, WINDOWHEIGHT * 5/8)
709 instructbutton = Button('(i)nstructions', WINDOWWIDTH / 2, WINDOWHEIGHT * 6/8)
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
710
711 while True: ### need to update this
712
713 DISPLAYSURF.fill(BGCOLOR)
714 DISPLAYSURF.blit(titleSurf, titleRect)
715 arcadebutton.display()
716 duelbutton.display()
9504e62 @djrahl added party mode.
authored Jul 25, 2012
717 partybutton.display()
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
718 instructbutton.display()
719
720 for event in pygame.event.get():
721 if event.type == QUIT:
722 terminate()
723 elif event.type == MOUSEBUTTONDOWN:
724 mouse = pygame.mouse.get_pos()
725 if arcadebutton.pressed(mouse):
726 pygame.event.get()
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
727 game = GameData()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
728 runGame(game, [SNAKEY])
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
729 showGameOverScreen()
730 elif duelbutton.pressed(mouse):
731 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
732 players = False
733 players = showSelectPlayersScreen()
734 if players != False:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
735 game = GameData(10, 10, 9, 2)
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
736 runGame(game, players)
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
737 showGameOverScreen()
9504e62 @djrahl added party mode.
authored Jul 25, 2012
738 elif partybutton.pressed(mouse):
739 pygame.event.get()
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
740 game = GameData(25, 12, 0, 4)
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
741 runGame(game, [SNAKEY, LINUS, WIGGLES, GIGGLES])
9504e62 @djrahl added party mode.
authored Jul 25, 2012
742 showGameOverScreen()
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
743 elif instructbutton.pressed(mouse):
744 showInstructScreen()
745 elif event.type == KEYDOWN:
746 if event.key == K_a:
747 pygame.event.get()
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
748 game = GameData()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
749 runGame(game, [SNAKEY])
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
750 showGameOverScreen()
751 elif event.key == K_d:
752 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
753 players = False
754 players = showSelectPlayersScreen()
755 if players != False:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
756 game = GameData(10, 10, 9, 2)
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
757 runGame(game, players)
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
758 showGameOverScreen()
9504e62 @djrahl added party mode.
authored Jul 25, 2012
759 elif event.key == K_p:
760 pygame.event.get()
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
761 game = GameData(25, 12, 0, 4)
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
762 runGame(game, [SNAKEY, LINUS, WIGGLES, GIGGLES])
9504e62 @djrahl added party mode.
authored Jul 25, 2012
763 showGameOverScreen()
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
764 elif event.key == K_i:
765 showInstructScreen()
766 elif event.key == K_ESCAPE or event.key == K_q:
767 terminate()
768
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
769 game = False
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
770 pygame.display.update()
771 FPSCLOCK.tick(FPS)
9504e62 @djrahl added party mode.
authored Jul 25, 2012
772
b68496b @djrahl first commit
authored Jul 3, 2012
773
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
774 def runGame(game, players=[]):
b68496b @djrahl first commit
authored Jul 3, 2012
775
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
776 # in game variables
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
777 allsnake = []
778 allfruit = []
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
779 nextEvent = 0
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
780
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
781 # create snakes based on name. 'player' is set to false initially to handle input
782 player = False
783 cur_position = 1
784 for snake in players:
785 if snake == SNAKEY:
786 player = Snake(SNAKEY, getStartPosition(cur_position))
787 allsnake.append(player)
788 cur_position = cur_position + 1
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
789 elif snake == LINUS:
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
790 linus = Opponent(LINUS, getStartPosition(cur_position), IVORY, COBALTGREEN, 5, 20)
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
791 allsnake.append(linus)
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
792 cur_position = cur_position + 1
793 elif snake == WIGGLES:
794 wiggles = Opponent(WIGGLES, getStartPosition(cur_position), OLIVEGREEN, PURPLE, 20, 5)
795 allsnake.append(wiggles)
796 cur_position = cur_position + 1
797 elif snake == GIGGLES:
798 giggles = Opponent(GIGGLES, getStartPosition(cur_position), PURPLE, EMERALDGREEN, 10, 10)
799 allsnake.append(giggles)
800 cur_position = cur_position + 1
b68496b @djrahl first commit
authored Jul 3, 2012
801
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
802 # create initial apple(s)
803 appleCounter = game.apples
804 while appleCounter > 0:
805 a = Apple(allfruit, allsnake, game)
806 allfruit.append(a)
807 appleCounter = appleCounter - 1
2199376 @djrahl changed intro menu; added arcade mode & duel mode.
authored Jul 24, 2012
808
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
809 # main game loop
810 while True:
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
811
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
812 # get grid representation for AIs
813 grid = getGrid(allsnake, allfruit)
814
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
815 # event handling loop -- get player's direction choice
816 stop = False
817
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
818 # get events in queue. This updates players direction and other key instructions (quit, debug...)
819 # if the next event after direction update suggests sharp direction change, following direction is stored.
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
820 for event in pygame.event.get():
b68496b @djrahl first commit
authored Jul 3, 2012
821 if event.type == QUIT:
822 terminate()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
823 elif nextEvent != 0 and player != False:
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
824 player.direction = nextEvent
825 nextEvent = 0
826 stop = True
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
827 # check for exit/quit/debug keys
828 if event.type == KEYDOWN and (event.key == K_ESCAPE or event.key == K_q):
829 terminate()
830 elif event.type == KEYDOWN and event.key == K_e:
831 return 1
832 elif event.type == KEYDOWN and event.key == K_g and DEBUG == True:
833 stop = True
834 debugPrintGrid(grid)
835
836 # if player exists - check for direction input
837 if event.type == KEYDOWN and player != False and stop == False:
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
838 if event.key == K_LEFT and player.direction != RIGHT:
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
839 player.direction = LEFT
b68496b @djrahl first commit
authored Jul 3, 2012
840 stop = True
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
841 elif event.key == K_RIGHT and player.direction != LEFT:
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
842 player.direction = RIGHT
b68496b @djrahl first commit
authored Jul 3, 2012
843 stop = True
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
844 elif event.key == K_UP and player.direction != DOWN:
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
845 player.direction = UP
b68496b @djrahl first commit
authored Jul 3, 2012
846 stop = True
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
847 elif event.key == K_DOWN and player.direction != UP:
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
848 player.direction = DOWN
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
849
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
850 # peak into very next event. If key suggests sharp direction change, store in nextEvent
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
851 elif event.type == KEYDOWN and player != False and nextEvent == 0:
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
852 if event.key == K_LEFT and player.direction != RIGHT:
853 nextEvent = LEFT
854 elif event.key == K_RIGHT and player.direction != LEFT:
855 nextEvent = RIGHT
856 elif event.key == K_UP and player.direction != DOWN:
857 nextEvent = UP
858 elif event.key == K_DOWN and player.direction != UP:
859 nextEvent = DOWN
860 elif event.key == K_ESCAPE or event.key == K_q:
861 terminate()
862 elif event.key == K_g and DEBUG == True:
863 debugPrintGrid(grid)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
864
865 if DEBUG == True:
866 debugPause()
867
868 # update all other snake's direction choice
869 for snake in allsnake:
870 if snake.alive and snake.player == False:
871 snake.updateDirection(grid)
b68496b @djrahl first commit
authored Jul 3, 2012
872
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
873 # collision detection
b68496b @djrahl first commit
authored Jul 3, 2012
874 for snake in allsnake:
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
875 # check if the snake has hit boundary
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
876 if snake.alive and snake.boundsCollision():
b68496b @djrahl first commit
authored Jul 3, 2012
877 snake.alive = False
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
878 # check if snake has hit another snake
879 for othersnake in allsnake:
880 if snake.alive and snake.snakeCollision(othersnake):
b68496b @djrahl first commit
authored Jul 3, 2012
881 snake.alive = False
882
883 # check score - change color accordingly
884 # only looks at player snake
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
885 if player != False:
886 if player.score > 2000:
887 player.color = SIENNA
888 player.colorBorder = CORAL
889 elif player.score > 1500:
890 player.color = CORAL
891 player.colorBorder = GOLDENROD
892 elif player.score > 1250:
893 player.color = GOLDENROD
894 player.colorBorder = EMERALDGREEN
895 elif player.score > 1000:
896 player.color = KHAKI
897 player.colorBorder = LIGHTYELLOW
898 elif player.score > 750:
899 player.color = YELLOW
900 player.colorBorder = GREEN
901 elif player.score > 500:
902 player.color = LIGHTYELLOW
903 player.colorBorder = FORESTGREEN
904 elif player.score > 400:
905 player.color = IVORY #change this
906 player.colorBorder = FORESTGREEN
907 elif player.score > 300:
908 player.color = GREENYELLOW
909 player.colorBorder = OLIVEGREEN
910 elif player.score > 200:
911 player.color = HONEYDEW
912 player.colorBorder = SEAGREEN
913 elif player.score > 100:
914 player.color = SEAGREEN
915 player.colorBorder = EMERALDGREEN
916 else:
917 player.color = GREEN
918 player.colorBorder = COBALTGREEN
b68496b @djrahl first commit
authored Jul 3, 2012
919
920 # check if fruit has been eaten by a snake
921 for snake in allsnake:
922 for fruit in allfruit:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
923 if snake.alive and snake.fruitCollision(fruit):
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
924 fruit.isEaten(snake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
925 # apples have special adding properties
926 if fruit.__class__ == Apple:
b68496b @djrahl first commit
authored Jul 3, 2012
927 # check for speed increase
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
928 if game.checkSpeedTrigger():
929 game.basespeed = game.basespeed + 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
930 # check for bonus drop
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
931 if game.checkBonusTrigger():
932 bonus = game.runBonus()
933 for bonusfruit in bonus:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
934 if bonusfruit == 'poison':
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
935 f = Poison(allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
936 elif bonusfruit == 'orange':
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
937 f = Orange(allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
938 elif bonusfruit == 'raspberry':
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
939 f = Raspberry(allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
940 elif bonusfruit == 'blueberry':
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
941 f = Blueberry(allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
942 else:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
943 f = Lemon(allfruit, allsnake, game)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
944 allfruit.append(f)
945 # chance of poison drop
b68496b @djrahl first commit
authored Jul 3, 2012
946 if random.randint(1,4) == 1:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
947 p = Poison(allfruit, allsnake, game)
b68496b @djrahl first commit
authored Jul 3, 2012
948 allfruit.append(p)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
949 # chance of orange drop
b68496b @djrahl first commit
authored Jul 3, 2012
950 if random.randint(1,5) == 1:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
951 o = Orange(allfruit, allsnake, game)
b68496b @djrahl first commit
authored Jul 3, 2012
952 allfruit.append(o)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
953 # chance of raspberry drop
b68496b @djrahl first commit
authored Jul 3, 2012
954 if random.randint(1,6) == 1:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
955 r = Raspberry(allfruit, allsnake, game)
b68496b @djrahl first commit
authored Jul 3, 2012
956 allfruit.append(r)
957 # create new apple
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
958 a = Apple(allfruit, allsnake, game)
b68496b @djrahl first commit
authored Jul 3, 2012
959 allfruit.append(a)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
960 elif fruit.__class__ == Blueberry:
961 # update speed
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
962 game.slowtimer = game.slowtimer + game.currentspeed * 9 # add 9 seconds
b68496b @djrahl first commit
authored Jul 3, 2012
963 # remove fruit
964 allfruit.remove(fruit)
965
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
966 # check for snake death and end game
967 gameover = True
b68496b @djrahl first commit
authored Jul 3, 2012
968 for snake in allsnake:
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
969 if snake.alive == True:
970 gameover = False
971 if gameover:
972 showGameStats(allsnake)
973 return 1
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
974
975 # check for size changes / move snake
976 for snake in allsnake:
977 snake.move()
b68496b @djrahl first commit
authored Jul 3, 2012
978
979 # check multiplier and adjust color and multiplier as needed
980 for snake in allsnake:
981 if snake.multipliertimer > 0:
982 snake.multipliertimer = snake.multipliertimer - 1
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
983 snake.colorBorderCurrent = PURPLE
b68496b @djrahl first commit
authored Jul 3, 2012
984 else:
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
985 # make sure multiplier is 1, color is normal
b68496b @djrahl first commit
authored Jul 3, 2012
986 snake.multiplier = 1
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
987 snake.colorBorderCurrent = snake.colorBorder
b68496b @djrahl first commit
authored Jul 3, 2012
988
989 # check slow and adjust color and fps as needed
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
990 if game.slowtimer > 0:
991 game.slowtimer = game.slowtimer - 1
b68496b @djrahl first commit
authored Jul 3, 2012
992 for snake in allsnake:
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
993 snake.colorCurrent = BLUE
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
994 if game.currentspeed > 8:
995 game.currentspeed = game.currentspeed - 1
b68496b @djrahl first commit
authored Jul 3, 2012
996 else:
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
997 if game.currentspeed < game.basespeed:
998 game.currentspeed = game.currentspeed + 1
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
999 # make sure color is normal
1000 for snake in allsnake:
1001 snake.colorCurrent = snake.color
b68496b @djrahl first commit
authored Jul 3, 2012
1002
1003 # update timers on fruits, remove if necessary
1004 for fruit in allfruit:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
1005 if fruit.__class__ != Apple:
1006 if fruit.updateTimer() == False:
b68496b @djrahl first commit
authored Jul 3, 2012
1007 allfruit.remove(fruit)
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
1008
b68496b @djrahl first commit
authored Jul 3, 2012
1009 DISPLAYSURF.fill(BGCOLOR)
1010 drawGrid()
1011 for fruit in allfruit:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
1012 fruit.drawFruit()
b68496b @djrahl first commit
authored Jul 3, 2012
1013 for snake in allsnake:
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
1014 snake.drawSnake()
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1015
1016 # print scores
1017 position = 1
1018 for snake in allsnake:
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1019 snake.drawScore(position, allsnake)
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1020 position = position + 1
b68496b @djrahl first commit
authored Jul 3, 2012
1021 pygame.display.update()
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1022 FPSCLOCK.tick(game.currentspeed)
b68496b @djrahl first commit
authored Jul 3, 2012
1023
1024
1025 def drawPressKeyMsg():
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1026 pressKeySurf = BASICFONT.render('Press any key to continue.', True, DARKGRAY)
b68496b @djrahl first commit
authored Jul 3, 2012
1027 pressKeyRect = pressKeySurf.get_rect()
1028 pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
1029 DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
1030
1031
1032 def checkForKeyPress():
1033 if len(pygame.event.get(QUIT)) > 0:
1034 terminate()
1035
1036 keyUpEvents = pygame.event.get(KEYUP)
1037 if len(keyUpEvents) == 0:
1038 return None
1039 if keyUpEvents[0].key == K_ESCAPE or keyUpEvents[0].key == K_q:
1040 terminate()
1041 return keyUpEvents[0].key
1042
1043
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1044 def showSelectPlayersScreen():
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1045 """
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1046 Blits player/opponent select onto screen. Returns selection as list.
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1047 """
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1048 playerbuttons = [] # not yet implemented
1049 playersnakeybutton = SelectButton('(s)nakey', WINDOWWIDTH / 3, WINDOWHEIGHT * 2/7, True)
1050 playerbuttons.append(playersnakeybutton)
1051 playerlinusbutton = SelectButton('(l)inus', WINDOWWIDTH / 3, WINDOWHEIGHT * 3/7)
1052 playerbuttons.append(playerlinusbutton)
1053 playerwigglesbutton = SelectButton('(w)iggles', WINDOWWIDTH / 3, WINDOWHEIGHT * 4/7)
1054 playerbuttons.append(playerwigglesbutton)
1055 playergigglesbutton = SelectButton('(g)iggles', WINDOWWIDTH / 3, WINDOWHEIGHT * 5/7)
1056 playerbuttons.append(playergigglesbutton)
1057
1058 opponentbuttons = [] # not yet implemented
1059 opponentlinusbutton = SelectButton('(l)inus', WINDOWWIDTH / 3 * 2, WINDOWHEIGHT * 3/7, True)
1060 opponentbuttons.append(opponentlinusbutton)
1061 opponentwigglesbutton = SelectButton('(w)iggles', WINDOWWIDTH / 3 * 2, WINDOWHEIGHT * 4/7)
1062 opponentbuttons.append(opponentwigglesbutton)
1063 opponentgigglesbutton = SelectButton('(g)iggles', WINDOWWIDTH / 3 * 2, WINDOWHEIGHT * 5/7)
1064 opponentbuttons.append(opponentgigglesbutton)
1065
1066
1067 cancelbutton = Button('(e)xit', WINDOWWIDTH / 3, WINDOWHEIGHT * 6/7)
1068 acceptbutton = Button('(d)uel!', WINDOWWIDTH / 3 * 2, WINDOWHEIGHT * 6/7)
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1069
1070 while True:
1071
1072 choiceFont = pygame.font.Font('freesansbold.ttf', 36)
1073 choiceSurf = choiceFont.render('Choose Opponent:', True, WHITE, FORESTGREEN)
1074 choiceRect = choiceSurf.get_rect()
1075
1076 DISPLAYSURF.fill(BGCOLOR)
1077 DISPLAYSURF.blit(choiceSurf, choiceRect)
1078
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1079 # display all buttons
1080 for button in playerbuttons:
1081 button.display()
1082 for button in opponentbuttons:
1083 button.display()
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1084 cancelbutton.display()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1085 acceptbutton.display()
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1086
1087 for event in pygame.event.get():
1088 if event.type == QUIT:
1089 terminate()
1090 elif event.type == MOUSEBUTTONDOWN:
1091 mouse = pygame.mouse.get_pos()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1092 # check each button for player
1093 for button in playerbuttons:
1094 if button.pressed(mouse):
1095 button.setActive(playerbuttons)
1096 # check each button for opponent
1097 for button in opponentbuttons:
1098 if button.pressed(mouse):
1099 button.setActive(opponentbuttons)
1100 # check cancel/accept buttons
1101 if cancelbutton.pressed(mouse):
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1102 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1103 return False
1104 elif acceptbutton.pressed(mouse):
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1105 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1106 final = []
1107 if playersnakeybutton.active:
1108 final.append(SNAKEY)
1109 elif playerlinusbutton.active:
1110 final.append(LINUS)
1111 elif playerwigglesbutton.active:
1112 final.append(WIGGLES)
1113 elif playergigglesbutton.active:
1114 final.append(GIGGLES)
1115 if opponentlinusbutton.active:
1116 final.append(LINUS)
1117 elif opponentwigglesbutton.active:
1118 final.append(WIGGLES)
1119 elif opponentgigglesbutton.active:
1120 final.append(GIGGLES)
1121 return final
1122
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1123 elif event.type == KEYDOWN:
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1124 if event.key == K_s:
1125 pygame.event.get()
1126 playersnakeybutton.setActive(playerbuttons)
1127 elif event.key == K_l:
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1128 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1129 opponentlinusbutton.setActive(opponentbuttons)
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1130 elif event.key == K_w:
1131 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1132 opponentwigglesbutton.setActive(opponentbuttons)
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1133 elif event.key == K_g:
1134 pygame.event.get()
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1135 opponentgigglesbutton.setActive(opponentbuttons)
1136 elif event.key == K_d:
1137 final = []
1138 if playersnakeybutton.active:
1139 final.append(SNAKEY)
1140 elif playerlinusbutton.active:
1141 final.append(LINUS)
1142 elif playerwigglesbutton.active:
1143 final.append(WIGGLES)
1144 elif playergigglesbutton.active:
1145 final.append(GIGGLES)
1146 if opponentlinusbutton.active:
1147 final.append(LINUS)
1148 elif opponentwigglesbutton.active:
1149 final.append(WIGGLES)
1150 elif opponentgigglesbutton.active:
1151 final.append(GIGGLES)
1152 return final
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1153 elif event.key == K_e:
1154 pygame.event.get()
1155 return False
1156 elif event.key == K_ESCAPE or event.key == K_q:
1157 terminate()
1158
1159 pygame.display.update()
1160
1161
b68496b @djrahl first commit
authored Jul 3, 2012
1162 def showInstructScreen():
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1163 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1164 Blits instructions onto screen. Returns when exit button clicked / key pressed.
1165 """
b68496b @djrahl first commit
authored Jul 3, 2012
1166 endinstructbutton = Button('(e)xit', WINDOWWIDTH / 2, WINDOWHEIGHT - 40)
1167
1168 while True:
1169
1170 instruct = pygame.image.load('snakey_party_instructions.png').convert()
1171
1172 DISPLAYSURF.blit(instruct, (54, 10))
1173
1174 endinstructbutton.display()
1175
1176 for event in pygame.event.get():
1177 if event.type == QUIT:
1178 terminate()
1179 elif event.type == MOUSEBUTTONDOWN:
1180 mouse = pygame.mouse.get_pos()
1181 if endinstructbutton.pressed(mouse):
1182 pygame.event.get()
1183 return
1184 elif event.type == KEYDOWN:
1185 if event.key == K_e or event.key == K_i:
1186 pygame.event.get()
1187 return
1188 elif event.key == K_ESCAPE or event.key == K_q:
1189 terminate()
1190
1191 pygame.display.update()
1192
1193
1194 def terminate():
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1195 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1196 Clean exit from pygame.
1197 """
b68496b @djrahl first commit
authored Jul 3, 2012
1198 pygame.quit()
1199 sys.exit()
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1200
1201
1202 def showGameStats(allsnake):
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1203 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1204 Displays game stats for all snakes at end of game.
1205 Returns when any key pressed.
1206 """
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1207 position = 1
1208 for snake in allsnake:
9504e62 @djrahl added party mode.
authored Jul 25, 2012
1209 drawText('alive:', snake.alive, getPosition(position, allsnake), 25, snake.color)
1210 drawText('score:', snake.score, getPosition(position, allsnake), 45, snake.color)
1211 drawText('apples:', snake.fruitEaten['apple'], getPosition(position, allsnake), 65, RED)
1212 drawText('poison:', snake.fruitEaten['poison'], getPosition(position, allsnake), 85, GREEN)
1213 drawText('oranges:', snake.fruitEaten['orange'], getPosition(position, allsnake), 105, ORANGE)
1214 drawText('raspberries:', snake.fruitEaten['raspberry'], getPosition(position, allsnake), 125, PURPLE)
1215 drawText('blueberries:', snake.fruitEaten['blueberry'], getPosition(position, allsnake), 145, BLUE)
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1216 position = position + 1
1217
1218 drawPressKeyMsg()
1219 pygame.display.update()
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1220 pygame.time.wait(200)
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1221 checkForKeyPress() # clear out any key presses in the event queue
1222
1223 while True:
1224 if checkForKeyPress():
1225 pygame.event.get() # clear event queue
1226 return
b68496b @djrahl first commit
authored Jul 3, 2012
1227
1228
1229 def showGameOverScreen():
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1230 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1231 Displays 'Game Over' message.
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1232 Returns when any key pressed.
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1233 """
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1234 gameOverFont = pygame.font.Font('freesansbold.ttf', 120)
b68496b @djrahl first commit
authored Jul 3, 2012
1235 gameSurf = gameOverFont.render('Game', True, WHITE)
1236 overSurf = gameOverFont.render('Over', True, WHITE)
1237 gameRect = gameSurf.get_rect()
1238 overRect = overSurf.get_rect()
1239 gameRect.midtop = (WINDOWWIDTH / 2, 10)
1240 overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25)
1241
1242 DISPLAYSURF.blit(gameSurf, gameRect)
1243 DISPLAYSURF.blit(overSurf, overRect)
1244 drawPressKeyMsg()
1245 pygame.display.update()
a734fdb @djrahl Added snake choices for duel mode.
authored Aug 1, 2012
1246 pygame.time.wait(200)
b68496b @djrahl first commit
authored Jul 3, 2012
1247 checkForKeyPress() # clear out any key presses in the event queue
1248
1249 while True:
1250 if checkForKeyPress():
1251 pygame.event.get() # clear event queue
1252 return
1253
1254
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1255 def getGrid(allsnake, allfruit):
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1256 """
c46945d @djrahl Moved Tally Class into Game Data- now passed from menu. Added support…
authored Aug 3, 2012
1257 Returns dictionary representation of all snakes and fruits on screen.
1258 Coordinates are entered as tuple (x,y).
1259 Used by AI when choosing best path.
1260 """
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1261 # refresh grid, dictionary representation of playing board used by AI
1262 grid = {(x,y):0 for x in range(CELLWIDTH) for y in range(CELLHEIGHT + (BUFFER / CELLSIZE))}
1263
1264 # add snakes to grid
1265 for snake in allsnake:
1266 for snakebody in snake.coords:
1267 grid[(snakebody['x'], snakebody['y'])] = 'snake'
6c613da @djrahl Worked on AI; added crude apple detection.
authored Jul 25, 2012
1268
1269 # add fruits to grid
1270 for fruit in allfruit:
1271 if fruit.__class__ == Apple:
1272 grid[(fruit.coords['x'], fruit.coords['y'])] = 'apple'
1273
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1274 return grid
b68496b @djrahl first commit
authored Jul 3, 2012
1275
1276
9504e62 @djrahl added party mode.
authored Jul 25, 2012
1277 def drawText(text, value, x=1, y=1, color=WHITE, background=BLACK):
1278 scoreSurf = BASICFONT.render('%s %s' % (text, value), True, color, background)
b68496b @djrahl first commit
authored Jul 3, 2012
1279 scoreRect = scoreSurf.get_rect()
faa87d1 @djrahl added Snake, Fruit, Tally classes
authored Jul 12, 2012
1280 scoreRect.topleft = (x, y)
b68496b @djrahl first commit
authored Jul 3, 2012
1281 DISPLAYSURF.blit(scoreSurf, scoreRect)
1282
1283
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1284
b68496b @djrahl first commit
authored Jul 3, 2012
1285 def drawGrid():
1286 for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1287 pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, BUFFER), (x, WINDOWHEIGHT))
4ae7881 @djrahl Fixed grid and snake color changes.
authored Jul 26, 2012
1288 for y in range(BUFFER, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines
1289 pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1290
1291
1292 def debugPause():
1293 while True:
1294 if checkForKeyPress():
1295 return
1296
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1297
6d8cfaf @djrahl set-up ai
authored Jul 19, 2012
1298 def debugPrintGrid(grid):
1299 x = 0
1300 y = 0
1301 line = ""
1302 while grid.has_key((0,y)):
1303 if grid.has_key((x,y)):
1304 line = line + str(grid[(x,y)])[0]
1305 x = x + 1
1306 else:
1307 print line
1308 line = ""
1309 y = y + 1
1310 x = 0
b68496b @djrahl first commit
authored Jul 3, 2012
1311
1312
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1313 def getPosition(position, allsnake):
1314 return (WINDOWWIDTH - (float(position) / float(len(allsnake)) * WINDOWWIDTH))
6127227 @djrahl Added more selection for Duel Mode.
authored Aug 6, 2012
1315
1316
1317 def getStartPosition(pos=1):
1318 if pos == 1:
1319 return [{'x':5, 'y':5},{'x':4, 'y':5},{'x':3, 'y':5}]
1320 elif pos == 2:
1321 return [{'x':CELLWIDTH-5, 'y':CELLHEIGHT-5},{'x':CELLWIDTH-4, 'y':CELLHEIGHT-5},{'x':CELLWIDTH-3, 'y':CELLHEIGHT-5}]
1322 elif pos == 3:
1323 return [{'x':CELLWIDTH-5, 'y':5},{'x':CELLWIDTH-4, 'y':5},{'x':CELLWIDTH-3, 'y':5}]
1324 elif pos == 4:
1325 [{'x':5, 'y':CELLHEIGHT-5},{'x':4, 'y':CELLHEIGHT-5},{'x':3, 'y':CELLHEIGHT-5}]
4b2744c @djrahl added post-game tally, added event handling for sharp turns
authored Jul 24, 2012
1326
1327
b68496b @djrahl first commit
authored Jul 3, 2012
1328 if __name__ == '__main__':
1329 main()
1330
Something went wrong with that request. Please try again.