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_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
):
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
),
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
)
206 menu
.add_item( "Continue", MENU_START
)
207 menu
.add_item( "End game", MENU_END
)
214 menu
.add_item( tmp_str
, MENU_MUSIC
)
216 tmp_str
= "Effects: "
217 if config
.sound_effects_on
:
221 menu
.add_item( tmp_str
, MENU_SOUND_EFFECTS
)
223 menu
.add_item( "Quit troncode", MENU_QUIT
)
227 def general_menu_screen( config
, gamestate
):
229 if gamestate
== None:
230 menu_title
= "troncode"
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()
243 event
= pygame
.event
.wait()
244 if event
.type == QUIT
:
246 elif config
.keys_menu
.matches( event
):
248 elif config
.keys_down
.matches( event
):
249 menurender
.move_down()
250 elif config
.keys_up
.matches( event
):
252 elif config
.keys_return
.matches( event
):
253 code
= menu
.get_selected_item().code
254 if code
== MENU_START
:
257 elif code
== MENU_END
:
258 gamestate
.alive
= INGAME_QUIT
260 elif code
== MENU_MUSIC
:
261 if config
.music_on
== 1:
265 general_menu_create_menu( menu
, config
, gamestate
)
266 menurender
.repaint_full()
267 sound_mgr
.setup( gamestate
)
269 elif code
== MENU_SOUND_EFFECTS
:
270 if config
.sound_effects_on
:
271 config
.sound_effects_on
= 0
273 config
.sound_effects_on
= 1
274 general_menu_create_menu( menu
, config
, gamestate
)
275 menurender
.repaint_full()
276 sound_mgr
.setup( gamestate
)
278 elif code
== MENU_QUIT
:
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
:
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) )
301 intro_draw_instructions()
302 pygame
.display
.update()
304 def intro_input( event
, config
, intro_mode
):
305 if event
.type == QUIT
:
307 elif config
.keys_volup
.matches( event
):
308 config
.volume
= sound_mgr
.increase_volume()
310 elif config
.keys_voldown
.matches( event
):
311 config
.volume
= sound_mgr
.decrease_volume()
314 if event
.type == EVENTTYPE_TITLE_TICK
:
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 )
323 intro_mode
= INTRO_MODE_ENDED
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
331 # ----------------------
333 def intro_mainloop( config
):
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
:
349 col
= mopelib
.dim_colour( colour
, gamestate
.dim
)
350 adj_x
= screen_border
[0] + scale
* x
351 adj_y
= screen_border
[1] + scale
* y
353 surface
.set_at( ( int(adj_x
), int(adj_y
) ), col
)
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
):
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
)
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
:
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()
401 elif config
.keys_voldown
.matches( event
):
402 config
.volume
= sound_mgr
.decrease_volume()
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
413 gamestate
.framerate
*= 2
414 elif config
.keys_skip_to_end
.matches( event
):
415 gamestate
.framerate
= 1000000
417 gamestate
.key_events
.append( event
)
420 # ----------------------
422 def finishedgame_input( event
, waiting
):
423 if event
.type == QUIT
:
425 elif config
.keys_volup
.matches( event
):
426 config
.volume
= sound_mgr
.increase_volume()
428 elif config
.keys_voldown
.matches( event
):
429 config
.volume
= sound_mgr
.decrease_volume()
431 elif config
.keys_startgame
.matches( event
):
435 # ----------------------
438 def __init__( self
, x
, y
, direction
, player
):
441 self
._dir
= direction
442 self
._colour
= player
.GetColour()
445 def GetPosition( self
):
446 return ( self
._x
, self
._y
)
448 def GetDirection( self
):
451 def SetDirection( self
, direction
):
452 self
._dir
= direction
454 def SetDead( 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."""
467 if self
._dir
== DIR_UP
:
469 elif self
._dir
== DIR_RIGHT
:
471 elif self
._dir
== DIR_DOWN
:
473 elif self
._dir
== DIR_LEFT
:
476 self
._dead
= gamestate
.AddPixel( self
._x
, self
._y
, self
._colour
)
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
508 found_pos
[1] >= self
._gamestate
.config
.arena_size
[1] ):
510 elif found_pos
in self
._gamestate
.pixels_set
:
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
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() ) )
533 def TurnRight( self
, direction
):
534 """Return the direction found by turning 90 degrees right from
535 the supplied direction."""
537 if direction
> DIR_LEFT
:
541 def TurnLeft( self
, direction
):
542 """Return the direction found by turning 90 degrees left from
543 the supplied direction."""
545 if direction
< DIR_UP
:
549 def class_is_human( cls
):
550 return "IsHuman" in cls
.__dict
__ and cls
.IsHuman()
553 def __init__( self
, config
, classes
):
558 self
.any_humans
= False
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
567 self
.players
.append( cls() )
569 self
.alive
= INGAME_TWO_ALIVE
572 self
.pixels_list
= []
573 self
.pixels_set
= set()
574 self
.create_initial_pixels()
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
):
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(),
598 new_dir
= player
.GetDir( status
.GetPosition(),
599 status
.GetDirection(), self
._gameboard
)
601 sys
.stderr
.write( "Player '" + player
.GetName()
602 + "' threw an exception from GetDir(). Killing it.\n" )
604 status
.SetDead( True )
606 if new_dir
not in (DIR_UP
, DIR_RIGHT
, DIR_DOWN
, DIR_LEFT
):
607 sys
.stderr
.write( "Player '" + player
.GetName()
608 + "' returned an invalid value from GetDir(). Killing it.\n" )
610 status
.SetDead( True )
612 status
.SetDirection( new_dir
)
613 # TODO: copy pixels list for "security"?
615 dead
= self
.statuses
[player
].Move( self
)
620 self
.alive
= INGAME_MOST_DEAD
622 def create_initial_pixels( self
):
623 colour
= (100, 100, 100)
624 size_x
, size_y
= config
.arena_size
625 for x
in range( size_x
):
626 self
.AddPixel( x
, 0, colour
)
627 self
.AddPixel( x
, size_y
- 1, colour
)
628 for y
in range( 1, size_y
- 1 ):
629 self
.AddPixel( 0, y
, colour
)
630 self
.AddPixel( size_x
- 1, y
, colour
)
632 def GetPosition( self
, player
):
633 return self
.statuses
[player
].GetPosition()
635 def AddPixel( self
, x
, y
, colour
):
636 if ( x
, y
) in self
.pixels_set
:
640 self
.pixels_set
.add( ( x
, y
) )
642 self
.pixels_list
.append( ( x
, y
, colour
) )
647 # ----------------------
649 def ingame_mainloop( config
):
652 for cls
in config
.player_classes
:
656 gamestate
= GameState( config
, config
.player_classes
)
657 inlevel_mainloop( config
, gamestate
, scores
)
658 if gamestate
.alive
== INGAME_QUIT
:
663 def increment_scores( gamestate
, scores
):
664 for player
in gamestate
.players
:
665 if not gamestate
.statuses
[player
]._dead
:
666 scores
[player
.__class
__] += 1
668 # ----------------------
670 def inlevel_mainloop( config
, gamestate
, scores
):
672 gamestate
.alive
= INGAME_TWO_ALIVE
674 inlevel_redraw_screen( gamestate
, True, scores
)
675 if gamestate
.any_humans
:
677 inlevel_redraw_screen( gamestate
, False, scores
)
682 gamestate
.framerate
= 0
684 while gamestate
.alive
== INGAME_TWO_ALIVE
:
685 for evt
in pygame
.event
.get():
686 inlevel_input( evt
, gamestate
, scores
)
687 gamestate
.timer_tick()
688 gamestate
.key_events
= []
690 if gamestate
.alive
!= INGAME_MOST_DEAD
:
691 if gamestate
.framerate
<= 1:
692 inlevel_update_screen( gamestate
, scores
)
693 if gamestate
.framerate
== 0:
694 pygame
.time
.wait( config
.tick_time
)
695 elif tick_counter
>= gamestate
.framerate
:
697 inlevel_redraw_screen( gamestate
, False, scores
)
700 mopelib
.clear_events( EVENTTYPE_INGAME_TICK
)
701 increment_scores( gamestate
, scores
)
703 finishedlevel_mainloop( gamestate
, scores
)
705 ingame_surface_background
.fill( config
.colour_background
)
708 # ----------------------
710 def write_text( txt
, colour
, size
, y_pos
):
711 ft
= pygame
.font
.Font( None, int( config
.screen_size
[1] * size
) )
712 sf
= ft
.render( txt
, True, colour
)
713 screen
.blit( sf
, ( (config
.screen_size
[0] - sf
.get_width() )/2,
714 (config
.screen_size
[1] - sf
.get_height() ) * y_pos
) )
716 # ----------------------
718 def write_text_ingame( gamestate
, scores
):
722 for cls
in scores
.keys():
723 txt
+= "%s: %d " % ( cls
.GetName(), scores
[cls
] )
725 colour
= (128, 128, 128)
726 bgcolour
= config
.colour_background
728 sf
= ingame_font
.render( txt
, True, colour
)
729 sf_bg
= pygame
.Surface( ( int( sf
.get_width() ), sf
.get_height() ) )
730 sf_bg
.fill( bgcolour
)
732 tlx
= ( config
.screen_size
[0] - sf_bg
.get_width() ) / 2
733 tly
= ( config
.screen_size
[1] - sf_bg
.get_height() ) * y_pos
735 dirty_rect
= Rect( tlx
, tly
, sf_bg
.get_width(), sf_bg
.get_height() )
736 gamestate
.offscreen_buff
.blit( sf_bg
, dirty_rect
)
737 gamestate
.offscreen_buff
.blit( sf
, ( tlx
* 1.01, tly
) )
739 # ----------------------
741 def finishedlevel_input( event
, waiting
, gamestate
, scores
):
742 if event
.type == QUIT
:
744 elif( ( event
.type == pygame
.ACTIVEEVENT
and event
.state
== 2 )
745 or config
.keys_menu
.matches( event
) ):
746 general_menu_screen( config
, gamestate
)
747 inlevel_redraw_screen( gamestate
, False, scores
)
748 if gamestate
.alive
== INGAME_QUIT
:
750 elif config
.keys_volup
.matches( event
):
751 config
.volume
= sound_mgr
.increase_volume()
753 elif config
.keys_voldown
.matches( event
):
754 config
.volume
= sound_mgr
.decrease_volume()
756 elif event
.type == EVENTTYPE_TITLE_TICK
:
758 elif config
.keys_startgame
.matches( event
):
762 def finishedlevel_mainloop( gamestate
, scores
):
765 if not gamestate
.any_humans
:
766 pygame
.time
.set_timer( EVENTTYPE_TITLE_TICK
, TITLE_TICK_TIME
)
768 inlevel_redraw_screen( gamestate
, False, scores
)
771 waiting
= finishedlevel_input( pygame
.event
.wait(), waiting
, gamestate
, scores
)
773 if not gamestate
.any_humans
:
774 mopelib
.clear_events( EVENTTYPE_TITLE_TICK
)
776 def finishedgame_mainloop( config
, gamestate
):
778 #config.start_level = 0
781 # inlevel_redraw_screen( gamestate )
782 # write_text( "Congratulations!", (255,255,255), 0.125, 0.38 )
783 # write_text( "You won!", (255,255,255), 0.125, 0.52 )
785 # write_text( "Press %s" % config.keys_startgame.name, (255,255,255),
787 # pygame.display.update()
789 # waiting = finishedgame_input( pygame.event.wait(), waiting )
791 # ingame_surface_background.fill( config.colour_background )
793 def sort_by_score( class2score
):
794 scorename_sorted
= []
796 for cls
in class2score
.keys():
797 scorename_sorted
.append( ( class2score
[cls
], cls
.GetName() ) )
799 scorename_sorted
.sort( reverse
= True )
801 return scorename_sorted
803 def execute_tournament( config
):
807 for cls
in config
.player_classes
:
808 if not class_is_human( cls
):
809 classes
.append( cls
)
810 total_scores
[cls
] = 0
813 print " " * 30 + "=== Pairings ==="
817 num_classes
= len( classes
)
818 for i
in range( num_classes
):
819 for j
in range( i
+1, num_classes
):
821 ( classes
[i
], classes
[j
] ),
822 total_scores
, False, config
.num_games
)
825 print " " * 30 + u
"=== M\xeal\xe9e ==="
828 execute_match( classes
, total_scores
, True,
829 config
.num_games
* (len( classes
)-1) )
832 print " " * 30 + "=== Total Scores ==="
835 scorename_sorted
= sort_by_score( total_scores
)
837 for score
, name
in scorename_sorted
:
838 print "%30s % 4d" % ( name
, score
)
842 def execute_match( classes
, total_scores
, newlines
, num_games
):
845 match_scores
[cls
] = 0
849 for i
in range( num_games
):
851 sys
.stdout
.write( "." )
852 gamestate
= GameState( config
, classes
)
854 while gamestate
.alive
== INGAME_TWO_ALIVE
:
855 gamestate
.timer_tick()
857 for player
in gamestate
.statuses
.keys():
858 status
= gamestate
.statuses
[player
]
859 if not status
.IsDead():
860 match_scores
[player
.__class
__] += 1
865 scorename_sorted
= sort_by_score( match_scores
)
868 for score
, name
in scorename_sorted
:
869 if oldscore
!= -1 and not newlines
:
870 if oldscore
== score
:
874 print "%- 4d %-30s" % ( score
, name
),
876 print "%30s% 4d" % ( name
, score
),
887 total_scores
[cls
] += match_scores
[cls
]
889 def get_players( players_dir
):
892 player_re
= re
.compile( """^(\w*Player).py$""" )
893 for filename
in os
.listdir( players_dir
):
894 m
= player_re
.match( filename
)
896 class_name
= m
.group( 1 )
897 cls
= __import__( "players." + class_name
,
898 globals(), locals() ).__dict
__[class_name
].__dict
__[class_name
]
899 ret_classes
.append( cls
)
901 #return ret_classes[:2]
904 # ----------------------
905 # Execution starts here
906 # ----------------------
919 MENU_SOUND_EFFECTS
= 4
921 MENU_CHANGE_PLAYER
= 100 # Must go at end of this list
927 TITLE_TICK_TIME
= 4000
929 EVENTTYPE_INGAME_TICK
= pygame
.USEREVENT
930 EVENTTYPE_TITLE_TICK
= pygame
.USEREVENT
+ 1
932 num_args
= len( sys
.argv
)
934 # if sys.argv[1] == "--help":
936 # print "troncode.py [install_dir] [config_file] [resolution] "
937 # print " [num_players] [--tournament]"
939 # print "e.g. ./troncode.py . troncoderc.txt '(640,480)' 2 --tournament"
943 # install_dir = sys.argv[1]
948 # config_filename = sys.argv[2]
950 # config_filename = os.path.expanduser( "~/.troncode/config" )
952 config_filename
= os
.path
.expanduser( "~/.troncode/config" )
955 config
= TronCodeConfig( config_filename
)
957 if num_args
> 1 and sys
.argv
[1] == "--tournament":
958 run_tournament
= True
959 config
.num_games
= 100
961 run_tournament
= False
963 config
.install_dir
= install_dir
964 config
.unsaved
.append( "install_dir" )
966 config
.images_dir
= os
.path
.join( install_dir
, "images" )
967 config
.unsaved
.append( "images_dir" )
969 config
.music_dir
= os
.path
.join( install_dir
, "music" )
970 config
.unsaved
.append( "music_dir" )
973 config
.screen_size
= config
.parse_value( sys
.argv
[3] )
975 config
.arena_size
= ( 200, 200 )
976 config
.unsaved
.append( "arena_size" )
978 config
.starting_border
= 35
979 config
.unsaved
.append( "starting_border" )
981 config
.players_dir
= "players"
982 config
.unsaved
.append( "players_dir" )
984 config
.player_classes
= get_players( config
.players_dir
)
985 config
.unsaved
.append( "player_classes" )
988 config
.unsaved
.append( "players" )
991 execute_tournament( config
)
996 window
= pygame
.display
.set_mode( config
.screen_size
)
997 pygame
.display
.set_caption( 'troncode' )
998 screen
= pygame
.display
.get_surface()
1003 ( float( config
.screen_size
[0] - fixed_border
*2 )
1004 / float( config
.arena_size
[0] ) ),
1005 ( float( config
.screen_size
[1] - ( fixed_border
*2 + bottom_border
) )
1006 / float( config
.arena_size
[1] ) ) )
1008 screen_border
= ( float( config
.screen_size
[0] - config
.arena_size
[0]*scale
)
1010 float( ( config
.screen_size
[1] - config
.arena_size
[1]*scale
) - ( bottom_border
- fixed_border
) ) / 2.0 )
1012 ceil_scale
= math
.ceil( scale
)
1014 # General initialisation
1016 num_joysticks
= pygame
.joystick
.get_count()
1017 for j
in range( num_joysticks
):
1018 pygame
.joystick
.Joystick( j
).init()
1020 intro_surface_title
= mopelib
.load_and_scale_image( "title.png", config
)
1021 intro_surface_instr
= mopelib
.load_and_scale_image( "instructions.png", config
)
1022 intro_surface_music
= mopelib
.load_and_scale_image( "music.png", config
)
1024 ingame_surface_background
= pygame
.Surface( screen
.get_size() ).convert()
1025 ingame_surface_background
.fill( config
.colour_background
)
1027 intro_mode
= INTRO_MODE_TITLE
1029 sound_mgr
= TronCodeSoundManager( config
.volume
)
1031 troncode_version
= mopelib
.read_version( config
)
1033 ingame_font
= pygame
.font
.Font( None, int( config
.screen_size
[1] * 0.03 ) )
1035 menurender
= mopelib
.MenuRenderer( screen
, config
, ingame_surface_background
,
1036 (128, 128, 128), (128, 255, 128), (128, 128, 128) )
1039 sound_mgr
.music_loud()
1040 intro_mainloop( config
)
1041 sound_mgr
.music_quiet()
1042 gamestate
= ingame_mainloop( config
)
1043 intro_mode
= finishedgame_mainloop( config
, gamestate
)