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