changed worldmap to be stored inside the same directory as the levelsubset, fixed...
[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   std::string::size_type p = map_filename.find_last_of('/');
372   if(p == std::string::npos)                              
373     levels_path = "";
374   else
375     levels_path = map_filename.substr(0, p+1);
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("start_pos_x", start_x);
401         props->get("start_pos_y", start_y);
402       } else if(iter.item() == "special-tiles") {
403         parse_special_tiles(iter.lisp());
404       } else {
405         std::cerr << "Unknown token '" << iter.item() << "' in worldmap.\n";
406       }
407     }
408
409     delete tux;
410     tux = new Tux(this);
411   } catch(std::exception& e) {
412     std::stringstream msg;
413     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
414       e.what();
415     throw std::runtime_error(msg.str());
416   }
417 }
418
419 void
420 WorldMap::parse_special_tiles(const lisp::Lisp* lisp)
421 {
422   lisp::ListIterator iter(lisp);
423   while(iter.next()) {
424     if(iter.item() == "special-tile") {
425       SpecialTile special_tile;
426
427       const lisp::Lisp* lisp = iter.lisp();
428       lisp->get("x", special_tile.pos.x);
429       lisp->get("y", special_tile.pos.y);
430       lisp->get("map-message", special_tile.map_message);
431       special_tile.passive_message = false;
432       lisp->get("passive-message", special_tile.passive_message);
433       special_tile.teleport_dest = Vector(-1,-1);
434       lisp->get("teleport-to-x", special_tile.teleport_dest.x);
435       lisp->get("teleport-to-y", special_tile.teleport_dest.y);
436       special_tile.invisible = false;
437       lisp->get("invisible-tile", special_tile.invisible);
438
439       special_tile.apply_action_north = true;
440       special_tile.apply_action_south = true;
441       special_tile.apply_action_east = true;
442       special_tile.apply_action_west = true;
443
444       std::string apply_direction;
445       lisp->get("apply-to-direction", apply_direction);
446       if(!apply_direction.empty()) {
447         special_tile.apply_action_north = false;
448         special_tile.apply_action_south = false;
449         special_tile.apply_action_east = false;
450         special_tile.apply_action_west = false;
451         if(apply_direction.find("north") != std::string::npos)
452           special_tile.apply_action_north = true;
453         if(apply_direction.find("south") != std::string::npos)
454           special_tile.apply_action_south = true;
455         if(apply_direction.find("east") != std::string::npos)
456           special_tile.apply_action_east = true;
457         if(apply_direction.find("west") != std::string::npos)
458           special_tile.apply_action_west = true;
459       }
460       
461       special_tiles.push_back(special_tile);
462     } else if(iter.item() == "level") {
463       Level level;
464
465       lisp::Lisp* level_lisp = iter.lisp();
466       level.solved = false;
467                       
468       level.north = true;
469       level.east  = true;
470       level.south = true;
471       level.west  = true;
472
473       level_lisp->get("extro-filename", level.extro_filename);
474       level_lisp->get("next-worldmap", level.next_worldmap);
475
476       level.quit_worldmap = false;
477       level_lisp->get("quit-worldmap", level.quit_worldmap);
478
479       level_lisp->get("name", level.name);
480       level_lisp->get("x", level.pos.x);
481       level_lisp->get("y", level.pos.y);
482
483       level.auto_path = true;
484       level_lisp->get("auto-path", level.auto_path);
485
486       level.vertical_flip = false;
487       level_lisp->get("vertical-flip", level.vertical_flip);
488
489       levels.push_back(level);
490     } else {
491       std::cerr << "Unknown token '" << iter.item() <<
492         "' in worldmap special-tiles list.";
493     }
494   }
495 }
496
497 void
498 WorldMap::get_level_title(Level& level)
499 {
500   /** get special_tile's title */
501   level.title = "<no title>";
502
503   try {
504     lisp::Parser parser;
505     std::auto_ptr<lisp::Lisp> root (
506         parser.parse(get_resource_filename(levels_path + level.name)));
507
508     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
509     if(!level_lisp)
510       return;
511     
512     level_lisp->get("name", level.title);
513   } catch(std::exception& e) {
514     std::cerr << "Problem when reading leveltitle: " << e.what() << "\n";
515     return;
516   }
517 }
518
519 void WorldMap::calculate_total_stats()
520 {
521   total_stats.reset();
522   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
523     {
524     if (i->solved)
525       {
526       total_stats += i->statistics;
527       }
528     }
529 }
530
531 void
532 WorldMap::on_escape_press()
533 {
534   // Show or hide the menu
535   if(!Menu::current())
536     {
537     Menu::set_current(worldmap_menu); 
538     tux->set_direction(D_NONE);  // stop tux movement when menu is called
539     }
540   else
541     Menu::set_current(0); 
542 }
543
544 void
545 WorldMap::get_input()
546 {
547   enter_level = false;
548   SDLKey key;
549
550   SDL_Event event;
551   while (SDL_PollEvent(&event))
552     {
553       if (Menu::current())
554         {
555           Menu::current()->event(event);
556         }
557       else
558         {
559           switch(event.type)
560             {
561             case SDL_QUIT:
562               Termination::abort("Received window close", "");
563               break;
564           
565             case SDL_KEYDOWN:
566               key = event.key.keysym.sym;
567
568               if(key == SDLK_ESCAPE)
569                 on_escape_press();
570               else if(key == SDLK_RETURN || key == keymap.power)
571                 enter_level = true;
572               else if(key == SDLK_LEFT || key == keymap.power)
573                 tux->set_direction(D_WEST);
574               else if(key == SDLK_RIGHT || key == keymap.right)
575                 tux->set_direction(D_EAST);
576               else if(key == SDLK_UP || key == keymap.up ||
577                 key == keymap.jump)
578                   // there might be ppl that use jump as up key
579                 tux->set_direction(D_NORTH);
580               else if(key == SDLK_DOWN || key == keymap.down)
581                 tux->set_direction(D_SOUTH);
582               break;
583
584             case SDL_JOYHATMOTION:
585               if(event.jhat.value & SDL_HAT_UP) {
586                 tux->set_direction(D_NORTH);
587               } else if(event.jhat.value & SDL_HAT_DOWN) {
588                 tux->set_direction(D_SOUTH);
589               } else if(event.jhat.value & SDL_HAT_LEFT) {
590                 tux->set_direction(D_WEST);
591               } else if(event.jhat.value & SDL_HAT_RIGHT) {
592                 tux->set_direction(D_EAST);
593               }
594               break;
595           
596             case SDL_JOYAXISMOTION:
597               if (event.jaxis.axis == joystick_keymap.x_axis)
598                 {
599                   if (event.jaxis.value < -joystick_keymap.dead_zone)
600                     tux->set_direction(D_WEST);
601                   else if (event.jaxis.value > joystick_keymap.dead_zone)
602                     tux->set_direction(D_EAST);
603                 }
604               else if (event.jaxis.axis == joystick_keymap.y_axis)
605                 {
606                   if (event.jaxis.value > joystick_keymap.dead_zone)
607                     tux->set_direction(D_SOUTH);
608                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
609                     tux->set_direction(D_NORTH);
610                 }
611               break;
612
613             case SDL_JOYBUTTONDOWN:
614               if (event.jbutton.button == joystick_keymap.b_button)
615                 enter_level = true;
616               else if (event.jbutton.button == joystick_keymap.start_button)
617                 on_escape_press();
618               break;
619
620             default:
621               break;
622             }
623         }
624     }
625 }
626
627 Vector
628 WorldMap::get_next_tile(Vector pos, Direction direction)
629 {
630   switch(direction)
631     {
632     case D_WEST:
633       pos.x -= 1;
634       break;
635     case D_EAST:
636       pos.x += 1;
637       break;
638     case D_NORTH:
639       pos.y -= 1;
640       break;
641     case D_SOUTH:
642       pos.y += 1;
643       break;
644     case D_NONE:
645       break;
646     }
647   return pos;
648 }
649
650 bool
651 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
652 {
653   *new_pos = get_next_tile(old_pos, direction);
654
655   if (!(new_pos->x >= 0 && new_pos->x < width
656         && new_pos->y >= 0 && new_pos->y < height))
657     { // New position is outsite the tilemap
658       return false;
659     }
660   else
661     { // Check if the tile allows us to go to new_pos
662       switch(direction)
663         {
664         case D_WEST:
665           return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
666               && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
667
668         case D_EAST:
669           return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
670               && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
671
672         case D_NORTH:
673           return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
674               && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
675
676         case D_SOUTH:
677           return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
678               && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
679
680         case D_NONE:
681           assert(!"path_ok() can't work if direction is NONE");
682         }
683       return false;
684     }
685 }
686
687 void
688 WorldMap::update(float delta)
689 {
690   if (enter_level && !tux->is_moving())
691     {
692       /* Check special tile action */
693       SpecialTile* special_tile = at_special_tile();
694       if(special_tile)
695         {
696         if (special_tile->teleport_dest != Vector(-1,-1))
697           {
698           // TODO: an animation, camera scrolling or a fading would be a nice touch
699           SoundManager::get()->play_sound(IDToSound(SND_WARP));
700           tux->back_direction = D_NONE;
701           tux->set_tile_pos(special_tile->teleport_dest);
702           SDL_Delay(1000);
703           }
704         }
705
706       /* Check level action */
707       bool level_finished = true;
708       Level* level = at_level();
709       if (!level)
710         {
711         std::cout << "No level to enter at: "
712           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y
713           << std::endl;
714         return;
715         }
716
717
718       if (level->pos == tux->get_tile_pos())
719         {
720           PlayerStatus old_player_status = player_status;
721
722           std::cout << "Enter the current level: " << level->name << std::endl;
723           // do a shriking fade to the level
724           shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
725                              (level->pos.y*32 + 16 + offset.y)), 500);
726           GameSession session(get_resource_filename(levels_path + level->name),
727                               ST_GL_LOAD_LEVEL_FILE, &level->statistics);
728
729           switch (session.run())
730             {
731             case GameSession::ES_LEVEL_FINISHED:
732               {
733                 level_finished = true;
734                 bool old_level_state = level->solved;
735                 level->solved = true;
736
737                 // deal with statistics
738                 level->statistics.merge(global_stats);
739                 calculate_total_stats();
740
741                 if (session.get_current_sector()->player->got_power !=
742                       session.get_current_sector()->player->NONE_POWER)
743                   player_status.bonus = PlayerStatus::FLOWER_BONUS;
744                 else if (session.get_current_sector()->player->size == BIG)
745                   player_status.bonus = PlayerStatus::GROWUP_BONUS;
746                 else
747                   player_status.bonus = PlayerStatus::NO_BONUS;
748
749                 if (old_level_state != level->solved && level->auto_path)
750                   { // Try to detect the next direction to which we should walk
751                     // FIXME: Mostly a hack
752                     Direction dir = D_NONE;
753                 
754                     const Tile* tile = at(tux->get_tile_pos());
755
756                     if (tile->getData() & Tile::WORLDMAP_NORTH
757                         && tux->back_direction != D_NORTH)
758                       dir = D_NORTH;
759                     else if (tile->getData() & Tile::WORLDMAP_SOUTH
760                         && tux->back_direction != D_SOUTH)
761                       dir = D_SOUTH;
762                     else if (tile->getData() & Tile::WORLDMAP_EAST
763                         && tux->back_direction != D_EAST)
764                       dir = D_EAST;
765                     else if (tile->getData() & Tile::WORLDMAP_WEST
766                         && tux->back_direction != D_WEST)
767                       dir = D_WEST;
768
769                     if (dir != D_NONE)
770                       {
771                         tux->set_direction(dir);
772                         //tux->update(delta);
773                       }
774
775                     std::cout << "Walk to dir: " << dir << std::endl;
776                   }
777               }
778
779               break;
780             case GameSession::ES_LEVEL_ABORT:
781               level_finished = false;
782               /* In case the player's abort the level, keep it using the old
783                   status. But the minimum lives and no bonus. */
784               player_status.distros = old_player_status.distros;
785               player_status.lives = std::min(old_player_status.lives, player_status.lives);
786               player_status.bonus = player_status.NO_BONUS;
787
788               break;
789             case GameSession::ES_GAME_OVER:
790               {
791               level_finished = false;
792               /* draw an end screen */
793               /* TODO: in the future, this should make a dialog a la SuperMario, asking
794               if the player wants to restart the world map with no score and from
795               level 1 */
796               char str[80];
797
798               DrawingContext context;
799               context.draw_gradient(Color (200,240,220), Color(200,200,220),
800                   LAYER_BACKGROUND0);
801
802               context.draw_text(blue_text, _("GAMEOVER"), 
803                   Vector(screen->w/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
804
805               sprintf(str, _("COINS: %d"), player_status.distros);
806               context.draw_text(gold_text, str,
807                   Vector(screen->w/2, screen->w - 32), CENTER_ALLIGN,
808                   LAYER_FOREGROUND1);
809
810               total_stats.draw_message_info(context, _("Total Statistics"));
811
812               context.do_drawing();
813
814               SDL_Event event;
815               wait_for_event(event,2000,6000,true);
816
817               quit = true;
818               player_status.reset();
819               break;
820               }
821             case GameSession::ES_NONE:
822               assert(false);
823               // Should never be reached 
824               break;
825             }
826
827           SoundManager::get()->play_music(song);
828           Menu::set_current(0);
829           if (!savegame_file.empty())
830             savegame(savegame_file);
831         }
832       /* The porpose of the next checking is that if the player lost
833          the level (in case there is one), don't show anything */
834       if(level_finished)
835         {
836         if (!level->extro_filename.empty())
837           {
838           // Display a text file
839           display_text_file(level->extro_filename, SCROLL_SPEED_MESSAGE,
840               white_big_text , white_text, white_small_text, blue_text );
841           }
842
843         if (!level->next_worldmap.empty())
844           {
845           // Load given worldmap
846           loadmap(level->next_worldmap);
847           }
848         if (level->quit_worldmap)
849           quit = true;
850         }
851     }
852   else
853     {
854       tux->action(delta);
855 //      tux->set_direction(input_direction);
856     }
857   
858   Menu* menu = Menu::current();
859   if(menu)
860     {
861       menu->action();
862
863       if(menu == worldmap_menu)
864         {
865           switch (worldmap_menu->check())
866             {
867             case MNID_RETURNWORLDMAP: // Return to game
868               break;
869             case MNID_QUITWORLDMAP: // Quit Worldmap
870               quit = true;
871               break;
872             }
873         }
874       else if(menu == options_menu)
875         {
876           process_options_menu();
877         }
878     }
879 }
880
881 const Tile*
882 WorldMap::at(Vector p)
883 {
884   assert(p.x >= 0 
885          && p.x < width
886          && p.y >= 0
887          && p.y < height);
888
889   int x = int(p.x);
890   int y = int(p.y);
891   return tile_manager->get(tilemap[width * y + x]);
892 }
893
894 WorldMap::Level*
895 WorldMap::at_level()
896 {
897   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
898     {
899       if (i->pos == tux->get_tile_pos())
900         return &*i; 
901     }
902
903   return 0;
904 }
905
906 WorldMap::SpecialTile*
907 WorldMap::at_special_tile()
908 {
909   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
910     {
911       if (i->pos == tux->get_tile_pos())
912         return &*i; 
913     }
914
915   return 0;
916 }
917
918
919 void
920 WorldMap::draw(DrawingContext& context, const Vector& offset)
921 {
922   for(int y = 0; y < height; ++y)
923     for(int x = 0; x < width; ++x)
924       {
925         const Tile* tile = at(Vector(x, y));
926         tile->draw(context, Vector(x*32 + offset.x, y*32 + offset.y),
927             LAYER_TILES);
928       }
929
930   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
931     {
932       if (i->solved)
933         context.draw_surface(leveldot_green,
934             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
935       else
936         context.draw_surface(leveldot_red,
937             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
938     }
939
940   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
941     {
942       if(i->invisible)
943         continue;
944
945       if (i->teleport_dest != Vector(-1, -1))
946         context.draw_surface(teleporterdot,
947                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
948
949       else if (!i->map_message.empty() && !i->passive_message)
950         context.draw_surface(messagedot,
951                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
952     }
953
954   tux->draw(context, offset);
955   draw_status(context);
956 }
957
958 void
959 WorldMap::draw_status(DrawingContext& context)
960 {
961   char str[80];
962   sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
963
964   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
965   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
966
967   sprintf(str, "%d", player_status.distros);
968   context.draw_text(white_text, _("COINS"), Vector(screen->w/2 - 16*5, 0),
969       LEFT_ALLIGN, LAYER_FOREGROUND1);
970   context.draw_text(gold_text, str, Vector(screen->w/2 + (16*5)/2, 0),
971         LEFT_ALLIGN, LAYER_FOREGROUND1);
972
973   if (player_status.lives >= 5)
974     {
975       sprintf(str, "%dx", player_status.lives);
976       context.draw_text(gold_text, str, 
977           Vector(screen->w - gold_text->get_text_width(str) - tux_life->w, 0),
978           LEFT_ALLIGN, LAYER_FOREGROUND1);
979       context.draw_surface(tux_life, Vector(screen->w -
980             gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
981     }
982   else
983     {
984       for(int i= 0; i < player_status.lives; ++i)
985         context.draw_surface(tux_life,
986             Vector(screen->w - tux_life->w*4 + (tux_life->w*i), 0),
987             LAYER_FOREGROUND1);
988     }
989   context.draw_text(white_text, _("LIVES"),
990       Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
991       LEFT_ALLIGN, LAYER_FOREGROUND1);
992
993   if (!tux->is_moving())
994     {
995       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
996         {
997           if (i->pos == tux->get_tile_pos())
998             {
999               if(i->title == "")
1000                 get_level_title(*i);
1001
1002               context.draw_text(white_text, i->title, 
1003                   Vector(screen->w/2,
1004                          screen->h - white_text->get_height() - 30),
1005                   CENTER_ALLIGN, LAYER_FOREGROUND1);
1006
1007               i->statistics.draw_worldmap_info(context);
1008               break;
1009             }
1010         }
1011       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1012         {
1013           if (i->pos == tux->get_tile_pos())
1014             {
1015                /* Display an in-map message in the map, if any as been selected */
1016               if(!i->map_message.empty() && !i->passive_message)
1017                 context.draw_text(gold_text, i->map_message, 
1018                     Vector(screen->w/2,
1019                            screen->h - white_text->get_height() - 60),
1020                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1021               break;
1022             }
1023         }
1024     }
1025   /* Display a passive message in the map, if needed */
1026   if(passive_message_timer.check())
1027     context.draw_text(gold_text, passive_message, 
1028             Vector(screen->w/2, screen->h - white_text->get_height() - 60),
1029             CENTER_ALLIGN, LAYER_FOREGROUND1);
1030 }
1031
1032 void
1033 WorldMap::display()
1034 {
1035   Menu::set_current(0);
1036
1037   quit = false;
1038
1039   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1040   SoundManager::get()->play_music(song);
1041
1042   FrameRate frame_rate(10);
1043   frame_rate.set_frame_limit(false);
1044
1045   frame_rate.start();
1046
1047   DrawingContext context;
1048   while(!quit)
1049     {
1050       float delta = frame_rate.get();
1051
1052       delta *= 1.3f;
1053
1054       if (delta > 10.0f)
1055         delta = .3f;
1056         
1057       frame_rate.update();
1058
1059       Vector tux_pos = tux->get_pos();
1060       if (1)
1061         {
1062           offset.x = -tux_pos.x + screen->w/2;
1063           offset.y = -tux_pos.y + screen->h/2;
1064
1065           if (offset.x > 0) offset.x = 0;
1066           if (offset.y > 0) offset.y = 0;
1067
1068           if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
1069           if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
1070         } 
1071
1072       draw(context, offset);
1073       get_input();
1074       update(delta);
1075       
1076       if(Menu::current())
1077         {
1078           Menu::current()->draw(context);
1079           mouse_cursor->draw(context);
1080         }
1081
1082       context.do_drawing();
1083
1084       SDL_Delay(20);
1085     }
1086 }
1087
1088 void
1089 WorldMap::savegame(const std::string& filename)
1090 {
1091   if(filename == "")
1092     return;
1093
1094   std::cout << "savegame: " << filename << std::endl;
1095
1096   std::ofstream file(filename.c_str(), std::ios::out);
1097   lisp::Writer writer(file);
1098
1099   int nb_solved_levels = 0, total_levels = 0;
1100   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
1101     ++total_levels;
1102     if (i->solved)
1103       ++nb_solved_levels;
1104   }
1105   char nb_solved_levels_str[80], total_levels_str[80];
1106   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1107   sprintf(total_levels_str, "%d", total_levels);
1108
1109   writer.write_comment("Worldmap save file");
1110
1111   writer.start_list("supertux-savegame");
1112
1113   writer.write_int("version", 1);
1114   writer.write_string("title",
1115       std::string(name + " - " + nb_solved_levels_str+"/"+total_levels_str));
1116   writer.write_string("map", map_filename);
1117   writer.write_int("lives", player_status.lives);
1118   writer.write_int("distros", player_status.lives);
1119   writer.write_int("max-score-multiplier", player_status.max_score_multiplier);
1120
1121   writer.start_list("tux");
1122
1123   writer.write_float("x", tux->get_tile_pos().x);
1124   writer.write_float("y", tux->get_tile_pos().y);
1125   writer.write_string("back", direction_to_string(tux->back_direction));
1126   writer.write_string("bonus", bonus_to_string(player_status.bonus));
1127
1128   writer.end_list("tux");
1129
1130   writer.start_list("levels");
1131
1132   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1133     {
1134       if (i->solved)
1135         {
1136         writer.start_list("level");
1137
1138         writer.write_string("name", i->name);
1139         writer.write_bool("solved", true);
1140         i->statistics.write(writer);
1141
1142         writer.end_list("level");
1143         }
1144     }  
1145
1146   writer.end_list("levels");
1147
1148   writer.end_list("supertux-savegame");
1149 }
1150
1151 void
1152 WorldMap::loadgame(const std::string& filename)
1153 {
1154   std::cout << "loadgame: " << filename << std::endl;
1155   savegame_file = filename;
1156
1157   try {
1158     lisp::Parser parser;
1159     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
1160   
1161     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
1162     if(!savegame)
1163       throw std::runtime_error("File is not a supertux-savegame file.");
1164
1165     /* Get the Map filename and then load it before setting level settings */
1166     std::string cur_map_filename = map_filename;
1167     savegame->get("map", map_filename);
1168     load_map(); 
1169
1170     savegame->get("lives", player_status.lives);
1171     savegame->get("distros", player_status.distros);
1172     savegame->get("max-score-multiplier", player_status.max_score_multiplier);
1173     if (player_status.lives < 0)
1174       player_status.lives = START_LIVES;
1175
1176     const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
1177     if(tux)
1178     {
1179       Vector p;
1180       std::string back_str = "none";
1181       std::string bonus_str = "none";
1182
1183       tux_lisp->get("x", p.x);
1184       tux_lisp->get("y", p.y);
1185       tux_lisp->get("back", back_str);
1186       tux_lisp->get("bonus", bonus_str);
1187       
1188       player_status.bonus = string_to_bonus(bonus_str);
1189       tux->back_direction = string_to_direction(back_str);      
1190       tux->set_tile_pos(p);
1191     }
1192
1193     const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
1194     if(levels_lisp) {
1195       lisp::ListIterator iter(levels_lisp);
1196       while(iter.next()) {
1197         if(iter.item() == "level") {
1198           std::string name;
1199           bool solved = false;
1200
1201           const lisp::Lisp* level = iter.lisp();
1202           level->get("name", name);
1203           level->get("solved", solved);
1204
1205           for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1206           {
1207             if (name == i->name)
1208             {
1209               i->solved = solved;
1210               i->statistics.parse(*level);
1211               break;
1212             }
1213           }
1214         } else {
1215           std::cerr << "Unknown token '" << iter.item() 
1216             << "' in levels block in worldmap.\n";
1217         }
1218       }
1219     }
1220   } catch(std::exception& e) {
1221     std::cerr << "Problem loading game '" << filename << "': " << e.what() 
1222       << "\n";
1223     load_map();
1224     player_status.reset();
1225   }
1226
1227   calculate_total_stats();
1228 }
1229
1230 void
1231 WorldMap::loadmap(const std::string& filename)
1232 {
1233   savegame_file = "";
1234   map_filename = filename;
1235   load_map();
1236 }
1237
1238 } // namespace WorldMapNS
1239
1240 /* Local Variables: */
1241 /* mode:c++ */
1242 /* End: */
1243