facad2f2a4d3c37c8902c0f0c4dde35b54d07749
[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
20 #include <iostream>
21 #include <fstream>
22 #include <vector>
23 #include <assert.h>
24 #include "globals.h"
25 #include "texture.h"
26 #include "screen.h"
27 #include "lispreader.h"
28 #include "gameloop.h"
29 #include "setup.h"
30 #include "worldmap.h"
31 #include "resources.h"
32
33 namespace WorldMapNS {
34
35 Direction reverse_dir(Direction direction)
36 {
37   switch(direction)
38     {
39     case WEST:
40       return EAST;
41     case EAST:
42       return WEST;
43     case NORTH:
44       return SOUTH;
45     case SOUTH:
46       return NORTH;
47     case NONE:
48       return NONE;
49     }
50   return NONE;
51 }
52
53 std::string
54 direction_to_string(Direction direction)
55 {
56   switch(direction)
57     {
58     case WEST:
59       return "west";
60     case EAST:
61       return "east";
62     case NORTH:
63       return "north";
64     case SOUTH:
65       return "south";
66     default:
67       return "none";
68     }
69 }
70
71 Direction
72 string_to_direction(const std::string& directory)
73 {
74   if (directory == "west")
75     return WEST;
76   else if (directory == "east")
77     return EAST;
78   else if (directory == "north")
79     return NORTH;
80   else if (directory == "south")
81     return SOUTH;
82   else
83     return NONE;
84 }
85
86 TileManager* TileManager::instance_  = 0;
87
88 TileManager::TileManager()
89 {
90   std::string stwt_filename = datadir +  "images/worldmap/antarctica.stwt";
91   lisp_object_t* root_obj = lisp_read_from_file(stwt_filename);
92  
93   if (!root_obj)
94     st_abort("Couldn't load file", stwt_filename);
95
96   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap-tiles") == 0)
97     {
98       lisp_object_t* cur = lisp_cdr(root_obj);
99
100       while(!lisp_nil_p(cur))
101         {
102           lisp_object_t* element = lisp_car(cur);
103
104           if (strcmp(lisp_symbol(lisp_car(element)), "tile") == 0)
105             {
106               int id = 0;
107               std::string filename = "<invalid>";
108
109               Tile* tile = new Tile;             
110               tile->north = true;
111               tile->east  = true;
112               tile->south = true;
113               tile->west  = true;
114               tile->stop  = true;
115   
116               LispReader reader(lisp_cdr(element));
117               reader.read_int("id",  &id);
118               reader.read_bool("north", &tile->north);
119               reader.read_bool("south", &tile->south);
120               reader.read_bool("west",  &tile->west);
121               reader.read_bool("east",  &tile->east);
122               reader.read_bool("stop",  &tile->stop);
123               reader.read_string("image",  &filename);
124
125               tile->sprite = new Surface(
126                            datadir +  "/images/worldmap/" + filename, 
127                            USE_ALPHA);
128
129               if (id >= int(tiles.size()))
130                 tiles.resize(id+1);
131
132               tiles[id] = tile;
133             }
134           else
135             {
136               puts("Unhandled symbol");
137             }
138
139           cur = lisp_cdr(cur);
140         }
141     }
142   else
143     {
144       assert(0);
145     }
146 }
147
148 Tile*
149 TileManager::get(int i)
150 {
151   assert(i >=0 && i < int(tiles.size()));
152   return tiles[i];
153 }
154
155 Tux::Tux(WorldMap* worldmap_)
156   : worldmap(worldmap_)
157 {
158   sprite = new Surface(datadir +  "/images/worldmap/tux.png", USE_ALPHA);
159   offset = 0;
160   moving = false;
161   tile_pos.x = 4;
162   tile_pos.y = 5;
163   direction = NONE;
164   input_direction = NONE;
165 }
166
167 void
168 Tux::draw(const Point& offset)
169 {
170   Point pos = get_pos();
171   sprite->draw(pos.x + offset.x, 
172                pos.y + offset.y);
173 }
174
175
176 Point
177 Tux::get_pos()
178 {
179   float x = tile_pos.x * 32;
180   float y = tile_pos.y * 32;
181
182   switch(direction)
183     {
184     case WEST:
185       x -= offset - 32;
186       break;
187     case EAST:
188       x += offset - 32;
189       break;
190     case NORTH:
191       y -= offset - 32;
192       break;
193     case SOUTH:
194       y += offset - 32;
195       break;
196     case NONE:
197       break;
198     }
199   
200   return Point((int)x, (int)y); 
201 }
202
203 void
204 Tux::stop()
205 {
206   offset = 0;
207   direction = NONE;
208   moving = false;
209 }
210
211 void
212 Tux::update(float delta)
213 {
214   if (!moving)
215     {
216       if (input_direction != NONE)
217         { 
218           WorldMap::Level* level = worldmap->at_level();
219
220           // We got a new direction, so lets start walking when possible
221           Point next_tile;
222           if ((!level || level->solved)
223               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
224             {
225               tile_pos = next_tile;
226               moving = true;
227               direction = input_direction;
228               back_direction = reverse_dir(direction);
229             }
230           else if (input_direction == back_direction)
231             {
232               std::cout << "Back triggered" << std::endl;
233               moving = true;
234               direction = input_direction;
235               tile_pos = worldmap->get_next_tile(tile_pos, direction);
236               back_direction = reverse_dir(direction);
237             }
238         }
239     }
240   else
241     {
242       // Let tux walk a few pixels (20 pixel/sec)
243       offset += 20.0f * delta;
244
245       if (offset > 32)
246         { // We reached the next tile, so we check what to do now
247           offset -= 32;
248
249           if (worldmap->at(tile_pos)->stop || worldmap->at_level())
250             {
251               stop();
252             }
253           else
254             {
255               // Walk automatically to the next tile
256               Point next_tile;
257               if (worldmap->path_ok(direction, tile_pos, &next_tile))
258                 {
259                   tile_pos = next_tile;
260                 }
261               else
262                 {
263                   puts("Tilemap data is buggy");
264                   stop();
265                 }
266             }
267         }
268     }
269 }
270
271 WorldMap::WorldMap()
272 {
273   tux = new Tux(this);
274
275   width  = 20;
276   height = 15;
277
278   level_sprite = new Surface(datadir +  "/images/worldmap/levelmarker.png", USE_ALPHA);
279   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", USE_ALPHA);
280   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", USE_ALPHA);
281
282   input_direction = NONE;
283   enter_level = false;
284
285   name = "<no file>";
286   music = "SALCON.MOD";
287
288   load_map();
289 }
290
291 WorldMap::~WorldMap()
292 {
293   delete tux;
294 }
295
296 void
297 WorldMap::load_map()
298 {
299   std::string filename = datadir +  "levels/default/worldmap.stwm";
300   
301   lisp_object_t* root_obj = lisp_read_from_file(filename);
302   if (!root_obj)
303     st_abort("Couldn't load file", filename);
304   
305   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
306     {
307       lisp_object_t* cur = lisp_cdr(root_obj);
308
309       while(!lisp_nil_p(cur))
310         {
311           lisp_object_t* element = lisp_car(cur);
312
313           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
314             {
315               LispReader reader(lisp_cdr(element));
316               reader.read_int("width",  &width);
317               reader.read_int("height", &height);
318               reader.read_int_vector("data", &tilemap);
319             }
320           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
321             {
322               LispReader reader(lisp_cdr(element));
323               reader.read_string("name",  &name);
324               reader.read_string("music", &music);
325             }
326           else if (strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
327             {
328               lisp_object_t* cur = lisp_cdr(element);
329               
330               while(!lisp_nil_p(cur))
331                 {
332                   lisp_object_t* element = lisp_car(cur);
333                   
334                   if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
335                     {
336                       Level level;
337                       LispReader reader(lisp_cdr(element));
338                       level.solved = false;
339                       
340                       level.north = true;
341                       level.east  = true;
342                       level.south = true;
343                       level.west  = true;
344
345                       reader.read_string("name",  &level.name);
346                       reader.read_int("x", &level.x);
347                       reader.read_int("y", &level.y);
348
349                       get_level_title(&level);   // get level's title
350
351                       levels.push_back(level);
352                     }
353                   
354                   cur = lisp_cdr(cur);      
355                 }
356             }
357           else
358             {
359               
360             }
361           
362           cur = lisp_cdr(cur);
363         }
364     }
365 }
366
367 void WorldMap::get_level_title(Levels::pointer level)
368 {
369 /** get level's title */
370 level->title = "<no title>";
371
372 FILE * fi;
373 lisp_object_t* root_obj = 0;
374 fi = fopen((datadir +  "levels/" + level->name).c_str(), "r");
375 if (fi == NULL)
376   {
377   perror((datadir +  "levels/" + level->name).c_str());
378   return;
379   }
380
381 lisp_stream_t stream;
382 lisp_stream_init_file (&stream, fi);
383 root_obj = lisp_read (&stream);
384
385 if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
386   {
387   printf("World: Parse Error in file %s", level->name.c_str());
388   }
389
390 if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-level") == 0)
391   {
392   LispReader reader(lisp_cdr(root_obj));
393   reader.read_string("name",  &level->title);
394   }
395
396 fclose(fi);
397 }
398
399 void
400 WorldMap::on_escape_press()
401 {
402   // Show or hide the menu
403   if(!Menu::current())
404     Menu::set_current(worldmap_menu); 
405   else
406     Menu::set_current(0); 
407 }
408
409 void
410 WorldMap::get_input()
411 {
412   enter_level = false;
413   input_direction = NONE;
414    
415   SDL_Event event;
416   while (SDL_PollEvent(&event))
417     {
418       if (Menu::current())
419         {
420           Menu::current()->event(event);
421         }
422       else
423         {
424           switch(event.type)
425             {
426             case SDL_QUIT:
427               st_abort("Received window close", "");
428               break;
429           
430             case SDL_KEYDOWN:
431               switch(event.key.keysym.sym)
432                 {
433                 case SDLK_ESCAPE:
434                   on_escape_press();
435                   break;
436                 case SDLK_LCTRL:
437                 case SDLK_RETURN:
438                   enter_level = true;
439                   break;
440                 default:
441                   break;
442                 }
443               break;
444           
445             case SDL_JOYAXISMOTION:
446               if (event.jaxis.axis == joystick_keymap.x_axis)
447                 {
448                   if (event.jaxis.value < -joystick_keymap.dead_zone)
449                     input_direction = WEST;
450                   else if (event.jaxis.value > joystick_keymap.dead_zone)
451                     input_direction = EAST;
452                 }
453               else if (event.jaxis.axis == joystick_keymap.y_axis)
454                 {
455                   if (event.jaxis.value > joystick_keymap.dead_zone)
456                     input_direction = SOUTH;
457                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
458                     input_direction = NORTH;
459                 }
460               break;
461
462             case SDL_JOYBUTTONDOWN:
463               if (event.jbutton.button == joystick_keymap.b_button)
464                 enter_level = true;
465               else if (event.jbutton.button == joystick_keymap.start_button)
466                 on_escape_press();
467               break;
468
469             default:
470               break;
471             }
472         }
473     }
474
475   if (!Menu::current())
476     {
477       Uint8 *keystate = SDL_GetKeyState(NULL);
478   
479       if (keystate[SDLK_LEFT])
480         input_direction = WEST;
481       else if (keystate[SDLK_RIGHT])
482         input_direction = EAST;
483       else if (keystate[SDLK_UP])
484         input_direction = NORTH;
485       else if (keystate[SDLK_DOWN])
486         input_direction = SOUTH;
487     }
488 }
489
490 Point
491 WorldMap::get_next_tile(Point pos, Direction direction)
492 {
493   switch(direction)
494     {
495     case WEST:
496       pos.x -= 1;
497       break;
498     case EAST:
499       pos.x += 1;
500       break;
501     case NORTH:
502       pos.y -= 1;
503       break;
504     case SOUTH:
505       pos.y += 1;
506       break;
507     case NONE:
508       break;
509     }
510   return pos;
511 }
512
513 bool
514 WorldMap::path_ok(Direction direction, Point old_pos, Point* new_pos)
515 {
516   *new_pos = get_next_tile(old_pos, direction);
517
518   if (!(new_pos->x >= 0 && new_pos->x < width
519         && new_pos->y >= 0 && new_pos->y < height))
520     { // New position is outsite the tilemap
521       return false;
522     }
523   else
524     { // Check if we the tile allows us to go to new_pos
525       switch(direction)
526         {
527         case WEST:
528           return (at(old_pos)->west && at(*new_pos)->east);
529
530         case EAST:
531           return (at(old_pos)->east && at(*new_pos)->west);
532
533         case NORTH:
534           return (at(old_pos)->north && at(*new_pos)->south);
535
536         case SOUTH:
537           return (at(old_pos)->south && at(*new_pos)->north);
538
539         case NONE:
540           assert(!"path_ok() can't work if direction is NONE");
541         }
542       return false;
543     }
544 }
545
546 void
547 WorldMap::update()
548 {
549   if (enter_level && !tux->is_moving())
550     {
551       Level* level = at_level();
552       if (level)
553         {
554           if (level->x == tux->get_tile_pos().x && 
555               level->y == tux->get_tile_pos().y)
556             {
557               std::cout << "Enter the current level: " << level->name << std::endl;;
558               GameSession session(datadir +  "levels/" + level->name,
559                                   1, ST_GL_LOAD_LEVEL_FILE);
560
561               switch (session.run())
562                 {
563                 case GameSession::LEVEL_FINISHED:
564                   level->solved = true;
565                   break;
566                 case GameSession::LEVEL_ABORT:
567                   // Reseting the player_status might be a worthy
568                   // consideration, but I don't think we need it
569                   // 'cause only the bad players will use it to
570                   // 'cheat' a few items and that isn't necesarry a
571                   // bad thing (ie. better they continue that way,
572                   // then stop playing the game all together since it
573                   // is to hard)
574                   break;
575                 case GameSession::GAME_OVER:
576                   quit = true;
577                   break;
578                 case GameSession::NONE:
579                   // Should never be reached 
580                   break;
581                 }
582
583               music_manager->play_music(song);
584               Menu::set_current(0);
585               if (!savegame_file.empty())
586                 savegame(savegame_file);
587               return;
588             }
589         }
590       else
591         {
592           std::cout << "Nothing to enter at: "
593                     << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
594         }
595     }
596   else
597     {
598       tux->set_direction(input_direction);
599       tux->update(0.33f);
600     }
601   
602   Menu* menu = Menu::current();
603   if(menu)
604     {
605       menu->action();
606
607       if(menu == worldmap_menu)
608         {
609           switch (worldmap_menu->check())
610             {
611             case MNID_RETURNWORLDMAP: // Return to game
612               break;
613             case MNID_SAVEGAME:
614               if (!savegame_file.empty())
615                 savegame(savegame_file);
616               break;
617                 
618             case MNID_QUITWORLDMAP: // Quit Worldmap
619               quit = true;
620               break;
621             }
622         }
623       else if(menu == options_menu)
624         {
625           process_options_menu();
626         }
627     }
628 }
629
630 Tile*
631 WorldMap::at(Point p)
632 {
633   assert(p.x >= 0 
634          && p.x < width
635          && p.y >= 0
636          && p.y < height);
637
638   return TileManager::instance()->get(tilemap[width * p.y + p.x]);
639 }
640
641 WorldMap::Level*
642 WorldMap::at_level()
643 {
644   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
645     {
646       if (i->x == tux->get_tile_pos().x && 
647           i->y == tux->get_tile_pos().y)
648         return &*i; 
649     }
650
651   return 0;
652 }
653
654
655 void
656 WorldMap::draw(const Point& offset)
657 {
658   for(int y = 0; y < height; ++y)
659     for(int x = 0; x < width; ++x)
660       {
661         Tile* tile = at(Point(x, y));
662         tile->sprite->draw(x*32 + offset.x,
663                            y*32 + offset.y);
664       }
665   
666   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
667     {
668       if (i->solved)
669         leveldot_green->draw(i->x*32 + offset.x, 
670                              i->y*32 + offset.y);
671       else
672         leveldot_red->draw(i->x*32 + offset.x, 
673                            i->y*32 + offset.y);        
674     }
675
676   tux->draw(offset);
677   draw_status();
678 }
679
680 void
681 WorldMap::draw_status()
682 {
683   char str[80];
684   sprintf(str, "%d", player_status.score);
685   white_text->draw("SCORE", 0, 0);
686   gold_text->draw(str, 96, 0);
687
688   sprintf(str, "%d", player_status.distros);
689   white_text->draw_align("COINS", 320-64, 0,  A_LEFT, A_TOP);
690   gold_text->draw_align(str, 320+64, 0, A_RIGHT, A_TOP);
691
692   white_text->draw("LIVES", 480, 0);
693   if (player_status.lives >= 5)
694     {
695       sprintf(str, "%dx", player_status.lives);
696       gold_text->draw(str, 585, 0);
697       tux_life->draw(565+(18*3), 0);
698     }
699   else
700     {
701       for(int i= 0; i < player_status.lives; ++i)
702         tux_life->draw(565+(18*i),0);
703     }
704
705   if (!tux->is_moving())
706     {
707       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
708         {
709           if (i->x == tux->get_tile_pos().x && 
710               i->y == tux->get_tile_pos().y)
711             {
712               white_text->draw_align(i->title.c_str(), screen->w/2, screen->h,  A_HMIDDLE, A_BOTTOM);
713               break;
714             }
715         }
716     }
717 }
718
719 void
720 WorldMap::display()
721 {
722   Menu::set_current(0);
723
724   quit = false;
725
726   song = music_manager->load_music(datadir +  "/music/" + music);
727   music_manager->play_music(song);
728
729   while(!quit) {
730     Point tux_pos = tux->get_pos();
731     if (1)
732       {
733         offset.x = -tux_pos.x + screen->w/2;
734         offset.y = -tux_pos.y + screen->h/2;
735
736         if (offset.x > 0) offset.x = 0;
737         if (offset.y > 0) offset.y = 0;
738
739         if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
740         if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
741       } 
742
743     draw(offset);
744     get_input();
745     update();
746
747   if(Menu::current())
748     {
749       Menu::current()->draw();
750       mouse_cursor->draw();
751     }
752     flipscreen();
753
754     SDL_Delay(20);
755   }
756 }
757
758 void
759 WorldMap::savegame(const std::string& filename)
760 {
761   std::cout << "savegame: " << filename << std::endl;
762   std::ofstream out(filename.c_str());
763
764   int nb_solved_levels = 0;
765   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
766     {
767       if (i->solved)
768         ++nb_solved_levels;
769     }
770
771   out << "(supertux-savegame\n"
772       << "  (version 1)\n"
773       << "  (title  \"Icyisland - " << nb_solved_levels << "/" << levels.size() << "\")\n"
774       << "  (lives   " << player_status.lives << ")\n"
775       << "  (score   " << player_status.score << ")\n"
776       << "  (distros " << player_status.distros << ")\n"
777       << "  (tux     (x " << tux->get_tile_pos().x << ") (y " << tux->get_tile_pos().y << ")"
778       << " (back \"" << direction_to_string(tux->back_direction) << "\"))\n"
779       << "  (levels\n";
780   
781   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
782     {
783       if (i->solved)
784         {
785           out << "     (level (name \"" << i->name << "\")\n"
786               << "            (solved #t))\n";
787         }
788     }  
789
790   out << "   )\n"
791       << " )\n\n;; EOF ;;" << std::endl;
792 }
793
794 void
795 WorldMap::loadgame(const std::string& filename)
796 {
797   std::cout << "loadgame: " << filename << std::endl;
798   savegame_file = filename;
799
800   if (access(filename.c_str(), F_OK) == 0)
801     {
802       lisp_object_t* cur = lisp_read_from_file(filename);
803
804       if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
805         return;
806
807       cur = lisp_cdr(cur);
808       LispReader reader(cur);
809   
810       reader.read_int("lives",  &player_status.lives);
811       reader.read_int("score",  &player_status.score);
812       reader.read_int("distros", &player_status.distros);
813
814       if (player_status.lives < 0)
815         player_status.lives = START_LIVES;
816
817       lisp_object_t* tux_cur = 0;
818       if (reader.read_lisp("tux", &tux_cur))
819         {
820           Point p;
821           std::string back_str = "none";
822
823           LispReader tux_reader(tux_cur);
824           tux_reader.read_int("x", &p.x);
825           tux_reader.read_int("y", &p.y);
826           tux_reader.read_string("back", &back_str);
827           
828           tux->back_direction = string_to_direction(back_str);      
829           tux->set_tile_pos(p);
830         }
831
832       lisp_object_t* level_cur = 0;
833       if (reader.read_lisp("levels", &level_cur))
834         {
835           while(level_cur)
836             {
837               lisp_object_t* sym  = lisp_car(lisp_car(level_cur));
838               lisp_object_t* data = lisp_cdr(lisp_car(level_cur));
839
840               if (strcmp(lisp_symbol(sym), "level") == 0)
841                 {
842                   std::string name;
843                   bool solved = false;
844
845                   LispReader level_reader(data);
846                   level_reader.read_string("name",   &name);
847                   level_reader.read_bool("solved", &solved);
848
849                   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
850                     {
851                       if (name == i->name)
852                         i->solved = solved;
853                     }
854                 }
855
856               level_cur = lisp_cdr(level_cur);
857             }
858         }
859     }
860 }
861
862 } // namespace WorldMapNS
863
864 /* Local Variables: */
865 /* mode:c++ */
866 /* End: */
867