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