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(),
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" )
603 status
.SetDead( True )
605 status
.SetDirection( new_dir
)
606 # TODO: copy pixels list for "security"?
608 dead
= self
.statuses
[player
].Move( self
)
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
:
633 self
.pixels_set
.add( ( x
, y
) )
635 self
.pixels_list
.append( ( x
, y
, colour
) )
640 # ----------------------
642 def ingame_mainloop( config
):
645 for cls
in config
.player_classes
:
649 gamestate
= GameState( config
, config
.player_classes
)
650 inlevel_mainloop( config
, gamestate
, scores
)
651 if gamestate
.alive
== INGAME_QUIT
:
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
:
670 inlevel_redraw_screen( gamestate
, False, scores
)
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
= []
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
:
690 inlevel_redraw_screen( gamestate
, False, scores
)
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
):
715 for cls
in scores
.keys():
716 txt
+= "%s: %d " % ( cls
.GetName(), scores
[cls
] )
718 colour
= (128, 128, 128)
719 bgcolour
= config
.colour_background
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
:
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
:
743 elif config
.keys_volup
.matches( event
):
744 config
.volume
= sound_mgr
.increase_volume()
746 elif config
.keys_voldown
.matches( event
):
747 config
.volume
= sound_mgr
.decrease_volume()
749 elif event
.type == EVENTTYPE_TITLE_TICK
:
751 elif config
.keys_startgame
.matches( event
):
755 def finishedlevel_mainloop( gamestate
, scores
):
758 if not gamestate
.any_humans
:
759 pygame
.time
.set_timer( EVENTTYPE_TITLE_TICK
, TITLE_TICK_TIME
)
761 inlevel_redraw_screen( gamestate
, False, scores
)
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
):
771 #config.start_level = 0
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 )
778 # write_text( "Press %s" % config.keys_startgame.name, (255,255,255),
780 # pygame.display.update()
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
):
800 for cls
in config
.player_classes
:
801 if not class_is_human( cls
):
802 classes
.append( cls
)
803 total_scores
[cls
] = 0
806 print " " * 30 + "=== Pairings ==="
810 num_classes
= len( classes
)
811 for i
in range( num_classes
):
812 for j
in range( i
+1, num_classes
):
814 ( classes
[i
], classes
[j
] ),
815 total_scores
, False )
818 print " " * 30 + "=== Medley ==="
821 execute_match( classes
, total_scores
, True )
824 print " " * 30 + "=== Total Scores ==="
827 scorename_sorted
= sort_by_score( total_scores
)
829 for score
, name
in scorename_sorted
:
830 print "%30s % 4d" % ( name
, score
)
834 def execute_match( classes
, total_scores
, newlines
):
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
)
853 for score
, name
in scorename_sorted
:
854 if oldscore
!= -1 and not newlines
:
855 if oldscore
== score
:
859 print "%- 4d %-30s" % ( score
, name
),
861 print "%30s% 4d" % ( name
, score
),
872 total_scores
[cls
] += match_scores
[cls
]
874 def get_players( players_dir
):
877 player_re
= re
.compile( """^(\w*Player).py$""" )
878 for filename
in os
.listdir( players_dir
):
879 m
= player_re
.match( filename
)
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]
889 # ----------------------
890 # Execution starts here
891 # ----------------------
904 MENU_SOUND_EFFECTS
= 4
906 MENU_CHANGE_PLAYER
= 100 # Must go at end of this list
912 TITLE_TICK_TIME
= 4000
914 EVENTTYPE_INGAME_TICK
= pygame
.USEREVENT
915 EVENTTYPE_TITLE_TICK
= pygame
.USEREVENT
+ 1
917 num_args
= len( sys
.argv
)
919 # if sys.argv[1] == "--help":
921 # print "troncode.py [install_dir] [config_file] [resolution] "
922 # print " [num_players] [--tournament]"
924 # print "e.g. ./troncode.py . troncoderc.txt '(640,480)' 2 --tournament"
928 # install_dir = sys.argv[1]
933 # config_filename = sys.argv[2]
935 # config_filename = os.path.expanduser( "~/.troncode/config" )
937 config_filename
= os
.path
.expanduser( "~/.troncode/config" )
940 config
= TronCodeConfig( config_filename
)
942 if num_args
> 1 and sys
.argv
[1] == "--tournament":
943 run_tournament
= True
944 config
.num_games
= 100
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" )
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" )
973 config
.unsaved
.append( "players" )
976 execute_tournament( config
)
981 window
= pygame
.display
.set_mode( config
.screen_size
)
982 pygame
.display
.set_caption( 'troncode' )
983 screen
= pygame
.display
.get_surface()
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
)
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) )
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
)