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,
27 from pygame
.locals import *
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
):
44 self
.screen_size
= ( 610, 635 )
45 self
.colour_background
= ( 0, 0, 0 )
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
):
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
),
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
)
203 menu
.add_item( "Continue", MENU_START
)
204 menu
.add_item( "End game", MENU_END
)
211 menu
.add_item( tmp_str
, MENU_MUSIC
)
213 tmp_str
= "Effects: "
214 if config
.sound_effects_on
:
218 menu
.add_item( tmp_str
, MENU_SOUND_EFFECTS
)
220 menu
.add_item( "Quit troncode", MENU_QUIT
)
224 def general_menu_screen( config
, gamestate
):
226 if gamestate
== None:
227 menu_title
= "troncode"
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()
240 event
= pygame
.event
.wait()
241 if event
.type == QUIT
:
243 elif config
.keys_menu
.matches( event
):
245 elif config
.keys_down
.matches( event
):
246 menurender
.move_down()
247 elif config
.keys_up
.matches( event
):
249 elif config
.keys_return
.matches( event
):
250 code
= menu
.get_selected_item().code
251 if code
== MENU_START
:
254 elif code
== MENU_END
:
255 gamestate
.alive
= INGAME_QUIT
257 elif code
== MENU_MUSIC
:
258 if config
.music_on
== 1:
262 general_menu_create_menu( menu
, config
, gamestate
)
263 menurender
.repaint_full()
264 sound_mgr
.setup( gamestate
)
266 elif code
== MENU_SOUND_EFFECTS
:
267 if config
.sound_effects_on
:
268 config
.sound_effects_on
= 0
270 config
.sound_effects_on
= 1
271 general_menu_create_menu( menu
, config
, gamestate
)
272 menurender
.repaint_full()
273 sound_mgr
.setup( gamestate
)
275 elif code
== MENU_QUIT
:
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
:
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) )
298 intro_draw_instructions()
299 pygame
.display
.update()
301 def intro_input( event
, config
, intro_mode
):
302 if event
.type == QUIT
:
304 elif config
.keys_volup
.matches( event
):
305 config
.volume
= sound_mgr
.increase_volume()
307 elif config
.keys_voldown
.matches( event
):
308 config
.volume
= sound_mgr
.decrease_volume()
311 if event
.type == EVENTTYPE_TITLE_TICK
:
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 )
320 intro_mode
= INTRO_MODE_ENDED
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
328 # ----------------------
330 def intro_mainloop( config
):
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
:
346 col
= mopelib
.dim_colour( colour
, gamestate
.dim
)
347 adj_x
= screen_border
[0] + scale
* x
348 adj_y
= screen_border
[1] + scale
* y
350 surface
.set_at( ( int(adj_x
), int(adj_y
) ), col
)
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
):
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
)
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
:
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()
398 elif config
.keys_voldown
.matches( event
):
399 config
.volume
= sound_mgr
.decrease_volume()
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
408 gamestate
.framerate
*= 2
410 gamestate
.key_events
.append( event
)
413 # ----------------------
415 def finishedgame_input( event
, waiting
):
416 if event
.type == QUIT
:
418 elif config
.keys_volup
.matches( event
):
419 config
.volume
= sound_mgr
.increase_volume()
421 elif config
.keys_voldown
.matches( event
):
422 config
.volume
= sound_mgr
.decrease_volume()
424 elif config
.keys_startgame
.matches( event
):
428 # ----------------------
431 def __init__( self
, x
, y
, direction
, player
):
434 self
._dir
= direction
435 self
._colour
= player
.GetColour()
438 def GetPosition( self
):
439 return ( self
._x
, self
._y
)
441 def GetDirection( self
):
444 def SetDirection( self
, direction
):
445 self
._dir
= direction
447 def SetDead( 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."""
460 if self
._dir
== DIR_UP
:
462 elif self
._dir
== DIR_RIGHT
:
464 elif self
._dir
== DIR_DOWN
:
466 elif self
._dir
== DIR_LEFT
:
469 self
._dead
= gamestate
.AddPixel( self
._x
, self
._y
, self
._colour
)
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
501 found_pos
[1] >= self
._gamestate
.config
.arena_size
[1] ):
503 elif found_pos
in self
._gamestate
.pixels_set
:
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
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() ) )
526 def TurnRight( self
, direction
):
527 """Return the direction found by turning 90 degrees right from
528 the supplied direction."""
530 if direction
> DIR_LEFT
:
534 def TurnLeft( self
, direction
):
535 """Return the direction found by turning 90 degrees left from
536 the supplied direction."""
538 if direction
< DIR_UP
:
542 def class_is_human( cls
):
543 return "IsHuman" in cls
.__dict
__ and cls
.IsHuman()
546 def __init__( self
, config
, classes
):
551 self
.any_humans
= False
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
560 self
.players
.append( cls() )
562 self
.alive
= INGAME_TWO_ALIVE
565 self
.pixels_list
= []
566 self
.pixels_set
= set()
567 self
.create_initial_pixels()
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
):
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(),
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" )
596 status
.SetDead( True )
598 status
.SetDirection( new_dir
)
599 # TODO: copy pixels list for "security"?
601 dead
= self
.statuses
[player
].Move( self
)
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
:
626 self
.pixels_set
.add( ( x
, y
) )
628 self
.pixels_list
.append( ( x
, y
, colour
) )
633 # ----------------------
635 def ingame_mainloop( config
):
638 for cls
in config
.player_classes
:
642 gamestate
= GameState( config
, config
.player_classes
)
643 inlevel_mainloop( config
, gamestate
, scores
)
644 if gamestate
.alive
== INGAME_QUIT
:
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
:
663 inlevel_redraw_screen( gamestate
, False, scores
)
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
= []
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
:
682 inlevel_redraw_screen( gamestate
, False, scores
)
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
):
707 for cls
in scores
.keys():
708 txt
+= "%s: %d " % ( cls
.GetName(), scores
[cls
] )
710 colour
= (128, 128, 128)
711 bgcolour
= config
.colour_background
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
:
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
:
735 elif config
.keys_volup
.matches( event
):
736 config
.volume
= sound_mgr
.increase_volume()
738 elif config
.keys_voldown
.matches( event
):
739 config
.volume
= sound_mgr
.decrease_volume()
741 elif event
.type == EVENTTYPE_TITLE_TICK
:
743 elif config
.keys_startgame
.matches( event
):
747 def finishedlevel_mainloop( gamestate
, scores
):
750 if not gamestate
.any_humans
:
751 pygame
.time
.set_timer( EVENTTYPE_TITLE_TICK
, TITLE_TICK_TIME
)
753 inlevel_redraw_screen( gamestate
, False, scores
)
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
):
763 #config.start_level = 0
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 )
770 # write_text( "Press %s" % config.keys_startgame.name, (255,255,255),
772 # pygame.display.update()
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
):
792 for cls
in config
.player_classes
:
793 if not class_is_human( cls
):
794 classes
.append( cls
)
795 total_scores
[cls
] = 0
798 print " " * 30 + "=== Pairings ==="
802 num_classes
= len( classes
)
803 for i
in range( num_classes
):
804 for j
in range( i
+1, num_classes
):
806 ( classes
[i
], classes
[j
] ),
807 total_scores
, False )
810 print " " * 30 + "=== Medley ==="
813 execute_match( classes
, total_scores
, True )
816 print " " * 30 + "=== Total Scores ==="
819 scorename_sorted
= sort_by_score( total_scores
)
821 for score
, name
in scorename_sorted
:
822 print "%30s % 4d" % ( name
, score
)
826 def execute_match( classes
, total_scores
, newlines
):
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
)
845 for score
, name
in scorename_sorted
:
846 if oldscore
!= -1 and not newlines
:
847 if oldscore
== score
:
851 print "%- 4d %-30s" % ( score
, name
),
853 print "%30s% 4d" % ( name
, score
),
864 total_scores
[cls
] += match_scores
[cls
]
866 def get_players( players_dir
):
869 player_re
= re
.compile( """^(\w*Player).py$""" )
870 for filename
in os
.listdir( players_dir
):
871 m
= player_re
.match( filename
)
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]
881 # ----------------------
882 # Execution starts here
883 # ----------------------
896 MENU_SOUND_EFFECTS
= 4
898 MENU_CHANGE_PLAYER
= 100 # Must go at end of this list
904 TITLE_TICK_TIME
= 4000
906 EVENTTYPE_INGAME_TICK
= pygame
.USEREVENT
907 EVENTTYPE_TITLE_TICK
= pygame
.USEREVENT
+ 1
909 num_args
= len( sys
.argv
)
911 # if sys.argv[1] == "--help":
913 # print "troncode.py [install_dir] [config_file] [resolution] "
914 # print " [num_players] [--tournament]"
916 # print "e.g. ./troncode.py . troncoderc.txt '(640,480)' 2 --tournament"
920 # install_dir = sys.argv[1]
925 # config_filename = sys.argv[2]
927 # config_filename = os.path.expanduser( "~/.troncode/config" )
929 config_filename
= os
.path
.expanduser( "~/.troncode/config" )
932 config
= TronCodeConfig( config_filename
)
934 if num_args
> 1 and sys
.argv
[1] == "--tournament":
935 run_tournament
= True
936 config
.num_games
= 100
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" )
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" )
965 config
.unsaved
.append( "players" )
968 execute_tournament( config
)
973 window
= pygame
.display
.set_mode( config
.screen_size
)
974 pygame
.display
.set_caption( 'troncode' )
975 screen
= pygame
.display
.get_surface()
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
)
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) )
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
)