Show name of key instead of code object.
[troncode.git] / troncode.py
blob54711dba537e1f38024fc354a95a4405a1d05fbc
1 #!/usr/bin/python -u
3 # troncode - write programs to play the classic lines game
5 # Copyright (C) 2008 Andy Balaam
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 # USA.
23 import gc
24 import math
25 import os
26 import pygame
27 from pygame.locals import *
28 import random
29 import re
30 import sys
31 import time
33 from AbstractGameBoard import AbstractGameBoard
34 from mopelib import mopelib
35 from troncode_values import *
37 # ----------------------
38 class TronCodeConfig( mopelib.Config ):
40 def default_config( self ):
41 self.num_players = 2
42 self.tick_time = 20
44 self.screen_size = ( 610, 635 )
45 self.colour_background = ( 0, 0, 0 )
47 self.volume = 50
49 self.music_on = 1
50 self.sound_effects_on = 1
52 self.keys_menu = mopelib.MyInputEvent( "Escape" )
53 self.keys_menu.add( pygame.KEYDOWN, pygame.K_ESCAPE )
54 self.keys_menu.add( pygame.JOYBUTTONDOWN, 8 ) # GP2X Start
55 self.keys_menu.add( pygame.JOYBUTTONDOWN, 9 ) # GP2X Select
57 self.keys_return = mopelib.MyInputEvent( "Return" )
58 self.keys_return.add( pygame.KEYDOWN, pygame.K_RETURN )
59 self.keys_return.add( pygame.JOYBUTTONDOWN, 13 ) # GP2X B button
61 self.keys_startgame = mopelib.MyInputEvent( "any key" )
62 self.keys_startgame.add_all( pygame.KEYDOWN )
63 self.keys_startgame.add_all( pygame.JOYBUTTONDOWN )
64 self.keys_startgame.add_all( pygame.MOUSEBUTTONDOWN )
66 self.keys_up = mopelib.MyInputEvent( "up" )
67 self.keys_up.add( pygame.KEYDOWN, ord( 'q' ) )
68 self.keys_up.add( pygame.KEYDOWN, pygame.K_UP )
69 self.keys_up.add( pygame.JOYBUTTONDOWN, 0 ) # GP2X Joy up
70 self.keys_up.add( pygame.JOYBUTTONDOWN, 15 ) # GP2X Y button
72 self.keys_right = mopelib.MyInputEvent( "right" )
73 self.keys_right.add( pygame.KEYDOWN, ord( 'p' ) )
74 self.keys_right.add( pygame.KEYDOWN, pygame.K_RIGHT )
75 self.keys_right.add( pygame.JOYBUTTONDOWN, 6 ) # GP2X Joy right
76 self.keys_right.add( pygame.JOYBUTTONDOWN, 13 ) # GP2X B button
78 self.keys_down = mopelib.MyInputEvent( "down" )
79 self.keys_down.add( pygame.KEYDOWN, ord( 'a' ) )
80 self.keys_down.add( pygame.KEYDOWN, pygame.K_DOWN )
81 self.keys_down.add( pygame.JOYBUTTONDOWN, 4 ) # GP2X Joy down
82 self.keys_down.add( pygame.JOYBUTTONDOWN, 14 ) # GP2X X button
84 self.keys_left = mopelib.MyInputEvent( "left" )
85 self.keys_left.add( pygame.KEYDOWN, ord( 'o' ) )
86 self.keys_left.add( pygame.KEYDOWN, pygame.K_LEFT )
87 self.keys_left.add( pygame.JOYBUTTONDOWN, 2 ) # GP2X Joy left
88 self.keys_left.add( pygame.JOYBUTTONDOWN, 12 ) # GP2X A button
90 self.keys_volup = mopelib.MyInputEvent( "+" )
91 self.keys_volup.add( pygame.KEYDOWN, ord( '+' ) )
92 self.keys_volup.add( pygame.KEYDOWN, ord( '=' ) )
93 self.keys_volup.add( pygame.JOYBUTTONDOWN, 16 ) # GP2X volume + button
95 self.keys_slow = mopelib.MyInputEvent( "s" )
96 self.keys_slow.add( pygame.KEYDOWN, ord( 's' ) )
98 self.keys_fast = mopelib.MyInputEvent( "f" )
99 self.keys_fast.add( pygame.KEYDOWN, ord( 'f' ) )
101 self.keys_skip_to_end = mopelib.MyInputEvent( "k" )
102 self.keys_skip_to_end.add( pygame.KEYDOWN, ord( 'k' ) )
104 self.keys_voldown = mopelib.MyInputEvent( "-" )
105 self.keys_voldown.add( pygame.KEYDOWN, ord( '-' ) )
106 self.keys_voldown.add( pygame.JOYBUTTONDOWN, 17 ) # GP2X volume - button
108 self.keys_p1_up = mopelib.MyInputEvent( "p1_up" )
109 self.keys_p1_up.add( pygame.KEYDOWN, pygame.K_UP )
110 self.keys_p1_up.add( pygame.JOYBUTTONDOWN, 0 ) # GP2X Joy up
112 self.keys_p1_right = mopelib.MyInputEvent( "p1_right" )
113 self.keys_p1_right.add( pygame.KEYDOWN, pygame.K_RIGHT )
114 self.keys_p1_right.add( pygame.JOYBUTTONDOWN, 6 ) # GP2X Joy right
116 self.keys_p1_down = mopelib.MyInputEvent( "p1_down" )
117 self.keys_p1_down.add( pygame.KEYDOWN, pygame.K_DOWN )
118 self.keys_p1_down.add( pygame.JOYBUTTONDOWN, 4 ) # GP2X Joy down
120 self.keys_p1_left = mopelib.MyInputEvent( "p1_left" )
121 self.keys_p1_left.add( pygame.KEYDOWN, pygame.K_LEFT )
122 self.keys_p1_left.add( pygame.JOYBUTTONDOWN, 4 ) # GP2X Joy left
124 self.keys_p2_up = mopelib.MyInputEvent( "p2_up" )
125 self.keys_p2_up.add( pygame.KEYDOWN, ord( '2' ) )
126 self.keys_p2_up.add( pygame.JOYBUTTONDOWN, 15 ) # GP2X Y button
128 self.keys_p2_right = mopelib.MyInputEvent( "p2_right" )
129 self.keys_p2_right.add( pygame.KEYDOWN, ord( 'e' ) )
130 self.keys_p2_right.add( pygame.JOYBUTTONDOWN, 13 ) # GP2X B button
132 self.keys_p2_down = mopelib.MyInputEvent( "p2_down" )
133 self.keys_p2_down.add( pygame.KEYDOWN, ord( 'w' ) )
134 self.keys_p2_down.add( pygame.JOYBUTTONDOWN, 14 ) # GP2X X button
136 self.keys_p2_left = mopelib.MyInputEvent( "p2_left" )
137 self.keys_p2_left.add( pygame.KEYDOWN, ord( 'q' ) )
138 self.keys_p2_left.add( pygame.JOYBUTTONDOWN, 12 ) # GP2X A button
140 self.keys_p3_up = mopelib.MyInputEvent( "p3_up" )
141 self.keys_p3_up.add( pygame.KEYDOWN, ord( 'i' ) )
143 self.keys_p3_right = mopelib.MyInputEvent( "p3_right" )
144 self.keys_p3_right.add( pygame.KEYDOWN, ord( 'l' ) )
146 self.keys_p3_down = mopelib.MyInputEvent( "p3_down" )
147 self.keys_p3_down.add( pygame.KEYDOWN, ord( 'k' ) )
149 self.keys_p3_left = mopelib.MyInputEvent( "p3_left" )
150 self.keys_p3_left.add( pygame.KEYDOWN, ord( 'j' ) )
152 self.keys_p4_up = mopelib.MyInputEvent( "p4_up" )
153 self.keys_p4_up.add( pygame.KEYDOWN, pygame.K_KP8 )
155 self.keys_p4_right = mopelib.MyInputEvent( "p4_right" )
156 self.keys_p4_right.add( pygame.KEYDOWN, pygame.K_KP6 )
158 self.keys_p4_down = mopelib.MyInputEvent( "p4_down" )
159 self.keys_p4_down.add( pygame.KEYDOWN, pygame.K_KP5 )
160 self.keys_p4_down.add( pygame.KEYDOWN, pygame.K_KP2 )
162 self.keys_p4_left = mopelib.MyInputEvent( "p4_left" )
163 self.keys_p4_left.add( pygame.KEYDOWN, pygame.K_KP4 )
166 # ----------------------
168 class TronCodeSoundManager( mopelib.SoundManager ):
170 def __init__( self, volume ):
171 mopelib.SoundManager.__init__( self, config )
173 #self.add_sample_group( "waddles", ["waddle1"] )
175 # ----------------------
177 def intro_draw_keys():
178 keys_colour = (0, 0, 0)
179 write_text( "Keys", keys_colour, 0.2, 0.05 )
180 write_text( "Slow down: %s" % config.keys_slow.name, keys_colour, 0.1, 0.25 )
181 write_text( "Speed up: %s" % config.keys_fast.name, keys_colour, 0.1, 0.35 )
182 write_text( "Skip round: %s" % config.keys_skip_to_end.name, keys_colour, 0.1, 0.45 )
184 # ----------------------
186 def intro_draw_instructions():
187 write_text( "Press %s for menu, or %s to start" % (
188 config.keys_menu.name, config.keys_startgame.name ),
189 (0, 0, 0), 0.05, 0.99 )
191 # ----------------------
193 def general_menu_create_menu( menu, config, gamestate ):
194 menu.items = []
195 if gamestate == None: # We are on a title screen - Start Game option
196 menu.add_item( "Start game", MENU_START )
197 menu.add_item( "Number of players: %d" % (config.num_players),
198 MENU_NUM_PLAYERS )
199 for player_num in range( config.num_players ):
200 cls_name = "--unknown--"
201 if player_num < len( config.player_classes ):
202 cls_name = config.player_classes[player_num].GetName()
203 menu.add_item( "P%d: %s" % ( player_num, cls_name ),
204 MENU_CHANGE_PLAYER + player_num )
205 else:
206 menu.add_item( "Continue", MENU_START )
207 menu.add_item( "End game", MENU_END )
209 tmp_str = "Music: "
210 if config.music_on:
211 tmp_str += "on"
212 else:
213 tmp_str += "off"
214 menu.add_item( tmp_str, MENU_MUSIC )
216 tmp_str = "Effects: "
217 if config.sound_effects_on:
218 tmp_str += "on"
219 else:
220 tmp_str += "off"
221 menu.add_item( tmp_str, MENU_SOUND_EFFECTS )
223 menu.add_item( "Quit troncode", MENU_QUIT )
225 return menu
227 def general_menu_screen( config, gamestate ):
229 if gamestate == None:
230 menu_title = "troncode"
231 else:
232 menu_title = "troncode paused"
234 menu = mopelib.Menu()
235 general_menu_create_menu( menu, config, gamestate )
236 menurender.set_menu( menu, menu_title )
237 menurender.repaint_full()
239 game_start = False
241 waiting = True
242 while waiting:
243 event = pygame.event.wait()
244 if event.type == QUIT:
245 sys.exit(0)
246 elif config.keys_menu.matches( event ):
247 waiting = False
248 elif config.keys_down.matches( event ):
249 menurender.move_down()
250 elif config.keys_up.matches( event ):
251 menurender.move_up()
252 elif config.keys_return.matches( event ):
253 code = menu.get_selected_item().code
254 if code == MENU_START:
255 game_start = True
256 waiting = False
257 elif code == MENU_END:
258 gamestate.alive = INGAME_QUIT
259 waiting = False
260 elif code == MENU_MUSIC:
261 if config.music_on == 1:
262 config.music_on = 0
263 else:
264 config.music_on = 1
265 general_menu_create_menu( menu, config, gamestate )
266 menurender.repaint_full()
267 sound_mgr.setup( gamestate )
268 config.save()
269 elif code == MENU_SOUND_EFFECTS:
270 if config.sound_effects_on:
271 config.sound_effects_on = 0
272 else:
273 config.sound_effects_on = 1
274 general_menu_create_menu( menu, config, gamestate )
275 menurender.repaint_full()
276 sound_mgr.setup( gamestate )
277 config.save()
278 elif code == MENU_QUIT:
279 sys.exit(0)
281 return game_start
283 # ----------------------
285 def intro_draw_title():
286 screen.blit( intro_surface_title, (0,0) )
287 write_text( "Version " + troncode_version,
288 ( 0, 0, 0 ), 0.05, 0.88 )
289 write_text( "by Andy Balaam", ( 0, 0, 0 ), 0.06, 0.93 )
290 intro_draw_instructions()
292 def intro_draw_something( intro_mode ):
293 if intro_mode == INTRO_MODE_TITLE:
294 intro_draw_title()
295 elif intro_mode == INTRO_MODE_INSTR:
296 screen.blit( intro_surface_instr, (0,0) )
297 intro_draw_instructions()
298 elif intro_mode == INTRO_MODE_MUSIC:
299 screen.blit( intro_surface_music, (0,0) )
300 intro_draw_keys()
301 intro_draw_instructions()
302 pygame.display.update()
304 def intro_input( event, config, intro_mode ):
305 if event.type == QUIT:
306 sys.exit(0)
307 elif config.keys_volup.matches( event ):
308 config.volume = sound_mgr.increase_volume()
309 config.save()
310 elif config.keys_voldown.matches( event ):
311 config.volume = sound_mgr.decrease_volume()
312 config.save()
313 else:
314 if event.type == EVENTTYPE_TITLE_TICK:
315 intro_mode += 1
316 if intro_mode == INTRO_MODE_ENDED:
317 intro_mode = INTRO_MODE_TITLE
318 intro_draw_something( intro_mode )
319 elif config.keys_menu.matches( event ):
320 mopelib.clear_events( EVENTTYPE_TITLE_TICK )
321 start_game = general_menu_screen( config, None )
322 if start_game:
323 intro_mode = INTRO_MODE_ENDED
324 else:
325 intro_draw_something( intro_mode )
326 pygame.time.set_timer( EVENTTYPE_TITLE_TICK, TITLE_TICK_TIME )
327 elif config.keys_startgame.matches( event ):
328 intro_mode = INTRO_MODE_ENDED
329 return intro_mode
331 # ----------------------
333 def intro_mainloop( config ):
334 intro_draw_title()
336 pygame.display.update()
337 pygame.time.set_timer( EVENTTYPE_TITLE_TICK, TITLE_TICK_TIME )
339 intro_mode = INTRO_MODE_TITLE
340 while intro_mode < INTRO_MODE_ENDED:
341 intro_mode = intro_input( pygame.event.wait(), config, intro_mode )
343 mopelib.clear_events( EVENTTYPE_TITLE_TICK )
345 def draw_pixel( gamestate, surface, colour, x, y, alive_colours ):
346 if colour in alive_colours:
347 col = colour
348 else:
349 col = mopelib.dim_colour( colour, gamestate.dim )
350 adj_x = screen_border[0] + scale * x
351 adj_y = screen_border[1] + scale * y
352 if scale < 1:
353 surface.set_at( ( int(adj_x), int(adj_y) ), col )
354 else:
355 pygame.draw.rect( surface, col,
356 (adj_x, adj_y, ceil_scale, ceil_scale ) )
358 def inlevel_screen_blit( gamestate ):
359 screen.blit( gamestate.offscreen_buff, (0,0) )
360 pygame.display.update()
362 def inlevel_redraw_screen( gamestate, arrows, scores ):
363 alive_colours = []
364 if gamestate.alive == INGAME_MOST_DEAD:
365 for player in gamestate.players:
366 if not gamestate.statuses[player]._dead:
367 alive_colours.append( player.GetColour() )
369 gamestate.offscreen_buff = pygame.Surface( gamestate.config.screen_size )
370 gamestate.offscreen_buff.blit( ingame_surface_background, (0,0) )
371 for x, y, colour in gamestate.pixels_list:
372 draw_pixel( gamestate, gamestate.offscreen_buff, colour, x, y, alive_colours )
373 inlevel_draw_players( gamestate, alive_colours )
374 write_text_ingame( gamestate, scores )
375 # TODO: draw arrows
376 inlevel_screen_blit( gamestate )
378 def inlevel_draw_players( gamestate, alive_colours ):
379 for player in gamestate.players:
380 x, y = gamestate.GetPosition( player )
381 draw_pixel( gamestate, gamestate.offscreen_buff, player.GetColour(),
382 x, y, alive_colours )
384 def inlevel_update_screen( gamestate, scores ):
385 inlevel_draw_players( gamestate, [] )
386 inlevel_screen_blit( gamestate )
390 # ----------------------
392 def inlevel_input( event, gamestate, scores ):
393 if event.type == QUIT:
394 sys.exit(0)
395 elif config.keys_menu.matches( event ):
396 general_menu_screen( config, gamestate )
397 inlevel_redraw_screen( gamestate, False, scores )
398 elif config.keys_volup.matches( event ):
399 config.volume = sound_mgr.increase_volume()
400 config.save()
401 elif config.keys_voldown.matches( event ):
402 config.volume = sound_mgr.decrease_volume()
403 config.save()
404 elif config.keys_slow.matches( event ):
405 gamestate.framerate = 0
406 inlevel_redraw_screen( gamestate, False, scores )
407 elif config.keys_fast.matches( event ):
408 if gamestate.framerate == 0:
409 gamestate.framerate = 1
410 elif gamestate.framerate == 1:
411 gamestate.framerate = 250
412 else:
413 gamestate.framerate *= 2
414 elif config.keys_skip_to_end.matches( event ):
415 gamestate.framerate = 1000000
416 else:
417 gamestate.key_events.append( event )
420 # ----------------------
422 def finishedgame_input( event, waiting ):
423 if event.type == QUIT:
424 sys.exit(0)
425 elif config.keys_volup.matches( event ):
426 config.volume = sound_mgr.increase_volume()
427 config.save()
428 elif config.keys_voldown.matches( event ):
429 config.volume = sound_mgr.decrease_volume()
430 config.save()
431 elif config.keys_startgame.matches( event ):
432 waiting = False
433 return waiting
435 # ----------------------
437 class PlayerStatus:
438 def __init__( self, x, y, direction, player ):
439 self._x = x
440 self._y = y
441 self._dir = direction
442 self._colour = player.GetColour()
443 self._dead = False
445 def GetPosition( self ):
446 return ( self._x, self._y )
448 def GetDirection( self ):
449 return ( self._dir )
451 def SetDirection( self, direction ):
452 self._dir = direction
454 def SetDead( self, dead ):
455 self._dead = dead
457 def IsDead( self ):
458 return self._dead
460 def Move( self, gamestate ):
461 """Moves the player one position depending on its direction, and
462 returns True if it hit anything, False otherwise."""
464 if self._dead:
465 return self._dead
467 if self._dir == DIR_UP:
468 self._y -= 1
469 elif self._dir == DIR_RIGHT:
470 self._x += 1
471 elif self._dir == DIR_DOWN:
472 self._y += 1
473 elif self._dir == DIR_LEFT:
474 self._x -= 1
476 self._dead = gamestate.AddPixel( self._x, self._y, self._colour )
478 return self._dead
480 class GameBoard( AbstractGameBoard ):
481 def __init__( self, gamestate ):
482 self._gamestate = gamestate
484 def GetRelativePixel( self, start_pos, facing_dir,
485 offset_fwd, offset_right ):
486 """Given a position to stand in the arena, and a direction to face,
487 return the status (0 for empty, >0 for non-empty) of a pixel that
488 is offset_fwd pixels in front, and offset_right pixels to the right
489 (negative values may be used to go backwards or left respectively).
490 Pixels outside the arena also return >0."""
492 if facing_dir == DIR_UP:
493 found_pos = ( start_pos[0] + offset_right,
494 start_pos[1] - offset_fwd )
495 elif facing_dir == DIR_RIGHT:
496 found_pos = ( start_pos[0] + offset_fwd,
497 start_pos[1] + offset_right )
498 elif facing_dir == DIR_DOWN:
499 found_pos = ( start_pos[0] - offset_right,
500 start_pos[1] + offset_fwd )
501 elif facing_dir == DIR_LEFT:
502 found_pos = ( start_pos[0] - offset_fwd,
503 start_pos[1] - offset_right )
505 if ( found_pos[0] < 0 or
506 found_pos[0] >= self._gamestate.config.arena_size[0] or
507 found_pos[1] < 0 or
508 found_pos[1] >= self._gamestate.config.arena_size[1] ):
509 retval = 100
510 elif found_pos in self._gamestate.pixels_set:
511 retval = 1
512 else:
513 retval = 0
515 return retval
517 def GetPlayerPositions( self, pos_to_exclude = None ):
518 """Returns a list of pairs (pos, dir) for each player on screen.
519 Excludes the player at the position specified if pos_to_exclude
520 is not None."""
522 ret = []
524 for player in self._gamestate.statuses.keys():
525 status = self._gamestate.statuses[player]
526 if not status.IsDead():
527 pos = status.GetPosition()
528 if pos_to_exclude != pos:
529 ret.append( ( pos, status.GetDirection() ) )
531 return ret
533 def TurnRight( self, direction ):
534 """Return the direction found by turning 90 degrees right from
535 the supplied direction."""
536 direction += 1
537 if direction > DIR_LEFT:
538 direction = DIR_UP
539 return direction
541 def TurnLeft( self, direction ):
542 """Return the direction found by turning 90 degrees left from
543 the supplied direction."""
544 direction -= 1
545 if direction < DIR_UP:
546 direction = DIR_LEFT
547 return direction
549 def class_is_human( cls ):
550 return "IsHuman" in cls.__dict__ and cls.IsHuman()
552 class GameState:
553 def __init__( self, config, classes ):
554 self.config = config
556 self.players = []
557 self.key_events = []
558 self.any_humans = False
560 for cls in classes:
561 if class_is_human( cls ):
562 self.players.append( cls( config.keys_p1_up,
563 config.keys_p1_right, config.keys_p1_down,
564 config.keys_p1_left ) )
565 self.any_humans = True
566 else:
567 self.players.append( cls() )
569 self.alive = INGAME_TWO_ALIVE
570 self.dim = 1
572 self.pixels_list = []
573 self.pixels_set = set()
574 self.create_initial_pixels()
576 self.statuses = {}
577 for player in self.players:
578 x = random.randint( config.starting_border, config.arena_size[0]
579 - config.starting_border )
580 y = random.randint( config.starting_border, config.arena_size[1]
581 - config.starting_border )
582 dr = random.randint( DIR_UP, DIR_LEFT )
583 self.statuses[player] = PlayerStatus( x, y, dr, player )
584 self.AddPixel( x, y, player.GetColour() )
586 self._gameboard = GameBoard( self )
588 def timer_tick( self ):
589 num_alive = 0
590 for player in self.players:
591 status = self.statuses[player]
592 if not status.IsDead():
593 if class_is_human( player.__class__ ):
594 new_dir = player.GetDirWithInput( status.GetDirection(),
595 self.key_events )
596 else:
597 new_dir = player.GetDir( status.GetPosition(),
598 status.GetDirection(), self._gameboard )
599 if new_dir not in (DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT):
600 sys.stderr.write( "Player '" + player.GetName()
601 + "' returned an invalid value from GetDir(). Killing it.\n" )
602 new_dir = DIR_UP
603 status.SetDead( True )
605 status.SetDirection( new_dir )
606 # TODO: copy pixels list for "security"?
608 dead = self.statuses[player].Move( self )
609 if not dead:
610 num_alive += 1
612 if num_alive < 2:
613 self.alive = INGAME_MOST_DEAD
615 def create_initial_pixels( self ):
616 colour = (100, 100, 100)
617 size_x, size_y = config.arena_size
618 for x in range( size_x ):
619 self.AddPixel( x, 0, colour )
620 self.AddPixel( x, size_y - 1, colour )
621 for y in range( 1, size_y - 1 ):
622 self.AddPixel( 0, y, colour )
623 self.AddPixel( size_x - 1, y, colour )
625 def GetPosition( self, player ):
626 return self.statuses[player].GetPosition()
628 def AddPixel( self, x, y, colour ):
629 if ( x, y ) in self.pixels_set:
630 dead = True
631 else:
632 dead = False
633 self.pixels_set.add( ( x, y ) )
635 self.pixels_list.append( ( x, y, colour ) )
637 return dead
640 # ----------------------
642 def ingame_mainloop( config ):
644 scores = {}
645 for cls in config.player_classes:
646 scores[cls] = 0
648 while True:
649 gamestate = GameState( config, config.player_classes )
650 inlevel_mainloop( config, gamestate, scores )
651 if gamestate.alive == INGAME_QUIT:
652 break
654 return gamestate
656 def increment_scores( gamestate, scores ):
657 for player in gamestate.players:
658 if not gamestate.statuses[player]._dead:
659 scores[player.__class__] += 1
661 # ----------------------
663 def inlevel_mainloop( config, gamestate, scores ):
665 gamestate.alive = INGAME_TWO_ALIVE
667 inlevel_redraw_screen( gamestate, True, scores )
668 if gamestate.any_humans:
669 time.sleep( 1 )
670 inlevel_redraw_screen( gamestate, False, scores )
672 gc.disable()
673 tick_counter = 0
675 gamestate.framerate = 0
677 while gamestate.alive == INGAME_TWO_ALIVE:
678 for evt in pygame.event.get():
679 inlevel_input( evt, gamestate, scores )
680 gamestate.timer_tick()
681 gamestate.key_events = []
682 tick_counter += 1
683 if gamestate.alive != INGAME_MOST_DEAD:
684 if gamestate.framerate <= 1:
685 inlevel_update_screen( gamestate, scores )
686 if gamestate.framerate == 0:
687 pygame.time.wait( config.tick_time )
688 elif tick_counter >= gamestate.framerate:
689 tick_counter = 0
690 inlevel_redraw_screen( gamestate, False, scores )
692 gc.enable()
693 mopelib.clear_events( EVENTTYPE_INGAME_TICK )
694 increment_scores( gamestate, scores )
696 finishedlevel_mainloop( gamestate, scores )
698 ingame_surface_background.fill( config.colour_background )
701 # ----------------------
703 def write_text( txt, colour, size, y_pos ):
704 ft = pygame.font.Font( None, int( config.screen_size[1] * size ) )
705 sf = ft.render( txt, True, colour )
706 screen.blit( sf, ( (config.screen_size[0] - sf.get_width() )/2,
707 (config.screen_size[1] - sf.get_height() ) * y_pos ) )
709 # ----------------------
711 def write_text_ingame( gamestate, scores ):
712 global ingame_font
714 txt = ""
715 for cls in scores.keys():
716 txt += "%s: %d " % ( cls.GetName(), scores[cls] )
718 colour = (128, 128, 128)
719 bgcolour = config.colour_background
720 y_pos = 0.996
721 sf = ingame_font.render( txt, True, colour )
722 sf_bg = pygame.Surface( ( int( sf.get_width() ), sf.get_height() ) )
723 sf_bg.fill( bgcolour )
725 tlx = ( config.screen_size[0] - sf_bg.get_width() ) / 2
726 tly = ( config.screen_size[1] - sf_bg.get_height() ) * y_pos
728 dirty_rect = Rect( tlx, tly, sf_bg.get_width(), sf_bg.get_height() )
729 gamestate.offscreen_buff.blit( sf_bg, dirty_rect )
730 gamestate.offscreen_buff.blit( sf, ( tlx * 1.01, tly ) )
732 # ----------------------
734 def finishedlevel_input( event, waiting, gamestate, scores ):
735 if event.type == QUIT:
736 sys.exit(0)
737 elif( ( event.type == pygame.ACTIVEEVENT and event.state == 2 )
738 or config.keys_menu.matches( event ) ):
739 general_menu_screen( config, gamestate )
740 inlevel_redraw_screen( gamestate, False, scores )
741 if gamestate.alive == INGAME_QUIT:
742 waiting = False
743 elif config.keys_volup.matches( event ):
744 config.volume = sound_mgr.increase_volume()
745 config.save()
746 elif config.keys_voldown.matches( event ):
747 config.volume = sound_mgr.decrease_volume()
748 config.save()
749 elif event.type == EVENTTYPE_TITLE_TICK:
750 waiting = False
751 elif config.keys_startgame.matches( event ):
752 waiting = False
753 return waiting
755 def finishedlevel_mainloop( gamestate, scores ):
756 gamestate.dim = 0.3
758 if not gamestate.any_humans:
759 pygame.time.set_timer( EVENTTYPE_TITLE_TICK, TITLE_TICK_TIME )
761 inlevel_redraw_screen( gamestate, False, scores )
762 waiting = True
763 while waiting:
764 waiting = finishedlevel_input( pygame.event.wait(), waiting, gamestate, scores )
766 if not gamestate.any_humans:
767 mopelib.clear_events( EVENTTYPE_TITLE_TICK )
769 def finishedgame_mainloop( config, gamestate ):
770 pass
771 #config.start_level = 0
772 # config.save()
774 # inlevel_redraw_screen( gamestate )
775 # write_text( "Congratulations!", (255,255,255), 0.125, 0.38 )
776 # write_text( "You won!", (255,255,255), 0.125, 0.52 )
777 # waiting = True
778 # write_text( "Press %s" % config.keys_startgame.name, (255,255,255),
779 # 0.05, 0.8 )
780 # pygame.display.update()
781 # while waiting:
782 # waiting = finishedgame_input( pygame.event.wait(), waiting )
784 # ingame_surface_background.fill( config.colour_background )
786 def sort_by_score( class2score ):
787 scorename_sorted = []
789 for cls in class2score.keys():
790 scorename_sorted.append( ( class2score[cls], cls.GetName() ) )
792 scorename_sorted.sort( reverse = True )
794 return scorename_sorted
796 def execute_tournament( config ):
797 total_scores = {}
799 classes = []
800 for cls in config.player_classes:
801 if not class_is_human( cls ):
802 classes.append( cls )
803 total_scores[cls] = 0
805 print
806 print " " * 30 + "=== Pairings ==="
807 print
809 pairs = []
810 num_classes = len( classes )
811 for i in range( num_classes ):
812 for j in range( i+1, num_classes ):
813 execute_match(
814 ( classes[i], classes[j] ),
815 total_scores, False )
817 print
818 print " " * 30 + "=== Medley ==="
819 print
821 execute_match( classes, total_scores, True )
823 print
824 print " " * 30 + "=== Total Scores ==="
825 print
827 scorename_sorted = sort_by_score( total_scores )
829 for score, name in scorename_sorted:
830 print "%30s % 4d" % ( name, score )
831 print
834 def execute_match( classes, total_scores, newlines ):
835 match_scores = {}
836 for cls in classes:
837 match_scores[cls] = 0
839 for i in range( config.num_games ):
840 gamestate = GameState( config, classes )
842 while gamestate.alive == INGAME_TWO_ALIVE:
843 gamestate.timer_tick()
845 for player in gamestate.statuses.keys():
846 status = gamestate.statuses[player]
847 if not status.IsDead():
848 match_scores[player.__class__] += 1
850 scorename_sorted = sort_by_score( match_scores )
852 oldscore = -1
853 for score, name in scorename_sorted:
854 if oldscore != -1 and not newlines:
855 if oldscore == score:
856 print " drew",
857 else:
858 print " beat",
859 print "%- 4d %-30s" % ( score, name ),
860 else:
861 print "%30s% 4d" % ( name, score ),
862 oldscore = score
865 if newlines:
866 print
868 if not newlines:
869 print
871 for cls in classes:
872 total_scores[cls] += match_scores[cls]
874 def get_players( players_dir ):
875 ret_classes = []
877 player_re = re.compile( """^(\w*Player).py$""" )
878 for filename in os.listdir( players_dir ):
879 m = player_re.match( filename )
880 if m:
881 class_name = m.group( 1 )
882 cls = __import__( "players." + class_name,
883 globals(), locals() ).__dict__[class_name].__dict__[class_name]
884 ret_classes.append( cls )
886 #return ret_classes[:2]
887 return ret_classes
889 # ----------------------
890 # Execution starts here
891 # ----------------------
893 # Fixed constants
895 INTRO_MODE_TITLE = 0
896 INTRO_MODE_INSTR = 1
897 INTRO_MODE_MUSIC = 2
898 INTRO_MODE_ENDED = 3
900 MENU_START = 0
901 MENU_NUM_PLAYERS = 1
902 MENU_END = 2
903 MENU_MUSIC = 3
904 MENU_SOUND_EFFECTS = 4
905 MENU_QUIT = 6
906 MENU_CHANGE_PLAYER = 100 # Must go at end of this list
908 INGAME_TWO_ALIVE = 0
909 INGAME_MOST_DEAD = 1
910 INGAME_QUIT = 2
912 TITLE_TICK_TIME = 4000
914 EVENTTYPE_INGAME_TICK = pygame.USEREVENT
915 EVENTTYPE_TITLE_TICK = pygame.USEREVENT + 1
917 num_args = len( sys.argv )
918 #if num_args > 1:
919 # if sys.argv[1] == "--help":
920 # print "Usage:"
921 # print "troncode.py [install_dir] [config_file] [resolution] "
922 # print " [num_players] [--tournament]"
923 # print
924 # print "e.g. ./troncode.py . troncoderc.txt '(640,480)' 2 --tournament"
925 # print
926 # sys.exit( 0 )
928 # install_dir = sys.argv[1]
929 #else:
930 # install_dir = "."
932 #if num_args > 2:
933 # config_filename = sys.argv[2]
934 #else:
935 # config_filename = os.path.expanduser( "~/.troncode/config" )
937 config_filename = os.path.expanduser( "~/.troncode/config" )
938 install_dir = "."
940 config = TronCodeConfig( config_filename )
942 if num_args > 1 and sys.argv[1] == "--tournament":
943 run_tournament = True
944 config.num_games = 100
945 else:
946 run_tournament = False
948 config.install_dir = install_dir
949 config.unsaved.append( "install_dir" )
951 config.images_dir = os.path.join( install_dir, "images" )
952 config.unsaved.append( "images_dir" )
954 config.music_dir = os.path.join( install_dir, "music" )
955 config.unsaved.append( "music_dir" )
957 if num_args > 3:
958 config.screen_size = config.parse_value( sys.argv[3] )
960 config.arena_size = ( 200, 200 )
961 config.unsaved.append( "arena_size" )
963 config.starting_border = 35
964 config.unsaved.append( "starting_border" )
966 config.players_dir = "players"
967 config.unsaved.append( "players_dir" )
969 config.player_classes = get_players( config.players_dir )
970 config.unsaved.append( "player_classes" )
972 config.players = []
973 config.unsaved.append( "players" )
975 if run_tournament:
976 execute_tournament( config )
977 else:
978 pygame.init()
979 pygame.font.init()
981 window = pygame.display.set_mode( config.screen_size )
982 pygame.display.set_caption( 'troncode' )
983 screen = pygame.display.get_surface()
985 fixed_border = 5
986 bottom_border = 25
987 scale = min(
988 ( float( config.screen_size[0] - fixed_border*2 )
989 / float( config.arena_size[0] ) ),
990 ( float( config.screen_size[1] - ( fixed_border*2 + bottom_border ) )
991 / float( config.arena_size[1] ) ) )
993 screen_border = ( float( config.screen_size[0] - config.arena_size[0]*scale )
994 / 2.0,
995 float( ( config.screen_size[1] - config.arena_size[1]*scale ) - ( bottom_border - fixed_border ) ) / 2.0 )
997 ceil_scale = math.ceil( scale )
999 # General initialisation
1001 num_joysticks = pygame.joystick.get_count()
1002 for j in range( num_joysticks ):
1003 pygame.joystick.Joystick( j ).init()
1005 intro_surface_title = mopelib.load_and_scale_image( "title.png", config )
1006 intro_surface_instr = mopelib.load_and_scale_image( "instructions.png", config )
1007 intro_surface_music = mopelib.load_and_scale_image( "music.png", config )
1009 ingame_surface_background = pygame.Surface( screen.get_size() ).convert()
1010 ingame_surface_background.fill( config.colour_background )
1012 intro_mode = INTRO_MODE_TITLE
1014 sound_mgr = TronCodeSoundManager( config.volume )
1016 troncode_version = mopelib.read_version( config )
1018 ingame_font = pygame.font.Font( None, int( config.screen_size[1] * 0.03 ) )
1020 menurender = mopelib.MenuRenderer( screen, config, ingame_surface_background,
1021 (128, 128, 128), (128, 255, 128), (128, 128, 128) )
1023 while True:
1024 sound_mgr.music_loud()
1025 intro_mainloop( config )
1026 sound_mgr.music_quiet()
1027 gamestate = ingame_mainloop( config )
1028 intro_mode = finishedgame_mainloop( config, gamestate )