-Some cleanups in text scrolling code
[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 "audio/sound_manager.h"
37 #include "lisp/parser.h"
38 #include "lisp/lisp.h"
39 #include "lisp/list_iterator.h"
40 #include "lisp/writer.h"
41 #include "gameloop.h"
42 #include "sector.h"
43 #include "worldmap.h"
44 #include "resources.h"
45 #include "misc.h"
46 #include "player_status.h"
47 #include "textscroller.h"
48
49 #define map_message_TIME 2.8
50
51 Menu* worldmap_menu  = 0;
52
53 static const float TUXSPEED = 200;
54
55 namespace WorldMapNS {
56
57 Direction reverse_dir(Direction direction)
58 {
59   switch(direction)
60     {
61     case D_WEST:
62       return D_EAST;
63     case D_EAST:
64       return D_WEST;
65     case D_NORTH:
66       return D_SOUTH;
67     case D_SOUTH:
68       return D_NORTH;
69     case D_NONE:
70       return D_NONE;
71     }
72   return D_NONE;
73 }
74
75 std::string
76 direction_to_string(Direction direction)
77 {
78   switch(direction)
79     {
80     case D_WEST:
81       return "west";
82     case D_EAST:
83       return "east";
84     case D_NORTH:
85       return "north";
86     case D_SOUTH:
87       return "south";
88     default:
89       return "none";
90     }
91 }
92
93 Direction
94 string_to_direction(const std::string& directory)
95 {
96   if (directory == "west")
97     return D_WEST;
98   else if (directory == "east")
99     return D_EAST;
100   else if (directory == "north")
101     return D_NORTH;
102   else if (directory == "south")
103     return D_SOUTH;
104   else
105     return D_NONE;
106 }
107
108 //---------------------------------------------------------------------------
109
110 Tux::Tux(WorldMap* worldmap_)
111   : worldmap(worldmap_)
112 {
113   largetux_sprite = new Surface(datadir +  "/images/worldmap/tux.png", true);
114   firetux_sprite = new Surface(datadir +  "/images/worldmap/firetux.png", true);
115   smalltux_sprite = new Surface(datadir +  "/images/worldmap/smalltux.png", true);
116
117   offset = 0;
118   moving = false;
119   tile_pos.x = worldmap->get_start_x();
120   tile_pos.y = worldmap->get_start_y();
121   direction = D_NONE;
122   input_direction = D_NONE;
123 }
124
125 Tux::~Tux()
126 {
127   delete smalltux_sprite;
128   delete firetux_sprite;
129   delete largetux_sprite;
130 }
131
132 void
133 Tux::draw(DrawingContext& context, const Vector& offset)
134 {
135   Vector pos = get_pos();
136   switch (player_status.bonus)
137     {
138     case PlayerStatus::GROWUP_BONUS:
139       context.draw_surface(largetux_sprite,
140           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
141       break;
142     case PlayerStatus::FLOWER_BONUS:
143       context.draw_surface(firetux_sprite,
144           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
145       break;
146     case PlayerStatus::NO_BONUS:
147       context.draw_surface(smalltux_sprite,
148           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
149       break;
150     }
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 (session.get_current_sector()->player->got_power !=
743                       session.get_current_sector()->player->NONE_POWER)
744                   player_status.bonus = PlayerStatus::FLOWER_BONUS;
745                 else if (session.get_current_sector()->player->size == BIG)
746                   player_status.bonus = PlayerStatus::GROWUP_BONUS;
747                 else
748                   player_status.bonus = PlayerStatus::NO_BONUS;
749
750                 if (old_level_state != level->solved && level->auto_path)
751                   { // Try to detect the next direction to which we should walk
752                     // FIXME: Mostly a hack
753                     Direction dir = D_NONE;
754                 
755                     const Tile* tile = at(tux->get_tile_pos());
756
757                     if (tile->getData() & Tile::WORLDMAP_NORTH
758                         && tux->back_direction != D_NORTH)
759                       dir = D_NORTH;
760                     else if (tile->getData() & Tile::WORLDMAP_SOUTH
761                         && tux->back_direction != D_SOUTH)
762                       dir = D_SOUTH;
763                     else if (tile->getData() & Tile::WORLDMAP_EAST
764                         && tux->back_direction != D_EAST)
765                       dir = D_EAST;
766                     else if (tile->getData() & Tile::WORLDMAP_WEST
767                         && tux->back_direction != D_WEST)
768                       dir = D_WEST;
769
770                     if (dir != D_NONE)
771                       {
772                         tux->set_direction(dir);
773                         //tux->update(delta);
774                       }
775
776                     std::cout << "Walk to dir: " << dir << std::endl;
777                   }
778               }
779
780               break;
781             case GameSession::ES_LEVEL_ABORT:
782               level_finished = false;
783               /* In case the player's abort the level, keep it using the old
784                   status. But the minimum lives and no bonus. */
785               player_status.distros = old_player_status.distros;
786               player_status.lives = std::min(old_player_status.lives, player_status.lives);
787               player_status.bonus = player_status.NO_BONUS;
788
789               break;
790             case GameSession::ES_GAME_OVER:
791               {
792               level_finished = false;
793               /* draw an end screen */
794               /* TODO: in the future, this should make a dialog a la SuperMario, asking
795               if the player wants to restart the world map with no score and from
796               level 1 */
797               char str[80];
798
799               DrawingContext context;
800               context.draw_gradient(Color (200,240,220), Color(200,200,220),
801                   LAYER_BACKGROUND0);
802
803               context.draw_text(blue_text, _("GAMEOVER"), 
804                   Vector(screen->w/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
805
806               sprintf(str, _("COINS: %d"), player_status.distros);
807               context.draw_text(gold_text, str,
808                   Vector(screen->w/2, screen->w - 32), CENTER_ALLIGN,
809                   LAYER_FOREGROUND1);
810
811               total_stats.draw_message_info(context, _("Total Statistics"));
812
813               context.do_drawing();
814
815               SDL_Event event;
816               wait_for_event(event,2000,6000,true);
817
818               quit = true;
819               player_status.reset();
820               break;
821               }
822             case GameSession::ES_NONE:
823               assert(false);
824               // Should never be reached 
825               break;
826             }
827
828           SoundManager::get()->play_music(song);
829           Menu::set_current(0);
830           if (!savegame_file.empty())
831             savegame(savegame_file);
832         }
833       /* The porpose of the next checking is that if the player lost
834          the level (in case there is one), don't show anything */
835       if(level_finished) {
836         if (!level->extro_filename.empty()) {
837           // Display a text file
838           std::string filename = levels_path + level->extro_filename;
839           display_text_file(filename);
840         }
841
842         if (!level->next_worldmap.empty())
843           {
844           // Load given worldmap
845           loadmap(level->next_worldmap);
846           }
847         if (level->quit_worldmap)
848           quit = true;
849         }
850     }
851   else
852     {
853       tux->action(delta);
854 //      tux->set_direction(input_direction);
855     }
856   
857   Menu* menu = Menu::current();
858   if(menu)
859     {
860       menu->action();
861
862       if(menu == worldmap_menu)
863         {
864           switch (worldmap_menu->check())
865             {
866             case MNID_RETURNWORLDMAP: // Return to game
867               break;
868             case MNID_QUITWORLDMAP: // Quit Worldmap
869               quit = true;
870               break;
871             }
872         }
873       else if(menu == options_menu)
874         {
875           process_options_menu();
876         }
877     }
878 }
879
880 const Tile*
881 WorldMap::at(Vector p)
882 {
883   assert(p.x >= 0 
884          && p.x < width
885          && p.y >= 0
886          && p.y < height);
887
888   int x = int(p.x);
889   int y = int(p.y);
890   return tile_manager->get(tilemap[width * y + x]);
891 }
892
893 WorldMap::Level*
894 WorldMap::at_level()
895 {
896   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
897     {
898       if (i->pos == tux->get_tile_pos())
899         return &*i; 
900     }
901
902   return 0;
903 }
904
905 WorldMap::SpecialTile*
906 WorldMap::at_special_tile()
907 {
908   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
909     {
910       if (i->pos == tux->get_tile_pos())
911         return &*i; 
912     }
913
914   return 0;
915 }
916
917
918 void
919 WorldMap::draw(DrawingContext& context, const Vector& offset)
920 {
921   for(int y = 0; y < height; ++y)
922     for(int x = 0; x < width; ++x)
923       {
924         const Tile* tile = at(Vector(x, y));
925         tile->draw(context, Vector(x*32 + offset.x, y*32 + offset.y),
926             LAYER_TILES);
927       }
928
929   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
930     {
931       if (i->solved)
932         context.draw_surface(leveldot_green,
933             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
934       else
935         context.draw_surface(leveldot_red,
936             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
937     }
938
939   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
940     {
941       if(i->invisible)
942         continue;
943
944       if (i->teleport_dest != Vector(-1, -1))
945         context.draw_surface(teleporterdot,
946                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
947
948       else if (!i->map_message.empty() && !i->passive_message)
949         context.draw_surface(messagedot,
950                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
951     }
952
953   tux->draw(context, offset);
954   draw_status(context);
955 }
956
957 void
958 WorldMap::draw_status(DrawingContext& context)
959 {
960   char str[80];
961   sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
962
963   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
964   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
965
966   sprintf(str, "%d", player_status.distros);
967   context.draw_text(white_text, _("COINS"), Vector(screen->w/2 - 16*5, 0),
968       LEFT_ALLIGN, LAYER_FOREGROUND1);
969   context.draw_text(gold_text, str, Vector(screen->w/2 + (16*5)/2, 0),
970         LEFT_ALLIGN, LAYER_FOREGROUND1);
971
972   if (player_status.lives >= 5)
973     {
974       sprintf(str, "%dx", player_status.lives);
975       context.draw_text(gold_text, str, 
976           Vector(screen->w - gold_text->get_text_width(str) - tux_life->w, 0),
977           LEFT_ALLIGN, LAYER_FOREGROUND1);
978       context.draw_surface(tux_life, Vector(screen->w -
979             gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
980     }
981   else
982     {
983       for(int i= 0; i < player_status.lives; ++i)
984         context.draw_surface(tux_life,
985             Vector(screen->w - tux_life->w*4 + (tux_life->w*i), 0),
986             LAYER_FOREGROUND1);
987     }
988   context.draw_text(white_text, _("LIVES"),
989       Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
990       LEFT_ALLIGN, LAYER_FOREGROUND1);
991
992   if (!tux->is_moving())
993     {
994       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
995         {
996           if (i->pos == tux->get_tile_pos())
997             {
998               if(i->title == "")
999                 get_level_title(*i);
1000
1001               context.draw_text(white_text, i->title, 
1002                   Vector(screen->w/2,
1003                          screen->h - white_text->get_height() - 30),
1004                   CENTER_ALLIGN, LAYER_FOREGROUND1);
1005
1006               i->statistics.draw_worldmap_info(context);
1007               break;
1008             }
1009         }
1010       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1011         {
1012           if (i->pos == tux->get_tile_pos())
1013             {
1014                /* Display an in-map message in the map, if any as been selected */
1015               if(!i->map_message.empty() && !i->passive_message)
1016                 context.draw_text(gold_text, i->map_message, 
1017                     Vector(screen->w/2,
1018                            screen->h - white_text->get_height() - 60),
1019                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1020               break;
1021             }
1022         }
1023     }
1024   /* Display a passive message in the map, if needed */
1025   if(passive_message_timer.check())
1026     context.draw_text(gold_text, passive_message, 
1027             Vector(screen->w/2, screen->h - white_text->get_height() - 60),
1028             CENTER_ALLIGN, LAYER_FOREGROUND1);
1029 }
1030
1031 void
1032 WorldMap::display()
1033 {
1034   Menu::set_current(0);
1035
1036   quit = false;
1037
1038   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1039   SoundManager::get()->play_music(song);
1040
1041   if(!intro_displayed && intro_filename != "") {
1042     std::string filename = levels_path + intro_filename;
1043     display_text_file(filename);
1044     intro_displayed = true;
1045   }
1046
1047   Uint32 lastticks = SDL_GetTicks();
1048   DrawingContext context;
1049   while(!quit) {
1050     Uint32 ticks = SDL_GetTicks();
1051     float elapsed_time = float(ticks - lastticks) / 1000;
1052     global_time += elapsed_time;
1053     lastticks = ticks;
1054     
1055     // 40 fps minimum
1056     if(elapsed_time > .025)
1057       elapsed_time = .025;
1058     
1059     Vector tux_pos = tux->get_pos();
1060     
1061     offset.x = -tux_pos.x + screen->w/2;
1062     offset.y = -tux_pos.y + screen->h/2;
1063
1064     if (offset.x > 0) offset.x = 0;
1065     if (offset.y > 0) offset.y = 0;
1066
1067     if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
1068     if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
1069     
1070     draw(context, offset);
1071     get_input();
1072     update(elapsed_time);
1073       
1074     if(Menu::current()) {
1075       Menu::current()->draw(context);
1076       mouse_cursor->draw(context);
1077     }
1078
1079     context.do_drawing();
1080   }
1081 }
1082
1083 void
1084 WorldMap::savegame(const std::string& filename)
1085 {
1086   if(filename == "")
1087     return;
1088
1089   std::ofstream file(filename.c_str(), std::ios::out);
1090   lisp::Writer writer(file);
1091
1092   int nb_solved_levels = 0, total_levels = 0;
1093   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
1094     ++total_levels;
1095     if (i->solved)
1096       ++nb_solved_levels;
1097   }
1098   char nb_solved_levels_str[80], total_levels_str[80];
1099   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1100   sprintf(total_levels_str, "%d", total_levels);
1101
1102   writer.write_comment("Worldmap save file");
1103
1104   writer.start_list("supertux-savegame");
1105
1106   writer.write_int("version", 1);
1107   writer.write_string("title",
1108       std::string(name + " - " + nb_solved_levels_str+"/"+total_levels_str));
1109   writer.write_string("map", map_filename);
1110   writer.write_bool("intro-displayed", intro_displayed);
1111
1112   writer.start_list("tux");
1113
1114   writer.write_float("x", tux->get_tile_pos().x);
1115   writer.write_float("y", tux->get_tile_pos().y);
1116   writer.write_string("back", direction_to_string(tux->back_direction));
1117   player_status.write(writer);
1118   writer.write_string("back", direction_to_string(tux->back_direction));
1119
1120   writer.end_list("tux");
1121
1122   writer.start_list("levels");
1123
1124   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1125     {
1126       if (i->solved)
1127         {
1128         writer.start_list("level");
1129
1130         writer.write_string("name", i->name);
1131         writer.write_bool("solved", true);
1132         i->statistics.write(writer);
1133
1134         writer.end_list("level");
1135         }
1136     }  
1137
1138   writer.end_list("levels");
1139
1140   writer.end_list("supertux-savegame");
1141 }
1142
1143 void
1144 WorldMap::loadgame(const std::string& filename)
1145 {
1146   std::cout << "loadgame: " << filename << std::endl;
1147   savegame_file = filename;
1148
1149   try {
1150     lisp::Parser parser;
1151     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
1152   
1153     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
1154     if(!savegame)
1155       throw std::runtime_error("File is not a supertux-savegame file.");
1156
1157     /* Get the Map filename and then load it before setting level settings */
1158     std::string cur_map_filename = map_filename;
1159     savegame->get("map", map_filename);
1160     load_map(); 
1161
1162     savegame->get("intro-displayed", intro_displayed);
1163     savegame->get("lives", player_status.lives);
1164     savegame->get("distros", player_status.distros);
1165     savegame->get("max-score-multiplier", player_status.max_score_multiplier);
1166     if (player_status.lives < 0)
1167       player_status.reset();
1168
1169     const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
1170     if(tux)
1171     {
1172       Vector p;
1173       std::string back_str = "none";
1174
1175       tux_lisp->get("x", p.x);
1176       tux_lisp->get("y", p.y);
1177       tux_lisp->get("back", back_str);
1178       player_status.read(*tux_lisp);
1179       
1180       tux->back_direction = string_to_direction(back_str);      
1181       tux->set_tile_pos(p);
1182     }
1183
1184     const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
1185     if(levels_lisp) {
1186       lisp::ListIterator iter(levels_lisp);
1187       while(iter.next()) {
1188         if(iter.item() == "level") {
1189           std::string name;
1190           bool solved = false;
1191
1192           const lisp::Lisp* level = iter.lisp();
1193           level->get("name", name);
1194           level->get("solved", solved);
1195
1196           for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1197           {
1198             if (name == i->name)
1199             {
1200               i->solved = solved;
1201               i->statistics.parse(*level);
1202               break;
1203             }
1204           }
1205         } else {
1206           std::cerr << "Unknown token '" << iter.item() 
1207             << "' in levels block in worldmap.\n";
1208         }
1209       }
1210     }
1211   } catch(std::exception& e) {
1212     std::cerr << "Problem loading game '" << filename << "': " << e.what() 
1213       << "\n";
1214     load_map();
1215     player_status.reset();
1216   }
1217
1218   calculate_total_stats();
1219 }
1220
1221 void
1222 WorldMap::loadmap(const std::string& filename)
1223 {
1224   savegame_file = "";
1225   map_filename = filename;
1226   load_map();
1227 }
1228
1229 } // namespace WorldMapNS