4 // Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
5 // Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
6 // Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License
10 // as published by the Free Software Foundation; either version 2
11 // of the License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
38 #include <sys/types.h>
42 #include "app/globals.h"
44 #include "video/screen.h"
45 #include "app/setup.h"
50 #include "player_status.h"
51 #include "object/particlesystem.h"
52 #include "object/background.h"
53 #include "object/tilemap.h"
54 #include "object/camera.h"
55 #include "object/player.h"
56 #include "lisp/lisp.h"
57 #include "lisp/parser.h"
58 #include "resources.h"
59 #include "app/gettext.h"
62 #include "statistics.h"
64 #include "object/fireworks.h"
65 #include "textscroller.h"
67 GameSession* GameSession::current_ = 0;
69 bool compare_last(std::string& haystack, std::string needle)
71 int haystack_size = haystack.size();
72 int needle_size = needle.size();
74 if(haystack_size < needle_size)
77 if(haystack.compare(haystack_size-needle_size, needle_size, needle) == 0)
82 GameSession::GameSession(const std::string& levelfile_, int mode,
83 Statistics* statistics)
84 : level(0), currentsector(0), st_gl_mode(mode),
85 end_sequence(NO_ENDSEQUENCE), levelfile(levelfile_),
86 best_level_statistics(statistics)
93 context = new DrawingContext();
99 GameSession::restart_level()
102 exit_status = ES_NONE;
103 end_sequence = NO_ENDSEQUENCE;
111 level->load(levelfile);
113 global_stats.reset();
114 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
115 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
116 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
118 if(reset_sector != "") {
119 currentsector = level->get_sector(reset_sector);
121 std::stringstream msg;
122 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
123 throw std::runtime_error(msg.str());
125 currentsector->activate(reset_pos);
127 currentsector = level->get_sector("main");
129 throw std::runtime_error("Couldn't find main sector");
130 currentsector->activate("main");
133 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
137 currentsector->play_music(LEVEL_MUSIC);
140 GameSession::~GameSession()
147 GameSession::levelintro()
149 SoundManager::get()->halt_music();
153 DrawingContext context;
154 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
155 i != currentsector->gameobjects.end(); ++i) {
156 Background* background = dynamic_cast<Background*> (*i);
158 background->draw(context);
162 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
163 // CENTER_ALLIGN, LAYER_FOREGROUND1);
164 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
167 sprintf(str, "TUX x %d", player_status.lives);
168 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
169 CENTER_ALLIGN, LAYER_FOREGROUND1);
171 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
172 //TODO make author check case/blank-insensitive
173 context.draw_text(white_small_text,
174 std::string(_("contributed by ")) + level->get_author(),
175 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
178 if(best_level_statistics != NULL)
179 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
181 context.do_drawing();
184 wait_for_event(event,1000,3000,true);
189 GameSession::start_timers()
191 time_left.start(level->timelimit);
196 GameSession::on_escape_press()
198 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
199 return; // don't let the player open the menu, when he is dying
204 if(st_gl_mode == ST_GL_TEST) {
205 exit_status = ES_LEVEL_ABORT;
206 } else if (!Menu::current()) {
207 Menu::set_current(game_menu);
208 Ticks::pause_start();
213 GameSession::process_events()
215 if (end_sequence != NO_ENDSEQUENCE)
217 Player& tux = *currentsector->player;
219 tux.input.fire = false;
220 tux.input.left = false;
221 tux.input.right = true;
222 tux.input.down = false;
224 if (int(last_x_pos) == int(tux.get_pos().x))
227 tux.input.up = false;
229 last_x_pos = tux.get_pos().x;
232 while (SDL_PollEvent(&event))
234 /* Check for menu-events, if the menu is shown */
237 Menu::current()->event(event);
244 case SDL_QUIT: /* Quit event - quit: */
245 Termination::abort("Received window close", "");
248 case SDL_KEYDOWN: /* A keypress! */
250 SDLKey key = event.key.keysym.sym;
254 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
262 case SDL_JOYBUTTONDOWN:
263 if (event.jbutton.button == joystick_keymap.start_button)
271 if(!Menu::current() && !game_pause)
275 while (SDL_PollEvent(&event))
277 /* Check for menu-events, if the menu is shown */
280 Menu::current()->event(event);
286 Player& tux = *currentsector->player;
290 case SDL_QUIT: /* Quit event - quit: */
291 Termination::abort("Received window close", "");
294 case SDL_KEYDOWN: /* A keypress! */
296 SDLKey key = event.key.keysym.sym;
298 if(tux.key_event(key, true))
303 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
311 case SDL_KEYUP: /* A keyrelease! */
313 SDLKey key = event.key.keysym.sym;
315 if(tux.key_event(key, false))
324 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
325 tux.get_pos().x, tux.get_pos().y);
326 context->draw_text(white_text, buf,
327 Vector(0, SCREEN_HEIGHT - white_text->get_height()),
328 LEFT_ALLIGN, LAYER_FOREGROUND1);
329 context->do_drawing();
336 // "lifeup" cheat activates pause cause of the 'p'
337 // so work around to ignore it
338 if(compare_last(last_keys, "lifeu"))
349 Ticks::pause_start();
358 /* Check if chacrater is ASCII */
360 if((event.key.keysym.unicode & 0xFF80) == 0)
362 ch[0] = event.key.keysym.unicode & 0x7F;
365 last_keys.append(ch); // add to cheat keys
369 case SDL_JOYAXISMOTION:
370 if (event.jaxis.axis == joystick_keymap.x_axis)
372 if (event.jaxis.value < -joystick_keymap.dead_zone)
374 tux.input.left = true;
375 tux.input.right = false;
377 else if (event.jaxis.value > joystick_keymap.dead_zone)
379 tux.input.left = false;
380 tux.input.right = true;
384 tux.input.left = false;
385 tux.input.right = false;
388 else if (event.jaxis.axis == joystick_keymap.y_axis)
390 if (event.jaxis.value > joystick_keymap.dead_zone)
393 tux.input.down = false;
395 else if (event.jaxis.value < -joystick_keymap.dead_zone)
397 tux.input.up = false;
398 tux.input.down = true;
402 tux.input.up = false;
403 tux.input.down = false;
408 case SDL_JOYHATMOTION:
409 if(event.jhat.value & SDL_HAT_UP) {
411 tux.input.down = false;
412 } else if(event.jhat.value & SDL_HAT_DOWN) {
413 tux.input.up = false;
414 tux.input.down = true;
415 } else if(event.jhat.value & SDL_HAT_LEFT) {
416 tux.input.left = true;
417 tux.input.right = false;
418 } else if(event.jhat.value & SDL_HAT_RIGHT) {
419 tux.input.left = false;
420 tux.input.right = true;
421 } else if(event.jhat.value == SDL_HAT_CENTERED) {
422 tux.input.left = false;
423 tux.input.right = false;
424 tux.input.up = false;
425 tux.input.down = false;
429 case SDL_JOYBUTTONDOWN:
430 // FIXME: I assume we have to set old_jump and stuff here?!?
431 if (event.jbutton.button == joystick_keymap.a_button)
432 tux.input.jump = true;
433 else if (event.jbutton.button == joystick_keymap.b_button)
434 tux.input.fire = true;
435 else if (event.jbutton.button == joystick_keymap.start_button)
438 case SDL_JOYBUTTONUP:
439 if (event.jbutton.button == joystick_keymap.a_button)
440 tux.input.jump = false;
441 else if (event.jbutton.button == joystick_keymap.b_button)
442 tux.input.fire = false;
454 GameSession::handle_cheats()
456 Player& tux = *currentsector->player;
458 // Cheating words (the goal of this is really for debugging,
459 // but could be used for some cheating, nothing wrong with that)
460 if(compare_last(last_keys, "grow")) {
461 tux.set_bonus(GROWUP_BONUS, false);
464 if(compare_last(last_keys, "fire")) {
465 tux.set_bonus(FIRE_BONUS, false);
468 if(compare_last(last_keys, "ice")) {
469 tux.set_bonus(ICE_BONUS, false);
472 if(compare_last(last_keys, "lifeup")) {
473 player_status.lives++;
476 if(compare_last(last_keys, "lifedown")) {
477 player_status.lives--;
480 if(compare_last(last_keys, "grease")) {
481 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
484 if(compare_last(last_keys, "invincible")) {
485 // be invincle for the rest of the level
486 tux.invincible_timer.start(10000);
489 if(compare_last(last_keys, "shrink")) {
491 tux.kill(tux.SHRINK);
494 if(compare_last(last_keys, "kill")) {
495 // kill Tux, but without losing a life
496 player_status.lives++;
500 if(compare_last(last_keys, "grid")) {
502 debug_grid = !debug_grid;
505 if(compare_last(last_keys, "hover")) {
506 // toggle hover ability on/off
507 tux.enable_hover = !tux.enable_hover;
510 if(compare_last(last_keys, "gotoend")) {
511 // goes to the end of the level
513 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
514 currentsector->camera->reset(
515 Vector(tux.get_pos().x, tux.get_pos().y));
518 if(compare_last(last_keys, "finish")) {
519 // finish current sector
520 exit_status = ES_LEVEL_FINISHED;
521 // don't add points to stats though...
523 // temporary to help player's choosing a flapping
524 if(compare_last(last_keys, "marek")) {
525 tux.flapping_mode = Player::MAREK_FLAP;
528 if(compare_last(last_keys, "ricardo")) {
529 tux.flapping_mode = Player::RICARDO_FLAP;
532 if(compare_last(last_keys, "ryan")) {
533 tux.flapping_mode = Player::RYAN_FLAP;
539 GameSession::check_end_conditions()
541 Player* tux = currentsector->player;
544 if(end_sequence && endsequence_timer.check()) {
545 exit_status = ES_LEVEL_FINISHED;
547 } else if (!end_sequence && tux->is_dead()) {
548 if (player_status.lives < 0) { // No more lives!?
549 exit_status = ES_GAME_OVER;
550 } else { // Still has lives, so reset Tux to the levelstart
559 GameSession::action(float elapsed_time)
562 if(!currentsector->player->growing_timer.started()) {
563 // Update Tux and the World
564 currentsector->action(elapsed_time);
567 // respawning in new sector?
568 if(newsector != "" && newspawnpoint != "") {
569 Sector* sector = level->get_sector(newsector);
571 std::cerr << "Sector '" << newsector << "' not found.\n";
573 sector->activate(newspawnpoint);
574 sector->play_music(LEVEL_MUSIC);
575 currentsector = sector;
584 currentsector->draw(*context);
585 drawstatus(*context);
590 if(Menu::current()) {
591 Menu::current()->draw(*context);
592 mouse_cursor->draw(*context);
595 context->do_drawing();
599 GameSession::draw_pause()
601 int x = SCREEN_HEIGHT / 20;
602 for(int i = 0; i < x; ++i) {
603 context->draw_filled_rect(
604 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
605 -((pause_menu_frame * i)%SCREEN_WIDTH)
606 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
607 Vector(SCREEN_WIDTH,10),
608 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
610 context->draw_filled_rect(
611 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
612 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
613 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
614 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
616 const char* str1 = _("Playing: ");
617 const char* str2 = level->get_name().c_str();
619 context->draw_text(blue_text, str1,
620 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
621 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
622 context->draw_text(white_text, str2,
623 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
624 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
628 GameSession::process_menu()
630 Menu* menu = Menu::current();
635 if(menu == game_menu)
637 switch (game_menu->check())
642 case MNID_ABORTLEVEL:
644 exit_status = ES_LEVEL_ABORT;
648 else if(menu == options_menu)
650 process_options_menu();
652 else if(menu == load_game_menu )
654 process_load_game_menu();
660 GameSession::ExitStatus
663 Menu::set_current(0);
667 double fps_nextframe_ticks; // fps regulating code
669 // Eat unneeded events
671 while(SDL_PollEvent(&event))
676 Uint32 lastticks = SDL_GetTicks();
677 fps_ticks = SDL_GetTicks();
678 fps_nextframe_ticks = SDL_GetTicks(); // fps regulating code
680 while (exit_status == ES_NONE) {
681 Uint32 ticks = SDL_GetTicks();
682 float elapsed_time = float(ticks - lastticks) / 1000.;
684 global_time += elapsed_time;
688 if(elapsed_time > 0.025){
689 elapsed_time = 0.025;
692 // fps regualting code
693 const double wantedFps= 60.0; // set to 60 by now
694 while (fps_nextframe_ticks > SDL_GetTicks()){
696 // If we really have to wait long, then do an imprecise SDL_Delay()
697 if (fps_nextframe_ticks - SDL_GetTicks() > 15){
702 float diff = SDL_GetTicks() - fps_nextframe_ticks;
704 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / wantedFps); // sets the ticks that must have elapsed
706 fps_nextframe_ticks += 1000.0 / wantedFps; // sets the ticks that must have elapsed
707 // in order for the next frame to start.
711 currentsector->player->input.old_fire = currentsector->player->input.fire;
712 currentsector->player->input.old_up = currentsector->player->input.old_up;
717 // Update the world state and all objects in the world
718 // Do that with a constante time-delta so that the game will run
719 // determistic and not different on different machines
720 if(!game_pause && !Menu::current())
723 check_end_conditions();
724 if (end_sequence == ENDSEQUENCE_RUNNING)
725 action(elapsed_time/2);
726 else if(end_sequence == NO_ENDSEQUENCE)
727 action(elapsed_time);
737 /* Time stops in pause mode */
738 if(game_pause || Menu::current())
743 //frame_rate.update();
746 if (time_left.check() && !end_sequence)
747 currentsector->player->kill(Player::KILL);
750 if (currentsector->player->invincible_timer.started() && !end_sequence)
752 currentsector->play_music(HERRING_MUSIC);
754 /* are we low on time ? */
755 else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
757 currentsector->play_music(HURRYUP_MUSIC);
759 /* or just normal music? */
760 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
762 currentsector->play_music(LEVEL_MUSIC);
765 /* Calculate frames per second */
770 if(SDL_GetTicks() - fps_ticks >= 500)
772 fps_fps = (float) fps_cnt / .5;
774 fps_ticks = SDL_GetTicks();
783 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
786 newspawnpoint = spawnpoint;
790 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
792 reset_sector = sector;
797 GameSession::display_info_box(const std::string& text)
799 InfoBox* box = new InfoBox(text);
804 while (SDL_PollEvent(&event)) {
820 GameSession::start_sequence(const std::string& sequencename)
822 if(sequencename == "endsequence" || sequencename == "fireworks") {
826 end_sequence = ENDSEQUENCE_RUNNING;
827 endsequence_timer.start(7.0); // 7 seconds until we finish the map
829 SoundManager::get()->play_music(level_end_song, 0);
830 currentsector->player->invincible_timer.start(7.0);
832 // add left time to stats
833 global_stats.set_points(TIME_NEEDED_STAT,
834 int(time_left.get_period() - time_left.get_timeleft()));
836 if(sequencename == "fireworks") {
837 currentsector->add_object(new Fireworks());
839 } else if(sequencename == "stoptux") {
840 end_sequence = ENDSEQUENCE_WAITING;
842 std::cout << "Unknown sequence '" << sequencename << "'.\n";
848 GameSession::drawstatus(DrawingContext& context)
852 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
853 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
854 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
856 if(st_gl_mode == ST_GL_TEST)
858 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
859 LEFT_ALLIGN, LAYER_FOREGROUND1);
862 if(time_left.get_timeleft() < 0) {
863 context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, 0),
864 CENTER_ALLIGN, LAYER_FOREGROUND1);
865 } else if (time_left.get_timeleft() > TIME_WARNING
866 || int(global_time * 2.5) % 2) {
867 sprintf(str, " %d", int(time_left.get_timeleft()));
868 context.draw_text(white_text, _("TIME"),
869 Vector(SCREEN_WIDTH/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
870 context.draw_text(gold_text, str,
871 Vector(SCREEN_WIDTH/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
874 sprintf(str, " %d", player_status.distros);
875 context.draw_text(white_text, _("COINS"),
876 Vector(SCREEN_WIDTH - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
877 LEFT_ALLIGN, LAYER_FOREGROUND1);
878 context.draw_text(gold_text, str,
879 Vector(SCREEN_WIDTH - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
881 if (player_status.lives >= 5)
883 sprintf(str, "%dx", player_status.lives);
884 float x = SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w;
885 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
886 context.draw_surface(tux_life, Vector(SCREEN_WIDTH - 16, 20),
891 for(int i= 0; i < player_status.lives; ++i)
892 context.draw_surface(tux_life,
893 Vector(SCREEN_WIDTH - tux_life->w*4 +(tux_life->w*i), 20),
897 context.draw_text(white_text, _("LIVES"),
898 Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
899 LEFT_ALLIGN, LAYER_FOREGROUND1);
903 sprintf(str, "%2.1f", fps_fps);
904 context.draw_text(white_text, "FPS",
905 Vector(SCREEN_WIDTH - white_text->get_text_width("FPS "), 40),
906 LEFT_ALLIGN, LAYER_FOREGROUND1);
907 context.draw_text(gold_text, str,
908 Vector(SCREEN_WIDTH-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
913 GameSession::drawresultscreen()
917 DrawingContext context;
918 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
919 i != currentsector->gameobjects.end(); ++i) {
920 Background* background = dynamic_cast<Background*> (*i);
922 background->draw(context);
926 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
927 CENTER_ALLIGN, LAYER_FOREGROUND1);
929 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
930 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
932 sprintf(str, _("COINS: %d"), player_status.distros);
933 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
935 context.do_drawing();
938 wait_for_event(event,2000,5000,true);
941 std::string slotinfo(int slot)
944 std::string slotfile;
946 std::stringstream stream;
948 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
952 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
954 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
956 throw std::runtime_error("file is not a supertux-savegame.");
958 savegame->get("title", title);
959 } catch(std::exception& e) {
960 return std::string(_("Slot")) + " " + stream.str() + " - " +
961 std::string(_("Free"));
964 return std::string("Slot ") + stream.str() + " - " + title;
967 bool process_load_game_menu()
969 int slot = load_game_menu->check();
971 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
973 std::stringstream stream;
975 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
978 DrawingContext context;
979 context.draw_text(white_text, "Loading...",
980 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
981 context.do_drawing();
983 WorldMapNS::WorldMap worldmap;
985 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
986 // Load the game or at least set the savegame_file variable
987 worldmap.loadgame(slotfile);
991 Menu::set_current(main_menu);