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