- added geometry option which allows SuperTux to run at any resolution
[supertux.git] / src / worldmap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <iostream>
22 #include <fstream>
23 #include <vector>
24 #include <cassert>
25 #include <stdexcept>
26 #include <sstream>
27 #include <unistd.h>
28
29 #include "app/globals.h"
30 #include "app/gettext.h"
31 #include "app/setup.h"
32 #include "video/surface.h"
33 #include "video/screen.h"
34 #include "video/drawing_context.h"
35 #include "special/frame_rate.h"
36 #include "special/sprite_manager.h"
37 #include "audio/sound_manager.h"
38 #include "lisp/parser.h"
39 #include "lisp/lisp.h"
40 #include "lisp/list_iterator.h"
41 #include "lisp/writer.h"
42 #include "gameloop.h"
43 #include "sector.h"
44 #include "worldmap.h"
45 #include "resources.h"
46 #include "misc.h"
47 #include "player_status.h"
48 #include "textscroller.h"
49
50 #define map_message_TIME 2.8
51
52 Menu* worldmap_menu  = 0;
53
54 static const float TUXSPEED = 200;
55
56 namespace WorldMapNS {
57
58 Direction reverse_dir(Direction direction)
59 {
60   switch(direction)
61     {
62     case D_WEST:
63       return D_EAST;
64     case D_EAST:
65       return D_WEST;
66     case D_NORTH:
67       return D_SOUTH;
68     case D_SOUTH:
69       return D_NORTH;
70     case D_NONE:
71       return D_NONE;
72     }
73   return D_NONE;
74 }
75
76 std::string
77 direction_to_string(Direction direction)
78 {
79   switch(direction)
80     {
81     case D_WEST:
82       return "west";
83     case D_EAST:
84       return "east";
85     case D_NORTH:
86       return "north";
87     case D_SOUTH:
88       return "south";
89     default:
90       return "none";
91     }
92 }
93
94 Direction
95 string_to_direction(const std::string& directory)
96 {
97   if (directory == "west")
98     return D_WEST;
99   else if (directory == "east")
100     return D_EAST;
101   else if (directory == "north")
102     return D_NORTH;
103   else if (directory == "south")
104     return D_SOUTH;
105   else
106     return D_NONE;
107 }
108
109 //---------------------------------------------------------------------------
110
111 Tux::Tux(WorldMap* worldmap_)
112   : worldmap(worldmap_)
113 {
114   tux_sprite = sprite_manager->create("worldmaptux");
115   
116   offset = 0;
117   moving = false;
118   tile_pos.x = worldmap->get_start_x();
119   tile_pos.y = worldmap->get_start_y();
120   direction = D_NONE;
121   input_direction = D_NONE;
122 }
123
124 Tux::~Tux()
125 {
126   delete tux_sprite;
127 }
128
129 void
130 Tux::draw(DrawingContext& context)
131 {
132   switch (player_status.bonus) {
133     case GROWUP_BONUS:
134       tux_sprite->set_action("large");
135       break;
136     case FIRE_BONUS:
137       tux_sprite->set_action("fire");
138       break;
139     case NO_BONUS:
140       tux_sprite->set_action("small");
141       break;
142     default:
143 #ifdef DBEUG
144       std::cerr << "Bonus type not handled in worldmap.\n";
145 #endif
146       tux_sprite->set_action("large");
147       break;
148   }
149
150   tux_sprite->draw(context, get_pos(), LAYER_OBJECTS);
151 }
152
153
154 Vector
155 Tux::get_pos()
156 {
157   float x = tile_pos.x * 32;
158   float y = tile_pos.y * 32;
159
160   switch(direction)
161     {
162     case D_WEST:
163       x -= offset - 32;
164       break;
165     case D_EAST:
166       x += offset - 32;
167       break;
168     case D_NORTH:
169       y -= offset - 32;
170       break;
171     case D_SOUTH:
172       y += offset - 32;
173       break;
174     case D_NONE:
175       break;
176     }
177   
178   return Vector((int)x, (int)y); 
179 }
180
181 void
182 Tux::stop()
183 {
184   offset = 0;
185   direction = D_NONE;
186   input_direction = D_NONE;
187   moving = false;
188 }
189
190 void
191 Tux::set_direction(Direction dir)
192 {
193 input_direction = dir;
194 }
195
196 void
197 Tux::action(float delta)
198 {
199   if (!moving)
200     {
201       if (input_direction != D_NONE)
202         { 
203           WorldMap::Level* level = worldmap->at_level();
204
205           // We got a new direction, so lets start walking when possible
206           Vector next_tile;
207           if ((!level || level->solved)
208               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
209             {
210               tile_pos = next_tile;
211               moving = true;
212               direction = input_direction;
213               back_direction = reverse_dir(direction);
214             }
215           else if (input_direction == back_direction)
216             {
217               moving = true;
218               direction = input_direction;
219               tile_pos = worldmap->get_next_tile(tile_pos, direction);
220               back_direction = reverse_dir(direction);
221             }
222         }
223     }
224   else
225     {
226       // Let tux walk
227       offset += TUXSPEED * delta;
228
229       if (offset > 32)
230         { // We reached the next tile, so we check what to do now
231           offset -= 32;
232
233           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
234           if(special_tile && special_tile->passive_message)
235             {  // direction and the apply_action_ are opposites, since they "see"
236                // directions in a different way
237             if((direction == D_NORTH && special_tile->apply_action_south) ||
238                (direction == D_SOUTH && special_tile->apply_action_north) ||
239                (direction == D_WEST && special_tile->apply_action_east) ||
240                (direction == D_EAST && special_tile->apply_action_west))
241               {
242               worldmap->passive_message = special_tile->map_message;
243               worldmap->passive_message_timer.start(map_message_TIME);
244               }
245             }
246
247           if (worldmap->at(tile_pos)->getData() & Tile::WORLDMAP_STOP ||
248              (special_tile && !special_tile->passive_message) ||
249               worldmap->at_level())
250             {
251               if(special_tile && !special_tile->map_message.empty() &&
252                 !special_tile->passive_message)
253                 worldmap->passive_message_timer.start(0);
254               stop();
255             }
256           else
257             {
258               const Tile* tile = worldmap->at(tile_pos);
259               if (direction != input_direction)
260                 { 
261                   // Turn to a new direction
262                   const Tile* tile = worldmap->at(tile_pos);
263
264                   if((tile->getData() & Tile::WORLDMAP_NORTH 
265                       && input_direction == D_NORTH) ||
266                      (tile->getData() & Tile::WORLDMAP_SOUTH
267                       && input_direction == D_SOUTH) ||
268                      (tile->getData() & Tile::WORLDMAP_EAST
269                       && input_direction == D_EAST) ||
270                      (tile->getData() & Tile::WORLDMAP_WEST
271                       && input_direction == D_WEST))
272                     {  // player has changed direction during auto-movement
273                       direction = input_direction;
274                       back_direction = reverse_dir(direction);
275                     }
276                   else
277                     {  // player has changed to impossible tile
278                       back_direction = reverse_dir(direction);
279                       stop();
280                     }
281                 }
282               else
283                 {
284                 Direction dir = D_NONE;
285               
286                 if (tile->getData() & Tile::WORLDMAP_NORTH
287                     && back_direction != D_NORTH)
288                   dir = D_NORTH;
289                 else if (tile->getData() & Tile::WORLDMAP_SOUTH
290                     && back_direction != D_SOUTH)
291                   dir = D_SOUTH;
292                 else if (tile->getData() & Tile::WORLDMAP_EAST
293                     && back_direction != D_EAST)
294                   dir = D_EAST;
295                 else if (tile->getData() & Tile::WORLDMAP_WEST
296                     && back_direction != D_WEST)
297                   dir = D_WEST;
298
299                 if (dir != D_NONE)
300                   {
301                   direction = dir;
302                   input_direction = direction;
303                   back_direction = reverse_dir(direction);
304                   }
305                 else
306                   {
307                   // Should never be reached if tiledata is good
308                   stop();
309                   return;
310                   }
311                 }
312
313               // Walk automatically to the next tile
314               if(direction != D_NONE)
315                 {
316                 Vector next_tile;
317                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
318                   {
319                   tile_pos = next_tile;
320                   }
321                 else
322                   {
323                   puts("Tilemap data is buggy");
324                   stop();
325                   }
326                 }
327             }
328         }
329     }
330 }
331
332 //---------------------------------------------------------------------------
333
334 WorldMap::WorldMap()
335 {
336   tile_manager = new TileManager("images/worldmap/antarctica.stwt");
337   
338   width  = 20;
339   height = 15;
340   
341   start_x = 4;
342   start_y = 5;
343
344   tux = new Tux(this);
345   
346   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", true);
347   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", true);
348   messagedot   = new Surface(datadir +  "/images/worldmap/messagedot.png", true);
349   teleporterdot   = new Surface(datadir +  "/images/worldmap/teleporterdot.png", true);
350
351   enter_level = false;
352
353   name = "<no title>";
354   music = "salcon.mod";
355   intro_displayed = false;
356
357   total_stats.reset();
358 }
359
360 WorldMap::~WorldMap()
361 {
362   delete tux;
363   delete tile_manager;
364
365   delete leveldot_green;
366   delete leveldot_red;
367   delete messagedot;
368   delete teleporterdot;
369 }
370
371 // Don't forget to set map_filename before calling this
372 void
373 WorldMap::load_map()
374 {
375   levels_path = FileSystem::dirname(map_filename);
376
377   try {
378     lisp::Parser parser;
379     std::string filename = get_resource_filename(map_filename);
380     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
381
382     const lisp::Lisp* lisp = root->get_lisp("supertux-worldmap");
383     if(!lisp)
384       throw new std::runtime_error("file isn't a supertux-worldmap file.");
385
386     lisp::ListIterator iter(lisp);
387     while(iter.next()) {
388       if(iter.item() == "tilemap") {
389         if(tilemap.size() > 0)
390           throw new std::runtime_error("multiple tilemaps specified");
391         
392         const lisp::Lisp* tilemap_lisp = iter.lisp();
393         tilemap_lisp->get("width",  width);
394         tilemap_lisp->get("height", height);
395         tilemap_lisp->get_vector("data", tilemap);
396       } else if(iter.item() == "properties") {
397         const lisp::Lisp* props = iter.lisp();
398         props->get("name", name);
399         props->get("music", music);
400         props->get("intro-filename", intro_filename);
401         props->get("start_pos_x", start_x);
402         props->get("start_pos_y", start_y);
403       } else if(iter.item() == "special-tiles") {
404         parse_special_tiles(iter.lisp());
405       } else {
406         std::cerr << "Unknown token '" << iter.item() << "' in worldmap.\n";
407       }
408     }
409
410     delete tux;
411     tux = new Tux(this);
412   } catch(std::exception& e) {
413     std::stringstream msg;
414     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
415       e.what();
416     throw std::runtime_error(msg.str());
417   }
418 }
419
420 void
421 WorldMap::parse_special_tiles(const lisp::Lisp* lisp)
422 {
423   lisp::ListIterator iter(lisp);
424   while(iter.next()) {
425     if(iter.item() == "special-tile") {
426       SpecialTile special_tile;
427
428       const lisp::Lisp* lisp = iter.lisp();
429       lisp->get("x", special_tile.pos.x);
430       lisp->get("y", special_tile.pos.y);
431       lisp->get("map-message", special_tile.map_message);
432       special_tile.passive_message = false;
433       lisp->get("passive-message", special_tile.passive_message);
434       special_tile.teleport_dest = Vector(-1,-1);
435       lisp->get("teleport-to-x", special_tile.teleport_dest.x);
436       lisp->get("teleport-to-y", special_tile.teleport_dest.y);
437       special_tile.invisible = false;
438       lisp->get("invisible-tile", special_tile.invisible);
439
440       special_tile.apply_action_north = true;
441       special_tile.apply_action_south = true;
442       special_tile.apply_action_east = true;
443       special_tile.apply_action_west = true;
444
445       std::string apply_direction;
446       lisp->get("apply-to-direction", apply_direction);
447       if(!apply_direction.empty()) {
448         special_tile.apply_action_north = false;
449         special_tile.apply_action_south = false;
450         special_tile.apply_action_east = false;
451         special_tile.apply_action_west = false;
452         if(apply_direction.find("north") != std::string::npos)
453           special_tile.apply_action_north = true;
454         if(apply_direction.find("south") != std::string::npos)
455           special_tile.apply_action_south = true;
456         if(apply_direction.find("east") != std::string::npos)
457           special_tile.apply_action_east = true;
458         if(apply_direction.find("west") != std::string::npos)
459           special_tile.apply_action_west = true;
460       }
461       
462       special_tiles.push_back(special_tile);
463     } else if(iter.item() == "level") {
464       Level level;
465
466       lisp::Lisp* level_lisp = iter.lisp();
467       level.solved = false;
468                       
469       level.north = true;
470       level.east  = true;
471       level.south = true;
472       level.west  = true;
473
474       level_lisp->get("extro-filename", level.extro_filename);
475       level_lisp->get("next-worldmap", level.next_worldmap);
476
477       level.quit_worldmap = false;
478       level_lisp->get("quit-worldmap", level.quit_worldmap);
479
480       level_lisp->get("name", level.name);
481       level_lisp->get("x", level.pos.x);
482       level_lisp->get("y", level.pos.y);
483
484       level.auto_path = true;
485       level_lisp->get("auto-path", level.auto_path);
486
487       level.vertical_flip = false;
488       level_lisp->get("vertical-flip", level.vertical_flip);
489
490       levels.push_back(level);
491     } else {
492       std::cerr << "Unknown token '" << iter.item() <<
493         "' in worldmap special-tiles list.";
494     }
495   }
496 }
497
498 void
499 WorldMap::get_level_title(Level& level)
500 {
501   /** get special_tile's title */
502   level.title = "<no title>";
503
504   try {
505     lisp::Parser parser;
506     std::auto_ptr<lisp::Lisp> root (
507         parser.parse(get_resource_filename(levels_path + level.name)));
508
509     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
510     if(!level_lisp)
511       return;
512     
513     level_lisp->get("name", level.title);
514   } catch(std::exception& e) {
515     std::cerr << "Problem when reading leveltitle: " << e.what() << "\n";
516     return;
517   }
518 }
519
520 void WorldMap::calculate_total_stats()
521 {
522   total_stats.reset();
523   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
524     {
525     if (i->solved)
526       {
527       total_stats += i->statistics;
528       }
529     }
530 }
531
532 void
533 WorldMap::on_escape_press()
534 {
535   // Show or hide the menu
536   if(!Menu::current())
537     {
538     Menu::set_current(worldmap_menu); 
539     tux->set_direction(D_NONE);  // stop tux movement when menu is called
540     }
541   else
542     Menu::set_current(0); 
543 }
544
545 void
546 WorldMap::get_input()
547 {
548   enter_level = false;
549   SDLKey key;
550
551   SDL_Event event;
552   while (SDL_PollEvent(&event))
553     {
554       if (Menu::current())
555         {
556           Menu::current()->event(event);
557         }
558       else
559         {
560           switch(event.type)
561             {
562             case SDL_QUIT:
563               Termination::abort("Received window close", "");
564               break;
565           
566             case SDL_KEYDOWN:
567               key = event.key.keysym.sym;
568
569               if(key == SDLK_ESCAPE)
570                 on_escape_press();
571               else if(key == SDLK_RETURN || key == keymap.power)
572                 enter_level = true;
573               else if(key == SDLK_LEFT || key == keymap.power)
574                 tux->set_direction(D_WEST);
575               else if(key == SDLK_RIGHT || key == keymap.right)
576                 tux->set_direction(D_EAST);
577               else if(key == SDLK_UP || key == keymap.up ||
578                 key == keymap.jump)
579                   // there might be ppl that use jump as up key
580                 tux->set_direction(D_NORTH);
581               else if(key == SDLK_DOWN || key == keymap.down)
582                 tux->set_direction(D_SOUTH);
583               break;
584
585             case SDL_JOYHATMOTION:
586               if(event.jhat.value & SDL_HAT_UP) {
587                 tux->set_direction(D_NORTH);
588               } else if(event.jhat.value & SDL_HAT_DOWN) {
589                 tux->set_direction(D_SOUTH);
590               } else if(event.jhat.value & SDL_HAT_LEFT) {
591                 tux->set_direction(D_WEST);
592               } else if(event.jhat.value & SDL_HAT_RIGHT) {
593                 tux->set_direction(D_EAST);
594               }
595               break;
596           
597             case SDL_JOYAXISMOTION:
598               if (event.jaxis.axis == joystick_keymap.x_axis)
599                 {
600                   if (event.jaxis.value < -joystick_keymap.dead_zone)
601                     tux->set_direction(D_WEST);
602                   else if (event.jaxis.value > joystick_keymap.dead_zone)
603                     tux->set_direction(D_EAST);
604                 }
605               else if (event.jaxis.axis == joystick_keymap.y_axis)
606                 {
607                   if (event.jaxis.value > joystick_keymap.dead_zone)
608                     tux->set_direction(D_SOUTH);
609                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
610                     tux->set_direction(D_NORTH);
611                 }
612               break;
613
614             case SDL_JOYBUTTONDOWN:
615               if (event.jbutton.button == joystick_keymap.b_button)
616                 enter_level = true;
617               else if (event.jbutton.button == joystick_keymap.start_button)
618                 on_escape_press();
619               break;
620
621             default:
622               break;
623             }
624         }
625     }
626 }
627
628 Vector
629 WorldMap::get_next_tile(Vector pos, Direction direction)
630 {
631   switch(direction)
632     {
633     case D_WEST:
634       pos.x -= 1;
635       break;
636     case D_EAST:
637       pos.x += 1;
638       break;
639     case D_NORTH:
640       pos.y -= 1;
641       break;
642     case D_SOUTH:
643       pos.y += 1;
644       break;
645     case D_NONE:
646       break;
647     }
648   return pos;
649 }
650
651 bool
652 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
653 {
654   *new_pos = get_next_tile(old_pos, direction);
655
656   if (!(new_pos->x >= 0 && new_pos->x < width
657         && new_pos->y >= 0 && new_pos->y < height))
658     { // New position is outsite the tilemap
659       return false;
660     }
661   else
662     { // Check if the tile allows us to go to new_pos
663       switch(direction)
664         {
665         case D_WEST:
666           return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
667               && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
668
669         case D_EAST:
670           return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
671               && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
672
673         case D_NORTH:
674           return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
675               && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
676
677         case D_SOUTH:
678           return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
679               && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
680
681         case D_NONE:
682           assert(!"path_ok() can't work if direction is NONE");
683         }
684       return false;
685     }
686 }
687
688 void
689 WorldMap::update(float delta)
690 {
691   if (enter_level && !tux->is_moving())
692     {
693       /* Check special tile action */
694       SpecialTile* special_tile = at_special_tile();
695       if(special_tile)
696         {
697         if (special_tile->teleport_dest != Vector(-1,-1))
698           {
699           // TODO: an animation, camera scrolling or a fading would be a nice touch
700           SoundManager::get()->play_sound(IDToSound(SND_WARP));
701           tux->back_direction = D_NONE;
702           tux->set_tile_pos(special_tile->teleport_dest);
703           SDL_Delay(1000);
704           }
705         }
706
707       /* Check level action */
708       bool level_finished = true;
709       Level* level = at_level();
710       if (!level)
711         {
712         std::cout << "No level to enter at: "
713           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y
714           << std::endl;
715         return;
716         }
717
718
719       if (level->pos == tux->get_tile_pos())
720         {
721           PlayerStatus old_player_status = player_status;
722
723           std::cout << "Enter the current level: " << level->name << std::endl;
724           // do a shriking fade to the level
725           shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
726                              (level->pos.y*32 + 16 + offset.y)), 500);
727           GameSession session(get_resource_filename(levels_path + level->name),
728                               ST_GL_LOAD_LEVEL_FILE, &level->statistics);
729
730           switch (session.run())
731             {
732             case GameSession::ES_LEVEL_FINISHED:
733               {
734                 level_finished = true;
735                 bool old_level_state = level->solved;
736                 level->solved = true;
737
738                 // deal with statistics
739                 level->statistics.merge(global_stats);
740                 calculate_total_stats();
741
742                 if (old_level_state != level->solved && level->auto_path)
743                   { // Try to detect the next direction to which we should walk
744                     // FIXME: Mostly a hack
745                     Direction dir = D_NONE;
746                 
747                     const Tile* tile = at(tux->get_tile_pos());
748
749                     if (tile->getData() & Tile::WORLDMAP_NORTH
750                         && tux->back_direction != D_NORTH)
751                       dir = D_NORTH;
752                     else if (tile->getData() & Tile::WORLDMAP_SOUTH
753                         && tux->back_direction != D_SOUTH)
754                       dir = D_SOUTH;
755                     else if (tile->getData() & Tile::WORLDMAP_EAST
756                         && tux->back_direction != D_EAST)
757                       dir = D_EAST;
758                     else if (tile->getData() & Tile::WORLDMAP_WEST
759                         && tux->back_direction != D_WEST)
760                       dir = D_WEST;
761
762                     if (dir != D_NONE)
763                       {
764                         tux->set_direction(dir);
765                         //tux->update(delta);
766                       }
767
768                     std::cout << "Walk to dir: " << dir << std::endl;
769                   }
770               }
771
772               break;
773             case GameSession::ES_LEVEL_ABORT:
774               level_finished = false;
775               /* In case the player's abort the level, keep it using the old
776                   status. But the minimum lives and no bonus. */
777               player_status.distros = old_player_status.distros;
778               player_status.lives = std::min(old_player_status.lives, player_status.lives);
779               player_status.bonus = NO_BONUS;
780
781               break;
782             case GameSession::ES_GAME_OVER:
783               {
784               level_finished = false;
785               /* draw an end screen */
786               /* TODO: in the future, this should make a dialog a la SuperMario, asking
787               if the player wants to restart the world map with no score and from
788               level 1 */
789               char str[80];
790
791               DrawingContext context;
792               context.draw_gradient(Color (200,240,220), Color(200,200,220),
793                   LAYER_BACKGROUND0);
794
795               context.draw_text(blue_text, _("GAMEOVER"), 
796                   Vector(SCREEN_WIDTH/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
797
798               sprintf(str, _("COINS: %d"), player_status.distros);
799               context.draw_text(gold_text, str,
800                   Vector(SCREEN_WIDTH/2, SCREEN_WIDTH - 32), CENTER_ALLIGN,
801                   LAYER_FOREGROUND1);
802
803               total_stats.draw_message_info(context, _("Total Statistics"));
804
805               context.do_drawing();
806
807               SDL_Event event;
808               wait_for_event(event,2000,6000,true);
809
810               quit = true;
811               player_status.reset();
812               break;
813               }
814             case GameSession::ES_NONE:
815               assert(false);
816               // Should never be reached 
817               break;
818             }
819
820           SoundManager::get()->play_music(song);
821           Menu::set_current(0);
822           if (!savegame_file.empty())
823             savegame(savegame_file);
824         }
825       /* The porpose of the next checking is that if the player lost
826          the level (in case there is one), don't show anything */
827       if(level_finished) {
828         if (!level->extro_filename.empty()) {
829           // Display a text file
830           std::string filename = levels_path + level->extro_filename;
831           display_text_file(filename);
832         }
833
834         if (!level->next_worldmap.empty())
835           {
836           // Load given worldmap
837           loadmap(level->next_worldmap);
838           }
839         if (level->quit_worldmap)
840           quit = true;
841         }
842     }
843   else
844     {
845       tux->action(delta);
846 //      tux->set_direction(input_direction);
847     }
848   
849   Menu* menu = Menu::current();
850   if(menu)
851     {
852       menu->action();
853
854       if(menu == worldmap_menu)
855         {
856           switch (worldmap_menu->check())
857             {
858             case MNID_RETURNWORLDMAP: // Return to game
859               break;
860             case MNID_QUITWORLDMAP: // Quit Worldmap
861               quit = true;
862               break;
863             }
864         }
865       else if(menu == options_menu)
866         {
867           process_options_menu();
868         }
869     }
870 }
871
872 const Tile*
873 WorldMap::at(Vector p)
874 {
875   assert(p.x >= 0 
876          && p.x < width
877          && p.y >= 0
878          && p.y < height);
879
880   int x = int(p.x);
881   int y = int(p.y);
882   return tile_manager->get(tilemap[width * y + x]);
883 }
884
885 WorldMap::Level*
886 WorldMap::at_level()
887 {
888   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
889     {
890       if (i->pos == tux->get_tile_pos())
891         return &*i; 
892     }
893
894   return 0;
895 }
896
897 WorldMap::SpecialTile*
898 WorldMap::at_special_tile()
899 {
900   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
901     {
902       if (i->pos == tux->get_tile_pos())
903         return &*i; 
904     }
905
906   return 0;
907 }
908
909 void
910 WorldMap::draw(DrawingContext& context)
911 {
912   for(int y = 0; y < height; ++y)
913     for(int x = 0; x < width; ++x)
914       {
915         const Tile* tile = at(Vector(x, y));
916         tile->draw(context, Vector(x*32, y*32), LAYER_TILES);
917       }
918
919   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
920     {
921       if (i->solved)
922         context.draw_surface(leveldot_green,
923             Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
924       else
925         context.draw_surface(leveldot_red,
926             Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
927     }
928
929   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
930     {
931       if(i->invisible)
932         continue;
933
934       if (i->teleport_dest != Vector(-1, -1))
935         context.draw_surface(teleporterdot,
936                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
937
938       else if (!i->map_message.empty() && !i->passive_message)
939         context.draw_surface(messagedot,
940                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
941     }
942
943   tux->draw(context);
944   draw_status(context);
945 }
946
947 void
948 WorldMap::draw_status(DrawingContext& context)
949 {
950   context.push_transform();
951   context.set_translation(Vector(0, 0));
952   
953   char str[80];
954   sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
955
956   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
957   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
958
959   sprintf(str, "%d", player_status.distros);
960   context.draw_text(white_text, _("COINS"), Vector(SCREEN_WIDTH/2 - 16*5, 0),
961       LEFT_ALLIGN, LAYER_FOREGROUND1);
962   context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2 + (16*5)/2, 0),
963         LEFT_ALLIGN, LAYER_FOREGROUND1);
964
965   if (player_status.lives >= 5)
966     {
967       sprintf(str, "%dx", player_status.lives);
968       context.draw_text(gold_text, str, 
969           Vector(SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w, 0),
970           LEFT_ALLIGN, LAYER_FOREGROUND1);
971       context.draw_surface(tux_life, Vector(SCREEN_WIDTH -
972             gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
973     }
974   else
975     {
976       for(int i= 0; i < player_status.lives; ++i)
977         context.draw_surface(tux_life,
978             Vector(SCREEN_WIDTH - tux_life->w*4 + (tux_life->w*i), 0),
979             LAYER_FOREGROUND1);
980     }
981   context.draw_text(white_text, _("LIVES"),
982       Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
983       LEFT_ALLIGN, LAYER_FOREGROUND1);
984
985   if (!tux->is_moving())
986     {
987       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
988         {
989           if (i->pos == tux->get_tile_pos())
990             {
991               if(i->title == "")
992                 get_level_title(*i);
993
994               context.draw_text(white_text, i->title, 
995                   Vector(SCREEN_WIDTH/2,
996                          SCREEN_HEIGHT - white_text->get_height() - 30),
997                   CENTER_ALLIGN, LAYER_FOREGROUND1);
998
999               i->statistics.draw_worldmap_info(context);
1000               break;
1001             }
1002         }
1003       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1004         {
1005           if (i->pos == tux->get_tile_pos())
1006             {
1007                /* Display an in-map message in the map, if any as been selected */
1008               if(!i->map_message.empty() && !i->passive_message)
1009                 context.draw_text(gold_text, i->map_message, 
1010                     Vector(SCREEN_WIDTH/2,
1011                            SCREEN_HEIGHT - white_text->get_height() - 60),
1012                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1013               break;
1014             }
1015         }
1016     }
1017   /* Display a passive message in the map, if needed */
1018   if(passive_message_timer.check())
1019     context.draw_text(gold_text, passive_message, 
1020             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
1021             CENTER_ALLIGN, LAYER_FOREGROUND1);
1022
1023   context.pop_transform();
1024 }
1025
1026 void
1027 WorldMap::display()
1028 {
1029   Menu::set_current(0);
1030
1031   quit = false;
1032
1033   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1034   SoundManager::get()->play_music(song);
1035
1036   if(!intro_displayed && intro_filename != "") {
1037     std::string filename = levels_path + intro_filename;
1038     display_text_file(filename);
1039     intro_displayed = true;
1040   }
1041
1042   Uint32 lastticks = SDL_GetTicks();
1043   DrawingContext context;
1044   while(!quit) {
1045     Uint32 ticks = SDL_GetTicks();
1046     float elapsed_time = float(ticks - lastticks) / 1000;
1047     global_time += elapsed_time;
1048     lastticks = ticks;
1049     
1050     // 40 fps minimum
1051     if(elapsed_time > .025)
1052       elapsed_time = .025;
1053     
1054     Vector tux_pos = tux->get_pos();
1055     
1056     offset.x = -tux_pos.x + SCREEN_WIDTH/2;
1057     offset.y = -tux_pos.y + SCREEN_HEIGHT/2;
1058
1059     if (offset.x > 0) offset.x = 0;
1060     if (offset.y > 0) offset.y = 0;
1061
1062     if (offset.x < SCREEN_WIDTH - width*32) offset.x = SCREEN_WIDTH - width*32;
1063     if (offset.y < SCREEN_HEIGHT - height*32) offset.y = SCREEN_HEIGHT - height*32;
1064   
1065     context.push_transform();
1066     context.set_translation(-offset);
1067     draw(context);
1068     context.pop_transform();
1069     get_input();
1070     update(elapsed_time);
1071       
1072     if(Menu::current()) {
1073       Menu::current()->draw(context);
1074       mouse_cursor->draw(context);
1075     }
1076
1077     context.do_drawing();
1078   }
1079 }
1080
1081 void
1082 WorldMap::savegame(const std::string& filename)
1083 {
1084   if(filename == "")
1085     return;
1086
1087   std::ofstream file(filename.c_str(), std::ios::out);
1088   lisp::Writer writer(file);
1089
1090   int nb_solved_levels = 0, total_levels = 0;
1091   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
1092     ++total_levels;
1093     if (i->solved)
1094       ++nb_solved_levels;
1095   }
1096   char nb_solved_levels_str[80], total_levels_str[80];
1097   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1098   sprintf(total_levels_str, "%d", total_levels);
1099
1100   writer.write_comment("Worldmap save file");
1101
1102   writer.start_list("supertux-savegame");
1103
1104   writer.write_int("version", 1);
1105   writer.write_string("title",
1106       std::string(name + " - " + nb_solved_levels_str+"/"+total_levels_str));
1107   writer.write_string("map", map_filename);
1108   writer.write_bool("intro-displayed", intro_displayed);
1109
1110   writer.start_list("tux");
1111
1112   writer.write_float("x", tux->get_tile_pos().x);
1113   writer.write_float("y", tux->get_tile_pos().y);
1114   writer.write_string("back", direction_to_string(tux->back_direction));
1115   player_status.write(writer);
1116   writer.write_string("back", direction_to_string(tux->back_direction));
1117
1118   writer.end_list("tux");
1119
1120   writer.start_list("levels");
1121
1122   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1123     {
1124       if (i->solved)
1125         {
1126         writer.start_list("level");
1127
1128         writer.write_string("name", i->name);
1129         writer.write_bool("solved", true);
1130         i->statistics.write(writer);
1131
1132         writer.end_list("level");
1133         }
1134     }  
1135
1136   writer.end_list("levels");
1137
1138   writer.end_list("supertux-savegame");
1139 }
1140
1141 void
1142 WorldMap::loadgame(const std::string& filename)
1143 {
1144   std::cout << "loadgame: " << filename << std::endl;
1145   savegame_file = filename;
1146
1147   try {
1148     lisp::Parser parser;
1149     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
1150   
1151     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
1152     if(!savegame)
1153       throw std::runtime_error("File is not a supertux-savegame file.");
1154
1155     /* Get the Map filename and then load it before setting level settings */
1156     std::string cur_map_filename = map_filename;
1157     savegame->get("map", map_filename);
1158     load_map(); 
1159
1160     savegame->get("intro-displayed", intro_displayed);
1161     savegame->get("lives", player_status.lives);
1162     savegame->get("distros", player_status.distros);
1163     savegame->get("max-score-multiplier", player_status.max_score_multiplier);
1164     if (player_status.lives < 0)
1165       player_status.reset();
1166
1167     const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
1168     if(tux)
1169     {
1170       Vector p;
1171       std::string back_str = "none";
1172
1173       tux_lisp->get("x", p.x);
1174       tux_lisp->get("y", p.y);
1175       tux_lisp->get("back", back_str);
1176       player_status.read(*tux_lisp);
1177       
1178       tux->back_direction = string_to_direction(back_str);      
1179       tux->set_tile_pos(p);
1180     }
1181
1182     const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
1183     if(levels_lisp) {
1184       lisp::ListIterator iter(levels_lisp);
1185       while(iter.next()) {
1186         if(iter.item() == "level") {
1187           std::string name;
1188           bool solved = false;
1189
1190           const lisp::Lisp* level = iter.lisp();
1191           level->get("name", name);
1192           level->get("solved", solved);
1193
1194           for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1195           {
1196             if (name == i->name)
1197             {
1198               i->solved = solved;
1199               i->statistics.parse(*level);
1200               break;
1201             }
1202           }
1203         } else {
1204           std::cerr << "Unknown token '" << iter.item() 
1205             << "' in levels block in worldmap.\n";
1206         }
1207       }
1208     }
1209   } catch(std::exception& e) {
1210     std::cerr << "Problem loading game '" << filename << "': " << e.what() 
1211       << "\n";
1212     load_map();
1213     player_status.reset();
1214   }
1215
1216   calculate_total_stats();
1217 }
1218
1219 void
1220 WorldMap::loadmap(const std::string& filename)
1221 {
1222   savegame_file = "";
1223   map_filename = filename;
1224   load_map();
1225 }
1226
1227 } // namespace WorldMapNS