abf95b23f61ee7543cb9d6e0a4356c90f93a795f
[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 TileManager* TileManager::instance_  = 0;
35
36 TileManager::TileManager()
37 {
38   std::string stwt_filename = datadir +  "images/worldmap/antarctica.stwt";
39   lisp_object_t* root_obj = lisp_read_from_file(stwt_filename);
40  
41   if (!root_obj)
42     st_abort("Couldn't load file", stwt_filename);
43
44   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap-tiles") == 0)
45     {
46       lisp_object_t* cur = lisp_cdr(root_obj);
47
48       while(!lisp_nil_p(cur))
49         {
50           lisp_object_t* element = lisp_car(cur);
51
52           if (strcmp(lisp_symbol(lisp_car(element)), "tile") == 0)
53             {
54               int id = 0;
55               std::string filename = "<invalid>";
56
57               Tile* tile = new Tile;             
58               tile->north = true;
59               tile->east  = true;
60               tile->south = true;
61               tile->west  = true;
62               tile->stop  = true;
63   
64               LispReader reader(lisp_cdr(element));
65               reader.read_int("id",  &id);
66               reader.read_bool("north", &tile->north);
67               reader.read_bool("south", &tile->south);
68               reader.read_bool("west",  &tile->west);
69               reader.read_bool("east",  &tile->east);
70               reader.read_bool("stop",  &tile->stop);
71               reader.read_string("image",  &filename);
72
73               tile->sprite = new Surface(
74                            datadir +  "/images/worldmap/" + filename, 
75                            USE_ALPHA);
76
77               if (id >= int(tiles.size()))
78                 tiles.resize(id+1);
79
80               tiles[id] = tile;
81             }
82           else
83             {
84               puts("Unhandled symbol");
85             }
86
87           cur = lisp_cdr(cur);
88         }
89     }
90   else
91     {
92       assert(0);
93     }
94 }
95
96 Tile*
97 TileManager::get(int i)
98 {
99   assert(i >=0 && i < int(tiles.size()));
100   return tiles[i];
101 }
102
103 Tux::Tux(WorldMap* worldmap_)
104   : worldmap(worldmap_)
105 {
106   sprite = new Surface(datadir +  "/images/worldmap/tux.png", USE_ALPHA);
107   offset = 0;
108   moving = false;
109   tile_pos.x = 5;
110   tile_pos.y = 5;
111   direction = NONE;
112   input_direction = NONE;
113 }
114
115 void
116 Tux::draw(const Point& offset)
117 {
118   Point pos = get_pos();
119   sprite->draw(pos.x + offset.x, 
120                pos.y + offset.y);
121 }
122
123
124 Point
125 Tux::get_pos()
126 {
127   float x = tile_pos.x * 32;
128   float y = tile_pos.y * 32;
129
130   switch(direction)
131     {
132     case WEST:
133       x -= offset - 32;
134       break;
135     case EAST:
136       x += offset - 32;
137       break;
138     case NORTH:
139       y -= offset - 32;
140       break;
141     case SOUTH:
142       y += offset - 32;
143       break;
144     case NONE:
145       break;
146     }
147   
148   return Point((int)x, (int)y); 
149 }
150
151 void
152 Tux::stop()
153 {
154   offset = 0;
155   direction = NONE;
156   moving = false;
157 }
158
159 void
160 Tux::update(float delta)
161 {
162   if (!moving)
163     {
164       if (input_direction != NONE)
165         { // We got a new direction, so lets start walking when possible
166           Point next_tile;
167           if (worldmap->path_ok(input_direction, tile_pos, &next_tile))
168             {
169               tile_pos = next_tile;
170               moving = true;
171               direction = input_direction;
172             }
173         }
174     }
175   else
176     {
177       // Let tux walk a few pixels (20 pixel/sec)
178       offset += 20.0f * delta;
179
180       if (offset > 32)
181         { // We reached the next tile, so we check what to do now
182           offset -= 32;
183
184           if (worldmap->at(tile_pos)->stop || worldmap->at_level())
185             {
186               stop();
187             }
188           else
189             {
190               Point next_tile;
191               if (worldmap->path_ok(direction, tile_pos, &next_tile))
192                 {
193                   tile_pos = next_tile;
194                 }
195               else
196                 {
197                   puts("Tilemap data is buggy");
198                   stop();
199                 }
200             }
201         }
202     }
203 }
204
205 WorldMap::WorldMap()
206 {
207   tux = new Tux(this);
208
209   width  = 20;
210   height = 15;
211
212   level_sprite = new Surface(datadir +  "/images/worldmap/levelmarker.png", USE_ALPHA);
213   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", USE_ALPHA);
214   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", USE_ALPHA);
215
216   input_direction = NONE;
217   enter_level = false;
218
219   name = "<no name>";
220   music = "SALCON.MOD";
221   song = 0;
222
223   load_map();
224 }
225
226 WorldMap::~WorldMap()
227 {
228   delete tux;
229 }
230
231 void
232 WorldMap::load_map()
233 {
234   std::string filename = datadir +  "levels/default/worldmap.stwm";
235   
236   lisp_object_t* root_obj = lisp_read_from_file(filename);
237   if (!root_obj)
238     st_abort("Couldn't load file", filename);
239   
240   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
241     {
242       lisp_object_t* cur = lisp_cdr(root_obj);
243
244       while(!lisp_nil_p(cur))
245         {
246           lisp_object_t* element = lisp_car(cur);
247
248           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
249             {
250               LispReader reader(lisp_cdr(element));
251               reader.read_int("width",  &width);
252               reader.read_int("height", &height);
253               reader.read_int_vector("data", &tilemap);
254             }
255           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
256             {
257               LispReader reader(lisp_cdr(element));
258               reader.read_string("name",  &name);
259               reader.read_string("music", &music);
260             }
261           else if (strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
262             {
263               lisp_object_t* cur = lisp_cdr(element);
264               
265               while(!lisp_nil_p(cur))
266                 {
267                   lisp_object_t* element = lisp_car(cur);
268                   
269                   if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
270                     {
271                       Level level;
272                       LispReader reader(lisp_cdr(element));
273                       level.solved = false;
274                       reader.read_string("name",  &level.name);
275                       reader.read_int("x", &level.x);
276                       reader.read_int("y", &level.y);
277                       levels.push_back(level);
278                     }
279                   
280                   cur = lisp_cdr(cur);      
281                 }
282             }
283           else
284             {
285               
286             }
287           
288           cur = lisp_cdr(cur);
289         }
290     }
291 }
292
293 void
294 WorldMap::get_input()
295 {
296   enter_level = false;
297   input_direction = NONE;
298    
299   SDL_Event event;
300   while (SDL_PollEvent(&event))
301     {
302       if(show_menu)
303         {
304           current_menu->event(event);
305         }
306       else
307         {
308           switch(event.type)
309             {
310             case SDL_QUIT:
311               st_abort("Received window close", "");
312               break;
313           
314             case SDL_KEYDOWN:
315               switch(event.key.keysym.sym)
316                 {
317                 case SDLK_ESCAPE:
318                   Menu::set_current(worldmap_menu);
319                   show_menu = !show_menu;
320                   break;
321                 case SDLK_LCTRL:
322                 case SDLK_RETURN:
323                   enter_level = true;
324                   break;
325                 default:
326                   break;
327                 }
328               break;
329           
330             case SDL_JOYAXISMOTION:
331               switch(event.jaxis.axis)
332                 {
333                 case JOY_X:
334                   if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
335                     input_direction = WEST;
336                   else if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
337                     input_direction = EAST;
338                   break;
339                 case JOY_Y:
340                   if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
341                     input_direction = SOUTH;
342                   else if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
343                     input_direction = NORTH;
344                   break;
345                 }
346               break;
347
348             case SDL_JOYBUTTONDOWN:
349               if (event.jbutton.button == JOY_B)
350                 enter_level = true;
351               break;
352
353             default:
354               break;
355             }
356         }
357     }
358
359   if (!show_menu)
360     {
361       Uint8 *keystate = SDL_GetKeyState(NULL);
362   
363       if (keystate[SDLK_LEFT])
364         input_direction = WEST;
365       else if (keystate[SDLK_RIGHT])
366         input_direction = EAST;
367       else if (keystate[SDLK_UP])
368         input_direction = NORTH;
369       else if (keystate[SDLK_DOWN])
370         input_direction = SOUTH;
371     }
372 }
373
374 Point
375 WorldMap::get_next_tile(Point pos, Direction direction)
376 {
377   switch(direction)
378     {
379     case WEST:
380       pos.x -= 1;
381       break;
382     case EAST:
383       pos.x += 1;
384       break;
385     case NORTH:
386       pos.y -= 1;
387       break;
388     case SOUTH:
389       pos.y += 1;
390       break;
391     case NONE:
392       break;
393     }
394   return pos;
395 }
396
397 bool
398 WorldMap::path_ok(Direction direction, Point old_pos, Point* new_pos)
399 {
400   *new_pos = get_next_tile(old_pos, direction);
401
402   if (!(new_pos->x >= 0 && new_pos->x < width
403         && new_pos->y >= 0 && new_pos->y < height))
404     { // New position is outsite the tilemap
405       return false;
406     }
407   else
408     { // Check if we the tile allows us to go to new_pos
409       switch(direction)
410         {
411         case WEST:
412           return (at(old_pos)->west && at(*new_pos)->east);
413
414         case EAST:
415           return (at(old_pos)->east && at(*new_pos)->west);
416
417         case NORTH:
418           return (at(old_pos)->north && at(*new_pos)->south);
419
420         case SOUTH:
421           return (at(old_pos)->south && at(*new_pos)->north);
422
423         case NONE:
424           assert(!"path_ok() can't work if direction is NONE");
425         }
426       return false;
427     }
428 }
429
430 void
431 WorldMap::update()
432 {
433   if (enter_level && !tux->is_moving())
434     {
435       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
436         {
437           if (i->x == tux->get_tile_pos().x && 
438               i->y == tux->get_tile_pos().y)
439             {
440               std::cout << "Enter the current level: " << i->name << std::endl;;
441               halt_music();
442               GameSession session(datadir +  "levels/" + i->name,
443                                   1, ST_GL_LOAD_LEVEL_FILE);
444               session.run();
445
446               if (1) // FIXME: insert exit status checker here
447                 i->solved = true;
448
449               play_music(song, 1);
450               show_menu = 0;
451               menu_reset();
452               if (!savegame_file.empty())
453                 savegame(savegame_file);
454               return;
455             }
456         }
457       std::cout << "Nothing to enter at: "
458                 << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
459     }
460   else
461     {
462       tux->set_direction(input_direction);
463       tux->update(0.33f);
464     }
465   
466   if(show_menu)
467     {
468       if(current_menu == worldmap_menu)
469         {
470           switch (worldmap_menu->check())
471             {
472             case 2: // Return to game
473               menu_reset();
474               break;
475             case 5: // Quit Worldmap
476               quit = true;
477               break;
478             }
479         }
480     }
481 }
482
483 Tile*
484 WorldMap::at(Point p)
485 {
486   assert(p.x >= 0 
487          && p.x < width
488          && p.y >= 0
489          && p.y < height);
490   return TileManager::instance()->get(tilemap[width * p.y + p.x]);
491 }
492
493 bool
494 WorldMap::at_level()
495 {
496   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
497     {
498       if (i->x == tux->get_tile_pos().x && 
499           i->y == tux->get_tile_pos().y)
500            return true; 
501     }
502
503   return false;
504 }
505
506
507 void
508 WorldMap::draw(const Point& offset)
509 {
510   for(int y = 0; y < height; ++y)
511     for(int x = 0; x < width; ++x)
512       {
513         Tile* tile = at(Point(x, y));
514         tile->sprite->draw(x*32 + offset.x,
515                            y*32 + offset.y);
516       }
517   
518   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
519     {
520       leveldot_green->draw(i->x*32 + offset.x, 
521                            i->y*32 + offset.y);
522     }
523
524   tux->draw(offset);
525   draw_status();
526 }
527
528 void
529 WorldMap::draw_status()
530 {
531   char str[80];
532   sprintf(str, "%d", player_status.score);
533   white_text->draw("SCORE", 0, 0);
534   gold_text->draw(str, 96, 0);
535
536   sprintf(str, "%d", player_status.distros);
537   white_text->draw_align("COINS", 320-64, 0,  A_LEFT, A_TOP);
538   gold_text->draw_align(str, 320+64, 0, A_RIGHT, A_TOP);
539
540   white_text->draw("LIVES", 480, 0);
541   if (player_status.lives >= 5)
542     {
543       sprintf(str, "%dx", player_status.lives);
544       gold_text->draw(str, 585, 0);
545       tux_life->draw(565+(18*3), 0);
546     }
547   else
548     {
549       for(int i= 0; i < player_status.lives; ++i)
550         tux_life->draw(565+(18*i),0);
551     }
552
553   if (!tux->is_moving())
554     {
555       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
556         {
557           if (i->x == tux->get_tile_pos().x && 
558               i->y == tux->get_tile_pos().y)
559             {
560               white_text->draw_align(i->name.c_str(), screen->w/2, screen->h,  A_HMIDDLE, A_BOTTOM);
561               break;
562             }
563         }
564     }
565 }
566
567 void
568 WorldMap::display()
569 {
570   show_menu = 0;
571   menu_reset();
572
573   quit = false;
574
575   song = load_song(datadir +  "/music/" + music);
576   play_music(song, 1);
577
578   while(!quit) {
579     Point tux_pos = tux->get_pos();
580     if (1)
581       {
582         offset.x = -tux_pos.x + screen->w/2;
583         offset.y = -tux_pos.y + screen->h/2;
584
585         if (offset.x > 0) offset.x = 0;
586         if (offset.y > 0) offset.y = 0;
587
588         if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
589         if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
590       } 
591
592     draw(offset);
593     get_input();
594     update();
595
596     menu_process_current();
597     flipscreen();
598
599     SDL_Delay(20);
600   }
601
602   free_music(song);
603 }
604
605 void
606 WorldMap::savegame(const std::string& filename)
607 {
608   std::cout << "savegame: " << filename << std::endl;
609   std::ofstream out(filename.c_str());
610
611   int nb_solved_levels = 0;
612   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
613     {
614       if (i->solved)
615         ++nb_solved_levels;
616     }
617
618   out << "(supertux-savegame\n"
619       << "  (version 1)\n"
620       << "  (title  \"Icyisland - " << nb_solved_levels << "/" << levels.size() << "\")\n"
621       << "  (lives   " << player_status.lives << ")\n"
622       << "  (score   " << player_status.score << ")\n"
623       << "  (distros " << player_status.distros << ")\n"
624       << "  (tux     (x " << tux->get_tile_pos().x << ") (y " << tux->get_tile_pos().y << "))\n"
625       << "  (levels\n";
626   
627   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
628     {
629       if (i->solved)
630         {
631           out << "     (level (name \"" << i->name << "\")\n"
632               << "            (solved #t))\n";
633         }
634     }  
635
636   out << "   )\n"
637       << " )\n\n;; EOF ;;" << std::endl;
638 }
639
640 void
641 WorldMap::loadgame(const std::string& filename)
642 {
643   std::cout << "loadgame: " << filename << std::endl;
644   savegame_file = filename;
645
646   if (access(filename.c_str(), F_OK) == 0)
647     {
648       lisp_object_t* cur = lisp_read_from_file(filename);
649
650       if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
651         return;
652
653       cur = lisp_cdr(cur);
654       LispReader reader(cur);
655   
656       reader.read_int("lives",  &player_status.lives);
657       reader.read_int("score",  &player_status.score);
658       reader.read_int("distros", &player_status.distros);
659
660       lisp_object_t* tux_cur = 0;
661       if (reader.read_lisp("tux", &tux_cur))
662         {
663           Point p;
664           LispReader tux_reader(tux_cur);
665           tux_reader.read_int("x", &p.x);
666           tux_reader.read_int("y", &p.y);
667       
668           tux->set_tile_pos(p);
669         }
670
671       lisp_object_t* level_cur = 0;
672       if (reader.read_lisp("levels", &level_cur))
673         {
674           while(level_cur)
675             {
676               std::string name;
677               bool solved = false;
678               LispReader level_reader(level_cur);
679               level_reader.read_string("name",   &name);
680               level_reader.read_bool("solved", &solved);
681
682               for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
683                 {
684                   if (name == i->name)
685                     i->solved = solved;
686                 }
687
688               level_cur = lisp_cdr(level_cur);
689             }
690         }
691     }
692 }
693
694 } // namespace WorldMapNS
695
696 /* EOF */