Changed the default background colour to black.
[troncode.git] / troncode.py
blob7c1bd3643b8934a51fe0d4deffad59e01d358638
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_voldown = mopelib.MyInputEvent( "-" )
102 self.keys_voldown.add( pygame.KEYDOWN, ord( '-' ) )
103 self.keys_voldown.add( pygame.JOYBUTTONDOWN, 17 ) # GP2X volume - button
105 self.keys_p1_up = mopelib.MyInputEvent( "p1_up" )
106 self.keys_p1_up.add( pygame.KEYDOWN, pygame.K_UP )
107 self.keys_p1_up.add( pygame.JOYBUTTONDOWN, 0 ) # GP2X Joy up
109 self.keys_p1_right = mopelib.MyInputEvent( "p1_right" )
110 self.keys_p1_right.add( pygame.KEYDOWN, pygame.K_RIGHT )
111 self.keys_p1_right.add( pygame.JOYBUTTONDOWN, 6 ) # GP2X Joy right
113 self.keys_p1_down = mopelib.MyInputEvent( "p1_down" )
114 self.keys_p1_down.add( pygame.KEYDOWN, pygame.K_DOWN )
115 self.keys_p1_down.add( pygame.JOYBUTTONDOWN, 4 ) # GP2X Joy down
117 self.keys_p1_left = mopelib.MyInputEvent( "p1_left" )
118 self.keys_p1_left.add( pygame.KEYDOWN, pygame.K_LEFT )
119 self.keys_p1_left.add( pygame.JOYBUTTONDOWN, 4 ) # GP2X Joy left
121 self.keys_p2_up = mopelib.MyInputEvent( "p2_up" )
122 self.keys_p2_up.add( pygame.KEYDOWN, ord( '2' ) )
123 self.keys_p2_up.add( pygame.JOYBUTTONDOWN, 15 ) # GP2X Y button
125 self.keys_p2_right = mopelib.MyInputEvent( "p2_right" )
126 self.keys_p2_right.add( pygame.KEYDOWN, ord( 'e' ) )
127 self.keys_p2_right.add( pygame.JOYBUTTONDOWN, 13 ) # GP2X B button
129 self.keys_p2_down = mopelib.MyInputEvent( "p2_down" )
130 self.keys_p2_down.add( pygame.KEYDOWN, ord( 'w' ) )
131 self.keys_p2_down.add( pygame.JOYBUTTONDOWN, 14 ) # GP2X X button
133 self.keys_p2_left = mopelib.MyInputEvent( "p2_left" )
134 self.keys_p2_left.add( pygame.KEYDOWN, ord( 'q' ) )
135 self.keys_p2_left.add( pygame.JOYBUTTONDOWN, 12 ) # GP2X A button
137 self.keys_p3_up = mopelib.MyInputEvent( "p3_up" )
138 self.keys_p3_up.add( pygame.KEYDOWN, ord( 'i' ) )
140 self.keys_p3_right = mopelib.MyInputEvent( "p3_right" )
141 self.keys_p3_right.add( pygame.KEYDOWN, ord( 'l' ) )
143 self.keys_p3_down = mopelib.MyInputEvent( "p3_down" )
144 self.keys_p3_down.add( pygame.KEYDOWN, ord( 'k' ) )
146 self.keys_p3_left = mopelib.MyInputEvent( "p3_left" )
147 self.keys_p3_left.add( pygame.KEYDOWN, ord( 'j' ) )
149 self.keys_p4_up = mopelib.MyInputEvent( "p4_up" )
150 self.keys_p4_up.add( pygame.KEYDOWN, pygame.K_KP8 )
152 self.keys_p4_right = mopelib.MyInputEvent( "p4_right" )
153 self.keys_p4_right.add( pygame.KEYDOWN, pygame.K_KP6 )
155 self.keys_p4_down = mopelib.MyInputEvent( "p4_down" )
156 self.keys_p4_down.add( pygame.KEYDOWN, pygame.K_KP5 )
157 self.keys_p4_down.add( pygame.KEYDOWN, pygame.K_KP2 )
159 self.keys_p4_left = mopelib.MyInputEvent( "p4_left" )
160 self.keys_p4_left.add( pygame.KEYDOWN, pygame.K_KP4 )
163 # ----------------------
165 class TronCodeSoundManager( mopelib.SoundManager ):
167 def __init__( self, volume ):
168 mopelib.SoundManager.__init__( self, config )
170 #self.add_sample_group( "waddles", ["waddle1"] )
172 # ----------------------
174 def intro_draw_keys():
175 keys_colour = (0, 0, 0)
176 write_text( "Keys", keys_colour, 0.2, 0.05 )
177 write_text( "Slow down: %s" % config.keys_slow.name, keys_colour, 0.1, 0.25 )
178 write_text( "Speed up: %s" % config.keys_fast.name, keys_colour, 0.1, 0.35 )
179 #write_text( "Skip round: %s" % config.keys_skip, keys_colour, 0.1, 0.45 )
181 # ----------------------
183 def intro_draw_instructions():
184 write_text( "Press %s for menu, or %s to start" % (
185 config.keys_menu.name, config.keys_startgame.name ),
186 (0, 0, 0), 0.05, 0.99 )
188 # ----------------------
190 def general_menu_create_menu( menu, config, gamestate ):
191 menu.items = []
192 if gamestate == None: # We are on a title screen - Start Game option
193 menu.add_item( "Start game", MENU_START )
194 menu.add_item( "Number of players: %d" % (config.num_players),
195 MENU_NUM_PLAYERS )
196 for player_num in range( config.num_players ):
197 cls_name = "--unknown--"
198 if player_num < len( config.player_classes ):
199 cls_name = config.player_classes[player_num].GetName()
200 menu.add_item( "P%d: %s" % ( player_num, cls_name ),
201 MENU_CHANGE_PLAYER + player_num )
202 else:
203 menu.add_item( "Continue", MENU_START )
204 menu.add_item( "End game", MENU_END )
206 tmp_str = "Music: "
207 if config.music_on:
208 tmp_str += "on"
209 else:
210 tmp_str += "off"
211 menu.add_item( tmp_str, MENU_MUSIC )
213 tmp_str = "Effects: "
214 if config.sound_effects_on:
215 tmp_str += "on"
216 else:
217 tmp_str += "off"
218 menu.add_item( tmp_str, MENU_SOUND_EFFECTS )
220 menu.add_item( "Quit troncode", MENU_QUIT )
222 return menu
224 def general_menu_screen( config, gamestate ):
226 if gamestate == None:
227 menu_title = "troncode"
228 else:
229 menu_title = "troncode paused"
231 menu = mopelib.Menu()
232 general_menu_create_menu( menu, config, gamestate )
233 menurender.set_menu( menu, menu_title )
234 menurender.repaint_full()
236 game_start = False
238 waiting = True
239 while waiting:
240 event = pygame.event.wait()
241 if event.type == QUIT:
242 sys.exit(0)
243 elif config.keys_menu.matches( event ):
244 waiting = False
245 elif config.keys_down.matches( event ):
246 menurender.move_down()
247 elif config.keys_up.matches( event ):
248 menurender.move_up()
249 elif config.keys_return.matches( event ):
250 code = menu.get_selected_item().code
251 if code == MENU_START:
252 game_start = True
253 waiting = False
254 elif code == MENU_END:
255 gamestate.alive = INGAME_QUIT
256 waiting = False
257 elif code == MENU_MUSIC:
258 if config.music_on == 1:
259 config.music_on = 0
260 else:
261 config.music_on = 1
262 general_menu_create_menu( menu, config, gamestate )
263 menurender.repaint_full()
264 sound_mgr.setup( gamestate )
265 config.save()
266 elif code == MENU_SOUND_EFFECTS:
267 if config.sound_effects_on:
268 config.sound_effects_on = 0
269 else:
270 config.sound_effects_on = 1
271 general_menu_create_menu( menu, config, gamestate )
272 menurender.repaint_full()
273 sound_mgr.setup( gamestate )
274 config.save()
275 elif code == MENU_QUIT:
276 sys.exit(0)
278 return game_start
280 # ----------------------
282 def intro_draw_title():
283 screen.blit( intro_surface_title, (0,0) )
284 write_text( "Version " + troncode_version,
285 ( 0, 0, 0 ), 0.05, 0.88 )
286 write_text( "by Andy Balaam", ( 0, 0, 0 ), 0.06, 0.93 )
287 intro_draw_instructions()
289 def intro_draw_something( intro_mode ):
290 if intro_mode == INTRO_MODE_TITLE:
291 intro_draw_title()
292 elif intro_mode == INTRO_MODE_INSTR:
293 screen.blit( intro_surface_instr, (0,0) )
294 intro_draw_instructions()
295 elif intro_mode == INTRO_MODE_MUSIC:
296 screen.blit( intro_surface_music, (0,0) )
297 intro_draw_keys()
298 intro_draw_instructions()
299 pygame.display.update()
301 def intro_input( event, config, intro_mode ):
302 if event.type == QUIT:
303 sys.exit(0)
304 elif config.keys_volup.matches( event ):
305 config.volume = sound_mgr.increase_volume()
306 config.save()
307 elif config.keys_voldown.matches( event ):
308 config.volume = sound_mgr.decrease_volume()
309 config.save()
310 else:
311 if event.type == EVENTTYPE_TITLE_TICK:
312 intro_mode += 1
313 if intro_mode == INTRO_MODE_ENDED:
314 intro_mode = INTRO_MODE_TITLE
315 intro_draw_something( intro_mode )
316 elif config.keys_menu.matches( event ):
317 mopelib.clear_events( EVENTTYPE_TITLE_TICK )
318 start_game = general_menu_screen( config, None )
319 if start_game:
320 intro_mode = INTRO_MODE_ENDED
321 else:
322 intro_draw_something( intro_mode )
323 pygame.time.set_timer( EVENTTYPE_TITLE_TICK, TITLE_TICK_TIME )
324 elif config.keys_startgame.matches( event ):
325 intro_mode = INTRO_MODE_ENDED
326 return intro_mode
328 # ----------------------
330 def intro_mainloop( config ):
331 intro_draw_title()
333 pygame.display.update()
334 pygame.time.set_timer( EVENTTYPE_TITLE_TICK, TITLE_TICK_TIME )
336 intro_mode = INTRO_MODE_TITLE
337 while intro_mode < INTRO_MODE_ENDED:
338 intro_mode = intro_input( pygame.event.wait(), config, intro_mode )
340 mopelib.clear_events( EVENTTYPE_TITLE_TICK )
342 def draw_pixel( gamestate, surface, colour, x, y, alive_colours ):
343 if colour in alive_colours:
344 col = colour
345 else:
346 col = mopelib.dim_colour( colour, gamestate.dim )
347 adj_x = screen_border[0] + scale * x
348 adj_y = screen_border[1] + scale * y
349 if scale < 1:
350 surface.set_at( ( int(adj_x), int(adj_y) ), col )
351 else:
352 pygame.draw.rect( surface, col,
353 (adj_x, adj_y, ceil_scale, ceil_scale ) )
355 def inlevel_screen_blit( gamestate ):
356 screen.blit( gamestate.offscreen_buff, (0,0) )
357 pygame.display.update()
359 def inlevel_redraw_screen( gamestate, arrows, scores ):
360 alive_colours = []
361 if gamestate.alive == INGAME_MOST_DEAD:
362 for player in gamestate.players:
363 if not gamestate.statuses[player]._dead:
364 alive_colours.append( player.GetColour() )
366 gamestate.offscreen_buff = pygame.Surface( gamestate.config.screen_size )
367 gamestate.offscreen_buff.blit( ingame_surface_background, (0,0) )
368 for x, y, colour in gamestate.pixels_list:
369 draw_pixel( gamestate, gamestate.offscreen_buff, colour, x, y, alive_colours )
370 inlevel_draw_players( gamestate, alive_colours )
371 write_text_ingame( gamestate, scores )
372 # TODO: draw arrows
373 inlevel_screen_blit( gamestate )
375 def inlevel_draw_players( gamestate, alive_colours ):
376 for player in gamestate.players:
377 x, y = gamestate.GetPosition( player )
378 draw_pixel( gamestate, gamestate.offscreen_buff, player.GetColour(),
379 x, y, alive_colours )
381 def inlevel_update_screen( gamestate, scores ):
382 inlevel_draw_players( gamestate, [] )
383 inlevel_screen_blit( gamestate )
387 # ----------------------
389 def inlevel_input( event, gamestate, scores ):
390 if event.type == QUIT:
391 sys.exit(0)
392 elif config.keys_menu.matches( event ):
393 general_menu_screen( config, gamestate )
394 inlevel_redraw_screen( gamestate, False, scores )
395 elif config.keys_volup.matches( event ):
396 config.volume = sound_mgr.increase_volume()
397 config.save()
398 elif config.keys_voldown.matches( event ):
399 config.volume = sound_mgr.decrease_volume()
400 config.save()
401 elif config.keys_slow.matches( event ):
402 gamestate.framerate = 1
403 inlevel_redraw_screen( gamestate, False, scores )
404 elif config.keys_fast.matches( event ):
405 if gamestate.framerate == 1:
406 gamestate.framerate = 500
407 else:
408 gamestate.framerate *= 2
409 else:
410 gamestate.key_events.append( event )
413 # ----------------------
415 def finishedgame_input( event, waiting ):
416 if event.type == QUIT:
417 sys.exit(0)
418 elif config.keys_volup.matches( event ):
419 config.volume = sound_mgr.increase_volume()
420 config.save()
421 elif config.keys_voldown.matches( event ):
422 config.volume = sound_mgr.decrease_volume()
423 config.save()
424 elif config.keys_startgame.matches( event ):
425 waiting = False
426 return waiting
428 # ----------------------
430 class PlayerStatus:
431 def __init__( self, x, y, direction, player ):
432 self._x = x
433 self._y = y
434 self._dir = direction
435 self._colour = player.GetColour()
436 self._dead = False
438 def GetPosition( self ):
439 return ( self._x, self._y )
441 def GetDirection( self ):
442 return ( self._dir )
444 def SetDirection( self, direction ):
445 self._dir = direction
447 def SetDead( self, dead ):
448 self._dead = dead
450 def IsDead( self ):
451 return self._dead
453 def Move( self, gamestate ):
454 """Moves the player one position depending on its direction, and
455 returns True if it hit anything, False otherwise."""
457 if self._dead:
458 return self._dead
460 if self._dir == DIR_UP:
461 self._y -= 1
462 elif self._dir == DIR_RIGHT:
463 self._x += 1
464 elif self._dir == DIR_DOWN:
465 self._y += 1
466 elif self._dir == DIR_LEFT:
467 self._x -= 1
469 self._dead = gamestate.AddPixel( self._x, self._y, self._colour )
471 return self._dead
473 class GameBoard( AbstractGameBoard ):
474 def __init__( self, gamestate ):
475 self._gamestate = gamestate
477 def GetRelativePixel( self, start_pos, facing_dir,
478 offset_fwd, offset_right ):
479 """Given a position to stand in the arena, and a direction to face,
480 return the status (0 for empty, >0 for non-empty) of a pixel that
481 is offset_fwd pixels in front, and offset_right pixels to the right
482 (negative values may be used to go backwards or left respectively).
483 Pixels outside the arena also return >0."""
485 if facing_dir == DIR_UP:
486 found_pos = ( start_pos[0] + offset_right,
487 start_pos[1] - offset_fwd )
488 elif facing_dir == DIR_RIGHT:
489 found_pos = ( start_pos[0] + offset_fwd,
490 start_pos[1] + offset_right )
491 elif facing_dir == DIR_DOWN:
492 found_pos = ( start_pos[0] - offset_right,
493 start_pos[1] + offset_fwd )
494 elif facing_dir == DIR_LEFT:
495 found_pos = ( start_pos[0] - offset_fwd,
496 start_pos[1] - offset_right )
498 if ( found_pos[0] < 0 or
499 found_pos[0] >= self._gamestate.config.arena_size[0] or
500 found_pos[1] < 0 or
501 found_pos[1] >= self._gamestate.config.arena_size[1] ):
502 retval = 100
503 elif found_pos in self._gamestate.pixels_set:
504 retval = 1
505 else:
506 retval = 0
508 return retval
510 def GetPlayerPositions( self, pos_to_exclude = None ):
511 """Returns a list of pairs (pos, dir) for each player on screen.
512 Excludes the player at the position specified if pos_to_exclude
513 is not None."""
515 ret = []
517 for player in self._gamestate.statuses.keys():
518 status = self._gamestate.statuses[player]
519 if not status.IsDead():
520 pos = status.GetPosition()
521 if pos_to_exclude != pos:
522 ret.append( ( pos, status.GetDirection() ) )
524 return ret
526 def TurnRight( self, direction ):
527 """Return the direction found by turning 90 degrees right from
528 the supplied direction."""
529 direction += 1
530 if direction > DIR_LEFT:
531 direction = DIR_UP
532 return direction
534 def TurnLeft( self, direction ):
535 """Return the direction found by turning 90 degrees left from
536 the supplied direction."""
537 direction -= 1
538 if direction < DIR_UP:
539 direction = DIR_LEFT
540 return direction
542 def class_is_human( cls ):
543 return "IsHuman" in cls.__dict__ and cls.IsHuman()
545 class GameState:
546 def __init__( self, config, classes ):
547 self.config = config
549 self.players = []
550 self.key_events = []
551 self.any_humans = False
553 for cls in classes:
554 if class_is_human( cls ):
555 self.players.append( cls( config.keys_p1_up,
556 config.keys_p1_right, config.keys_p1_down,
557 config.keys_p1_left ) )
558 self.any_humans = True
559 else:
560 self.players.append( cls() )
562 self.alive = INGAME_TWO_ALIVE
563 self.dim = 1
565 self.pixels_list = []
566 self.pixels_set = set()
567 self.create_initial_pixels()
569 self.statuses = {}
570 for player in self.players:
571 x = random.randint( config.starting_border, config.arena_size[0]
572 - config.starting_border )
573 y = random.randint( config.starting_border, config.arena_size[1]
574 - config.starting_border )
575 dr = random.randint( DIR_UP, DIR_LEFT )
576 self.statuses[player] = PlayerStatus( x, y, dr, player )
577 self.AddPixel( x, y, player.GetColour() )
579 self._gameboard = GameBoard( self )
581 def timer_tick( self ):
582 num_alive = 0
583 for player in self.players:
584 status = self.statuses[player]
585 if not status.IsDead():
586 if class_is_human( player.__class__ ):
587 new_dir = player.GetDirWithInput( status.GetDirection(),
588 self.key_events )
589 else:
590 new_dir = player.GetDir( status.GetPosition(),
591 status.GetDirection(), self._gameboard )
592 if new_dir not in (DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT):
593 sys.stderr.write( "Player '" + player.GetName()
594 + "' returned an invalid value from GetDir(). Killing it.\n" )
595 new_dir = DIR_UP
596 status.SetDead( True )
598 status.SetDirection( new_dir )
599 # TODO: copy pixels list for "security"?
601 dead = self.statuses[player].Move( self )
602 if not dead:
603 num_alive += 1
605 if num_alive < 2:
606 self.alive = INGAME_MOST_DEAD
608 def create_initial_pixels( self ):
609 colour = (100, 100, 100)
610 size_x, size_y = config.arena_size
611 for x in range( size_x ):
612 self.AddPixel( x, 0, colour )
613 self.AddPixel( x, size_y - 1, colour )
614 for y in range( 1, size_y - 1 ):
615 self.AddPixel( 0, y, colour )
616 self.AddPixel( size_x - 1, y, colour )
618 def GetPosition( self, player ):
619 return self.statuses[player].GetPosition()
621 def AddPixel( self, x, y, colour ):
622 if ( x, y ) in self.pixels_set:
623 dead = True
624 else:
625 dead = False
626 self.pixels_set.add( ( x, y ) )
628 self.pixels_list.append( ( x, y, colour ) )
630 return dead
633 # ----------------------
635 def ingame_mainloop( config ):
637 scores = {}
638 for cls in config.player_classes:
639 scores[cls] = 0
641 while True:
642 gamestate = GameState( config, config.player_classes )
643 inlevel_mainloop( config, gamestate, scores )
644 if gamestate.alive == INGAME_QUIT:
645 break
647 return gamestate
649 def increment_scores( gamestate, scores ):
650 for player in gamestate.players:
651 if not gamestate.statuses[player]._dead:
652 scores[player.__class__] += 1
654 # ----------------------
656 def inlevel_mainloop( config, gamestate, scores ):
658 gamestate.alive = INGAME_TWO_ALIVE
660 inlevel_redraw_screen( gamestate, True, scores )
661 if gamestate.any_humans:
662 time.sleep( 1 )
663 inlevel_redraw_screen( gamestate, False, scores )
665 gc.disable()
666 tick_counter = 0
668 gamestate.framerate = 1
670 while gamestate.alive == INGAME_TWO_ALIVE:
671 for evt in pygame.event.get():
672 inlevel_input( evt, gamestate, scores )
673 gamestate.timer_tick()
674 gamestate.key_events = []
675 tick_counter += 1
676 if gamestate.alive != INGAME_MOST_DEAD:
677 if gamestate.framerate == 1:
678 inlevel_update_screen( gamestate, scores )
679 pygame.time.wait( config.tick_time )
680 elif tick_counter >= gamestate.framerate:
681 tick_counter = 0
682 inlevel_redraw_screen( gamestate, False, scores )
684 gc.enable()
685 mopelib.clear_events( EVENTTYPE_INGAME_TICK )
686 increment_scores( gamestate, scores )
688 finishedlevel_mainloop( gamestate, scores )
690 ingame_surface_background.fill( config.colour_background )
693 # ----------------------
695 def write_text( txt, colour, size, y_pos ):
696 ft = pygame.font.Font( None, int( config.screen_size[1] * size ) )
697 sf = ft.render( txt, True, colour )
698 screen.blit( sf, ( (config.screen_size[0] - sf.get_width() )/2,
699 (config.screen_size[1] - sf.get_height() ) * y_pos ) )
701 # ----------------------
703 def write_text_ingame( gamestate, scores ):
704 global ingame_font
706 txt = ""
707 for cls in scores.keys():
708 txt += "%s: %d " % ( cls.GetName(), scores[cls] )
710 colour = (128, 128, 128)
711 bgcolour = config.colour_background
712 y_pos = 0.996
713 sf = ingame_font.render( txt, True, colour )
714 sf_bg = pygame.Surface( ( int( sf.get_width() ), sf.get_height() ) )
715 sf_bg.fill( bgcolour )
717 tlx = ( config.screen_size[0] - sf_bg.get_width() ) / 2
718 tly = ( config.screen_size[1] - sf_bg.get_height() ) * y_pos
720 dirty_rect = Rect( tlx, tly, sf_bg.get_width(), sf_bg.get_height() )
721 gamestate.offscreen_buff.blit( sf_bg, dirty_rect )
722 gamestate.offscreen_buff.blit( sf, ( tlx * 1.01, tly ) )
724 # ----------------------
726 def finishedlevel_input( event, waiting, gamestate, scores ):
727 if event.type == QUIT:
728 sys.exit(0)
729 elif( ( event.type == pygame.ACTIVEEVENT and event.state == 2 )
730 or config.keys_menu.matches( event ) ):
731 general_menu_screen( config, gamestate )
732 inlevel_redraw_screen( gamestate, False, scores )
733 if gamestate.alive == INGAME_QUIT:
734 waiting = False
735 elif config.keys_volup.matches( event ):
736 config.volume = sound_mgr.increase_volume()
737 config.save()
738 elif config.keys_voldown.matches( event ):
739 config.volume = sound_mgr.decrease_volume()
740 config.save()
741 elif event.type == EVENTTYPE_TITLE_TICK:
742 waiting = False
743 elif config.keys_startgame.matches( event ):
744 waiting = False
745 return waiting
747 def finishedlevel_mainloop( gamestate, scores ):
748 gamestate.dim = 0.3
750 if not gamestate.any_humans:
751 pygame.time.set_timer( EVENTTYPE_TITLE_TICK, TITLE_TICK_TIME )
753 inlevel_redraw_screen( gamestate, False, scores )
754 waiting = True
755 while waiting:
756 waiting = finishedlevel_input( pygame.event.wait(), waiting, gamestate, scores )
758 if not gamestate.any_humans:
759 mopelib.clear_events( EVENTTYPE_TITLE_TICK )
761 def finishedgame_mainloop( config, gamestate ):
762 pass
763 #config.start_level = 0
764 # config.save()
766 # inlevel_redraw_screen( gamestate )
767 # write_text( "Congratulations!", (255,255,255), 0.125, 0.38 )
768 # write_text( "You won!", (255,255,255), 0.125, 0.52 )
769 # waiting = True
770 # write_text( "Press %s" % config.keys_startgame.name, (255,255,255),
771 # 0.05, 0.8 )
772 # pygame.display.update()
773 # while waiting:
774 # waiting = finishedgame_input( pygame.event.wait(), waiting )
776 # ingame_surface_background.fill( config.colour_background )
778 def sort_by_score( class2score ):
779 scorename_sorted = []
781 for cls in class2score.keys():
782 scorename_sorted.append( ( class2score[cls], cls.GetName() ) )
784 scorename_sorted.sort( reverse = True )
786 return scorename_sorted
788 def execute_tournament( config ):
789 total_scores = {}
791 classes = []
792 for cls in config.player_classes:
793 if not class_is_human( cls ):
794 classes.append( cls )
795 total_scores[cls] = 0
797 print
798 print " " * 30 + "=== Pairings ==="
799 print
801 pairs = []
802 num_classes = len( classes )
803 for i in range( num_classes ):
804 for j in range( i+1, num_classes ):
805 execute_match(
806 ( classes[i], classes[j] ),
807 total_scores, False )
809 print
810 print " " * 30 + "=== Medley ==="
811 print
813 execute_match( classes, total_scores, True )
815 print
816 print " " * 30 + "=== Total Scores ==="
817 print
819 scorename_sorted = sort_by_score( total_scores )
821 for score, name in scorename_sorted:
822 print "%30s % 4d" % ( name, score )
823 print
826 def execute_match( classes, total_scores, newlines ):
827 match_scores = {}
828 for cls in classes:
829 match_scores[cls] = 0
831 for i in range( config.num_games ):
832 gamestate = GameState( config, classes )
834 while gamestate.alive == INGAME_TWO_ALIVE:
835 gamestate.timer_tick()
837 for player in gamestate.statuses.keys():
838 status = gamestate.statuses[player]
839 if not status.IsDead():
840 match_scores[player.__class__] += 1
842 scorename_sorted = sort_by_score( match_scores )
844 oldscore = -1
845 for score, name in scorename_sorted:
846 if oldscore != -1 and not newlines:
847 if oldscore == score:
848 print " drew",
849 else:
850 print " beat",
851 print "%- 4d %-30s" % ( score, name ),
852 else:
853 print "%30s% 4d" % ( name, score ),
854 oldscore = score
857 if newlines:
858 print
860 if not newlines:
861 print
863 for cls in classes:
864 total_scores[cls] += match_scores[cls]
866 def get_players( players_dir ):
867 ret_classes = []
869 player_re = re.compile( """^(\w*Player).py$""" )
870 for filename in os.listdir( players_dir ):
871 m = player_re.match( filename )
872 if m:
873 class_name = m.group( 1 )
874 cls = __import__( "players." + class_name,
875 globals(), locals() ).__dict__[class_name].__dict__[class_name]
876 ret_classes.append( cls )
878 #return ret_classes[:2]
879 return ret_classes
881 # ----------------------
882 # Execution starts here
883 # ----------------------
885 # Fixed constants
887 INTRO_MODE_TITLE = 0
888 INTRO_MODE_INSTR = 1
889 INTRO_MODE_MUSIC = 2
890 INTRO_MODE_ENDED = 3
892 MENU_START = 0
893 MENU_NUM_PLAYERS = 1
894 MENU_END = 2
895 MENU_MUSIC = 3
896 MENU_SOUND_EFFECTS = 4
897 MENU_QUIT = 6
898 MENU_CHANGE_PLAYER = 100 # Must go at end of this list
900 INGAME_TWO_ALIVE = 0
901 INGAME_MOST_DEAD = 1
902 INGAME_QUIT = 2
904 TITLE_TICK_TIME = 4000
906 EVENTTYPE_INGAME_TICK = pygame.USEREVENT
907 EVENTTYPE_TITLE_TICK = pygame.USEREVENT + 1
909 num_args = len( sys.argv )
910 #if num_args > 1:
911 # if sys.argv[1] == "--help":
912 # print "Usage:"
913 # print "troncode.py [install_dir] [config_file] [resolution] "
914 # print " [num_players] [--tournament]"
915 # print
916 # print "e.g. ./troncode.py . troncoderc.txt '(640,480)' 2 --tournament"
917 # print
918 # sys.exit( 0 )
920 # install_dir = sys.argv[1]
921 #else:
922 # install_dir = "."
924 #if num_args > 2:
925 # config_filename = sys.argv[2]
926 #else:
927 # config_filename = os.path.expanduser( "~/.troncode/config" )
929 config_filename = os.path.expanduser( "~/.troncode/config" )
930 install_dir = "."
932 config = TronCodeConfig( config_filename )
934 if num_args > 1 and sys.argv[1] == "--tournament":
935 run_tournament = True
936 config.num_games = 100
937 else:
938 run_tournament = False
940 config.install_dir = install_dir
941 config.unsaved.append( "install_dir" )
943 config.images_dir = os.path.join( install_dir, "images" )
944 config.unsaved.append( "images_dir" )
946 config.music_dir = os.path.join( install_dir, "music" )
947 config.unsaved.append( "music_dir" )
949 if num_args > 3:
950 config.screen_size = config.parse_value( sys.argv[3] )
952 config.arena_size = ( 200, 200 )
953 config.unsaved.append( "arena_size" )
955 config.starting_border = 35
956 config.unsaved.append( "starting_border" )
958 config.players_dir = "players"
959 config.unsaved.append( "players_dir" )
961 config.player_classes = get_players( config.players_dir )
962 config.unsaved.append( "player_classes" )
964 config.players = []
965 config.unsaved.append( "players" )
967 if run_tournament:
968 execute_tournament( config )
969 else:
970 pygame.init()
971 pygame.font.init()
973 window = pygame.display.set_mode( config.screen_size )
974 pygame.display.set_caption( 'troncode' )
975 screen = pygame.display.get_surface()
977 fixed_border = 5
978 bottom_border = 25
979 scale = min(
980 ( float( config.screen_size[0] - fixed_border*2 )
981 / float( config.arena_size[0] ) ),
982 ( float( config.screen_size[1] - ( fixed_border*2 + bottom_border ) )
983 / float( config.arena_size[1] ) ) )
985 screen_border = ( float( config.screen_size[0] - config.arena_size[0]*scale )
986 / 2.0,
987 float( ( config.screen_size[1] - config.arena_size[1]*scale ) - ( bottom_border - fixed_border ) ) / 2.0 )
989 ceil_scale = math.ceil( scale )
991 # General initialisation
993 num_joysticks = pygame.joystick.get_count()
994 for j in range( num_joysticks ):
995 pygame.joystick.Joystick( j ).init()
997 intro_surface_title = mopelib.load_and_scale_image( "title.png", config )
998 intro_surface_instr = mopelib.load_and_scale_image( "instructions.png", config )
999 intro_surface_music = mopelib.load_and_scale_image( "music.png", config )
1001 ingame_surface_background = pygame.Surface( screen.get_size() ).convert()
1002 ingame_surface_background.fill( config.colour_background )
1004 intro_mode = INTRO_MODE_TITLE
1006 sound_mgr = TronCodeSoundManager( config.volume )
1008 troncode_version = mopelib.read_version( config )
1010 ingame_font = pygame.font.Font( None, int( config.screen_size[1] * 0.03 ) )
1012 menurender = mopelib.MenuRenderer( screen, config, ingame_surface_background,
1013 (128, 128, 128), (128, 255, 128), (128, 128, 128) )
1015 while True:
1016 sound_mgr.music_loud()
1017 intro_mainloop( config )
1018 sound_mgr.music_quiet()
1019 gamestate = ingame_mainloop( config )
1020 intro_mode = finishedgame_mainloop( config, gamestate )