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