4f9934fd0f461baa6e7b9f72d443f33d8d6f20ac
[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)
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   quit = false;
210   width  = 20;
211   height = 15;
212
213   level_sprite = new Surface(datadir +  "/images/worldmap/levelmarker.png", USE_ALPHA);
214   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", USE_ALPHA);
215   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", USE_ALPHA);
216
217   input_direction = NONE;
218   enter_level = false;
219
220   name = "<no name>";
221   music = "SALCON.MOD";
222   song = 0;
223
224   load_map();
225 }
226
227 WorldMap::~WorldMap()
228 {
229   delete tux;
230 }
231
232 void
233 WorldMap::load_map()
234 {
235   std::string filename = datadir +  "levels/default/worldmap.stwm";
236   
237   lisp_object_t* root_obj = lisp_read_from_file(filename);
238   if (!root_obj)
239     st_abort("Couldn't load file", filename);
240   
241   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
242     {
243       lisp_object_t* cur = lisp_cdr(root_obj);
244
245       while(!lisp_nil_p(cur))
246         {
247           lisp_object_t* element = lisp_car(cur);
248
249           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
250             {
251               LispReader reader(lisp_cdr(element));
252               reader.read_int("width",  &width);
253               reader.read_int("height", &height);
254               reader.read_int_vector("data", &tilemap);
255             }
256           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
257             {
258               LispReader reader(lisp_cdr(element));
259               reader.read_string("name",  &name);
260               reader.read_string("music", &music);
261             }
262           else if (strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
263             {
264               lisp_object_t* cur = lisp_cdr(element);
265               
266               while(!lisp_nil_p(cur))
267                 {
268                   lisp_object_t* element = lisp_car(cur);
269                   
270                   if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
271                     {
272                       Level level;
273                       LispReader reader(lisp_cdr(element));
274                       level.solved = false;
275                       reader.read_string("name",  &level.name);
276                       reader.read_int("x", &level.x);
277                       reader.read_int("y", &level.y);
278                       levels.push_back(level);
279                     }
280                   
281                   cur = lisp_cdr(cur);      
282                 }
283             }
284           else
285             {
286               
287             }
288           
289           cur = lisp_cdr(cur);
290         }
291     }
292 }
293
294 void
295 WorldMap::get_input()
296 {
297   enter_level = false;
298   input_direction = NONE;
299    
300   SDL_Event event;
301   while (SDL_PollEvent(&event))
302     {
303       if(show_menu)
304         {
305           current_menu->event(event);
306         }
307       else
308         {
309           switch(event.type)
310             {
311             case SDL_QUIT:
312               quit = true;
313               break;
314           
315             case SDL_KEYDOWN:
316               switch(event.key.keysym.sym)
317                 {
318                 case SDLK_ESCAPE:
319                   Menu::set_current(worldmap_menu);
320                   show_menu = !show_menu;
321                   break;
322                 case SDLK_LCTRL:
323                 case SDLK_RETURN:
324                   enter_level = true;
325                   break;
326                 default:
327                   break;
328                 }
329               break;
330           
331             case SDL_JOYAXISMOTION:
332               switch(event.jaxis.axis)
333                 {
334                 case JOY_X:
335                   if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
336                     input_direction = WEST;
337                   else if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
338                     input_direction = EAST;
339                   break;
340                 case JOY_Y:
341                   if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
342                     input_direction = SOUTH;
343                   else if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
344                     input_direction = NORTH;
345                   break;
346                 }
347               break;
348
349             case SDL_JOYBUTTONDOWN:
350               if (event.jbutton.button == JOY_B)
351                 enter_level = true;
352               break;
353
354             default:
355               break;
356             }
357         }
358     }
359
360   if (!show_menu)
361     {
362       Uint8 *keystate = SDL_GetKeyState(NULL);
363   
364       if (keystate[SDLK_LEFT])
365         input_direction = WEST;
366       else if (keystate[SDLK_RIGHT])
367         input_direction = EAST;
368       else if (keystate[SDLK_UP])
369         input_direction = NORTH;
370       else if (keystate[SDLK_DOWN])
371         input_direction = SOUTH;
372     }
373 }
374
375 Point
376 WorldMap::get_next_tile(Point pos, Direction direction)
377 {
378   switch(direction)
379     {
380     case WEST:
381       pos.x -= 1;
382       break;
383     case EAST:
384       pos.x += 1;
385       break;
386     case NORTH:
387       pos.y -= 1;
388       break;
389     case SOUTH:
390       pos.y += 1;
391       break;
392     case NONE:
393       break;
394     }
395   return pos;
396 }
397
398 bool
399 WorldMap::path_ok(Direction direction, Point old_pos, Point* new_pos)
400 {
401   *new_pos = get_next_tile(old_pos, direction);
402
403   if (!(new_pos->x >= 0 && new_pos->x < width
404         && new_pos->y >= 0 && new_pos->y < height))
405     { // New position is outsite the tilemap
406       return false;
407     }
408   else
409     { // Check if we the tile allows us to go to new_pos
410       switch(direction)
411         {
412         case WEST:
413           return (at(old_pos)->west && at(*new_pos)->east);
414
415         case EAST:
416           return (at(old_pos)->east && at(*new_pos)->west);
417
418         case NORTH:
419           return (at(old_pos)->north && at(*new_pos)->south);
420
421         case SOUTH:
422           return (at(old_pos)->south && at(*new_pos)->north);
423
424         case NONE:
425           assert(!"path_ok() can't work if direction is NONE");
426         }
427       return false;
428     }
429 }
430
431 void
432 WorldMap::update()
433 {
434   if (enter_level && !tux->is_moving())
435     {
436       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
437         {
438           if (i->x == tux->get_tile_pos().x && 
439               i->y == tux->get_tile_pos().y)
440             {
441               std::cout << "Enter the current level: " << i->name << std::endl;;
442               halt_music();
443               GameSession session(datadir +  "levels/" + i->name,
444                                   1, ST_GL_LOAD_LEVEL_FILE);
445               session.run();
446
447               if (1) // FIXME: insert exit status checker here
448                 i->solved = true;
449
450               play_music(song, 1);
451               show_menu = 0;
452               menu_reset();
453               if (!savegame_file.empty())
454                 savegame(savegame_file);
455               return;
456             }
457         }
458       std::cout << "Nothing to enter at: "
459                 << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
460     }
461   else
462     {
463       tux->set_direction(input_direction);
464       tux->update(0.33f);
465     }
466   
467   if(show_menu)
468     {
469       if(current_menu == worldmap_menu)
470         {
471           switch (worldmap_menu->check())
472             {
473             case 2: // Return to game
474               menu_reset();
475               break;
476             case 5: // Quit Worldmap
477               quit = true;
478               break;
479             }
480         }
481     }
482 }
483
484 Tile*
485 WorldMap::at(Point p)
486 {
487   assert(p.x >= 0 
488          && p.x < width
489          && p.y >= 0
490          && p.y < height);
491   return TileManager::instance()->get(tilemap[width * p.y + p.x]);
492 }
493
494 void
495 WorldMap::draw(const Point& offset)
496 {
497   for(int y = 0; y < height; ++y)
498     for(int x = 0; x < width; ++x)
499       {
500         Tile* tile = at(Point(x, y));
501         tile->sprite->draw(x*32 + offset.x,
502                            y*32 + offset.y);
503       }
504   
505   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
506     {
507       leveldot_green->draw(i->x*32 + offset.x, 
508                            i->y*32 + offset.y);
509     }
510
511   tux->draw(offset);
512   draw_status();
513 }
514
515 void
516 WorldMap::draw_status()
517 {
518   char str[80];
519   sprintf(str, "%d", player_status.score);
520   white_text->draw("SCORE", 0, 0);
521   gold_text->draw(str, 96, 0);
522
523   sprintf(str, "%d", player_status.distros);
524   white_text->draw_align("COINS", 320-64, 0,  A_LEFT, A_TOP);
525   gold_text->draw_align(str, 320+64, 0, A_RIGHT, A_TOP);
526
527   white_text->draw("LIVES", 480, 0);
528   if (player_status.lives >= 5)
529     {
530       sprintf(str, "%dx", player_status.lives);
531       gold_text->draw(str, 585, 0);
532       tux_life->draw(565+(18*3), 0);
533     }
534   else
535     {
536       for(int i= 0; i < player_status.lives; ++i)
537         tux_life->draw(565+(18*i),0);
538     }
539
540   if (!tux->is_moving())
541     {
542       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
543         {
544           if (i->x == tux->get_tile_pos().x && 
545               i->y == tux->get_tile_pos().y)
546             {
547               white_text->draw_align(i->name.c_str(), screen->w/2, screen->h,  A_HMIDDLE, A_BOTTOM);
548               break;
549             }
550         }
551     }
552 }
553
554 void
555 WorldMap::display()
556 {
557   show_menu = 0;
558   menu_reset();
559
560   quit = false;
561
562   song = load_song(datadir +  "/music/" + music);
563   play_music(song, 1);
564
565   while(!quit) {
566     Point tux_pos = tux->get_pos();
567     if (1)
568       {
569         offset.x = -tux_pos.x + screen->w/2;
570         offset.y = -tux_pos.y + screen->h/2;
571
572         if (offset.x > 0) offset.x = 0;
573         if (offset.y > 0) offset.y = 0;
574
575         if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
576         if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
577       } 
578
579     draw(offset);
580     get_input();
581     update();
582
583     menu_process_current();
584     flipscreen();
585
586     SDL_Delay(20);
587   }
588
589   free_music(song);
590 }
591
592 void
593 WorldMap::savegame(const std::string& filename)
594 {
595   std::cout << "savegame: " << filename << std::endl;
596   std::ofstream out(filename.c_str());
597
598   int nb_solved_levels = 0;
599   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
600     {
601       if (i->solved)
602         ++nb_solved_levels;
603     }
604
605   out << "(supertux-savegame\n"
606       << "  (version 1)\n"
607       << "  (title  \"Icyisland - " << nb_solved_levels << "/" << levels.size() << "\")\n"
608       << "  (lives   " << player_status.lives << ")\n"
609       << "  (score   " << player_status.score << ")\n"
610       << "  (distros " << player_status.distros << ")\n"
611       << "  (tux     (x " << tux->get_tile_pos().x << ") (y " << tux->get_tile_pos().y << "))\n"
612       << "  (levels\n";
613   
614   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
615     {
616       if (i->solved)
617         {
618           out << "     (level (name \"" << i->name << "\")\n"
619               << "            (solved #t))\n";
620         }
621     }  
622
623   out << "   )\n"
624       << " )\n\n;; EOF ;;" << std::endl;
625 }
626
627 void
628 WorldMap::loadgame(const std::string& filename)
629 {
630   std::cout << "loadgame: " << filename << std::endl;
631   savegame_file = filename;
632
633   if (access(filename.c_str(), F_OK) == 0)
634     {
635       lisp_object_t* cur = lisp_read_from_file(filename);
636
637       if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
638         return;
639
640       cur = lisp_cdr(cur);
641       LispReader reader(cur);
642   
643       reader.read_int("lives",  &player_status.lives);
644       reader.read_int("score",  &player_status.score);
645       reader.read_int("distros", &player_status.distros);
646
647       lisp_object_t* tux_cur = 0;
648       if (reader.read_lisp("tux", &tux_cur))
649         {
650           Point p;
651           LispReader tux_reader(tux_cur);
652           tux_reader.read_int("x", &p.x);
653           tux_reader.read_int("y", &p.y);
654       
655           tux->set_tile_pos(p);
656         }
657
658       lisp_object_t* level_cur = 0;
659       if (reader.read_lisp("levels", &level_cur))
660         {
661           while(level_cur)
662             {
663               std::string name;
664               bool solved = false;
665               LispReader level_reader(level_cur);
666               level_reader.read_string("name",   &name);
667               level_reader.read_bool("solved", &solved);
668
669               for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
670                 {
671                   if (name == i->name)
672                     i->solved = solved;
673                 }
674
675               level_cur = lisp_cdr(level_cur);
676             }
677         }
678     }
679 }
680
681 } // namespace WorldMapNS
682
683 /* EOF */