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"
66 GameSession* GameSession::current_ = 0;
68 bool compare_last(std::string& haystack, std::string needle)
70 int haystack_size = haystack.size();
71 int needle_size = needle.size();
73 if(haystack_size < needle_size)
76 if(haystack.compare(haystack_size-needle_size, needle_size, needle) == 0)
81 GameSession::GameSession(const std::string& levelfile_, int mode,
82 Statistics* statistics)
83 : level(0), currentsector(0), st_gl_mode(mode),
84 end_sequence(NO_ENDSEQUENCE), levelfile(levelfile_),
85 best_level_statistics(statistics)
92 context = new DrawingContext();
98 GameSession::restart_level()
101 exit_status = ES_NONE;
102 end_sequence = NO_ENDSEQUENCE;
107 Vector tux_pos = Vector(-1,-1);
110 // Tux has lost a life, so we try to respawn him at the nearest reset point
111 tux_pos = currentsector->player->base;
119 level->load(levelfile);
121 global_stats.reset();
122 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
123 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
124 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
126 if(reset_sector != "") {
127 currentsector = level->get_sector(reset_sector);
129 std::stringstream msg;
130 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
131 throw std::runtime_error(msg.str());
133 currentsector->activate(reset_pos);
135 currentsector = level->get_sector("main");
137 throw std::runtime_error("Couldn't find main sector");
138 currentsector->activate("main");
141 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
145 currentsector->play_music(LEVEL_MUSIC);
148 GameSession::~GameSession()
155 GameSession::levelintro()
157 SoundManager::get()->halt_music();
161 DrawingContext context;
162 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
163 i != currentsector->gameobjects.end(); ++i) {
164 Background* background = dynamic_cast<Background*> (*i);
166 background->draw(context);
170 // context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
171 // CENTER_ALLIGN, LAYER_FOREGROUND1);
172 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
175 sprintf(str, "TUX x %d", player_status.lives);
176 context.draw_text(white_text, str, Vector(screen->w/2, 210),
177 CENTER_ALLIGN, LAYER_FOREGROUND1);
179 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
180 //TODO make author check case/blank-insensitive
181 context.draw_text(white_small_text,
182 std::string(_("contributed by ")) + level->get_author(),
183 Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
186 if(best_level_statistics != NULL)
187 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
189 context.do_drawing();
192 wait_for_event(event,1000,3000,true);
197 GameSession::start_timers()
199 time_left.start(level->timelimit);
204 GameSession::on_escape_press()
206 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
207 return; // don't let the player open the menu, when he is dying
212 if(st_gl_mode == ST_GL_TEST) {
213 exit_status = ES_LEVEL_ABORT;
214 } else if (!Menu::current()) {
215 Menu::set_current(game_menu);
216 Ticks::pause_start();
221 GameSession::process_events()
223 if (end_sequence != NO_ENDSEQUENCE)
225 Player& tux = *currentsector->player;
227 tux.input.fire = false;
228 tux.input.left = false;
229 tux.input.right = true;
230 tux.input.down = false;
232 if (int(last_x_pos) == int(tux.get_pos().x))
235 tux.input.up = false;
237 last_x_pos = tux.get_pos().x;
240 while (SDL_PollEvent(&event))
242 /* Check for menu-events, if the menu is shown */
245 Menu::current()->event(event);
252 case SDL_QUIT: /* Quit event - quit: */
253 Termination::abort("Received window close", "");
256 case SDL_KEYDOWN: /* A keypress! */
258 SDLKey key = event.key.keysym.sym;
262 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
270 case SDL_JOYBUTTONDOWN:
271 if (event.jbutton.button == joystick_keymap.start_button)
279 if(!Menu::current() && !game_pause)
283 while (SDL_PollEvent(&event))
285 /* Check for menu-events, if the menu is shown */
288 Menu::current()->event(event);
294 Player& tux = *currentsector->player;
298 case SDL_QUIT: /* Quit event - quit: */
299 Termination::abort("Received window close", "");
302 case SDL_KEYDOWN: /* A keypress! */
304 SDLKey key = event.key.keysym.sym;
306 if(tux.key_event(key, true))
311 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
319 case SDL_KEYUP: /* A keyrelease! */
321 SDLKey key = event.key.keysym.sym;
323 if(tux.key_event(key, false))
332 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
333 tux.get_pos().x, tux.get_pos().y);
334 context->draw_text(white_text, buf,
335 Vector(0, screen->h - white_text->get_height()),
336 LEFT_ALLIGN, LAYER_FOREGROUND1);
337 context->do_drawing();
344 // "lifeup" cheat activates pause cause of the 'p'
345 // so work around to ignore it
346 if(compare_last(last_keys, "lifeu"))
357 Ticks::pause_start();
366 /* Check if chacrater is ASCII */
368 if((event.key.keysym.unicode & 0xFF80) == 0)
370 ch[0] = event.key.keysym.unicode & 0x7F;
373 last_keys.append(ch); // add to cheat keys
377 case SDL_JOYAXISMOTION:
378 if (event.jaxis.axis == joystick_keymap.x_axis)
380 if (event.jaxis.value < -joystick_keymap.dead_zone)
382 tux.input.left = true;
383 tux.input.right = false;
385 else if (event.jaxis.value > joystick_keymap.dead_zone)
387 tux.input.left = false;
388 tux.input.right = true;
392 tux.input.left = false;
393 tux.input.right = false;
396 else if (event.jaxis.axis == joystick_keymap.y_axis)
398 if (event.jaxis.value > joystick_keymap.dead_zone)
401 tux.input.down = false;
403 else if (event.jaxis.value < -joystick_keymap.dead_zone)
405 tux.input.up = false;
406 tux.input.down = true;
410 tux.input.up = false;
411 tux.input.down = false;
416 case SDL_JOYHATMOTION:
417 if(event.jhat.value & SDL_HAT_UP) {
419 tux.input.down = false;
420 } else if(event.jhat.value & SDL_HAT_DOWN) {
421 tux.input.up = false;
422 tux.input.down = true;
423 } else if(event.jhat.value & SDL_HAT_LEFT) {
424 tux.input.left = true;
425 tux.input.right = false;
426 } else if(event.jhat.value & SDL_HAT_RIGHT) {
427 tux.input.left = false;
428 tux.input.right = true;
429 } else if(event.jhat.value == SDL_HAT_CENTERED) {
430 tux.input.left = false;
431 tux.input.right = false;
432 tux.input.up = false;
433 tux.input.down = false;
437 case SDL_JOYBUTTONDOWN:
438 // FIXME: I assume we have to set old_jump and stuff here?!?
439 if (event.jbutton.button == joystick_keymap.a_button)
440 tux.input.jump = true;
441 else if (event.jbutton.button == joystick_keymap.b_button)
442 tux.input.fire = true;
443 else if (event.jbutton.button == joystick_keymap.start_button)
446 case SDL_JOYBUTTONUP:
447 if (event.jbutton.button == joystick_keymap.a_button)
448 tux.input.jump = false;
449 else if (event.jbutton.button == joystick_keymap.b_button)
450 tux.input.fire = false;
462 GameSession::handle_cheats()
464 Player& tux = *currentsector->player;
466 // Cheating words (the goal of this is really for debugging,
467 // but could be used for some cheating, nothing wrong with that)
468 if(compare_last(last_keys, "grow")) {
472 if(compare_last(last_keys, "fire")) {
474 tux.got_power = tux.FIRE_POWER;
477 if(compare_last(last_keys, "ice")) {
479 tux.got_power = tux.ICE_POWER;
482 if(compare_last(last_keys, "lifeup")) {
483 player_status.lives++;
486 if(compare_last(last_keys, "lifedown")) {
487 player_status.lives--;
490 if(compare_last(last_keys, "grease")) {
491 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
494 if(compare_last(last_keys, "invincible")) {
495 // be invincle for the rest of the level
496 tux.invincible_timer.start(10000);
499 if(compare_last(last_keys, "shrink")) {
501 tux.kill(tux.SHRINK);
504 if(compare_last(last_keys, "kill")) {
505 // kill Tux, but without losing a life
506 player_status.lives++;
510 if(compare_last(last_keys, "grid")) {
512 debug_grid = !debug_grid;
515 if(compare_last(last_keys, "hover")) {
516 // toggle hover ability on/off
517 tux.enable_hover = !tux.enable_hover;
520 if(compare_last(last_keys, "gotoend")) {
521 // goes to the end of the level
523 (currentsector->solids->get_width()*32) - (screen->w*2), 0));
524 currentsector->camera->reset(
525 Vector(tux.get_pos().x, tux.get_pos().y));
528 if(compare_last(last_keys, "finish")) {
529 // finish current sector
530 exit_status = ES_LEVEL_FINISHED;
531 // don't add points to stats though...
533 // temporary to help player's choosing a flapping
534 if(compare_last(last_keys, "marek")) {
535 tux.flapping_mode = Player::MAREK_FLAP;
538 if(compare_last(last_keys, "ricardo")) {
539 tux.flapping_mode = Player::RICARDO_FLAP;
542 if(compare_last(last_keys, "ryan")) {
543 tux.flapping_mode = Player::RYAN_FLAP;
549 GameSession::check_end_conditions()
551 Player* tux = currentsector->player;
554 if(end_sequence && endsequence_timer.check()) {
555 exit_status = ES_LEVEL_FINISHED;
557 } else if (!end_sequence && tux->is_dead()) {
558 player_status.bonus = PlayerStatus::NO_BONUS;
560 if (player_status.lives < 0) { // No more lives!?
561 exit_status = ES_GAME_OVER;
562 } else { // Still has lives, so reset Tux to the levelstart
571 GameSession::action(float elapsed_time)
574 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
576 // Update Tux and the World
577 currentsector->action(elapsed_time);
580 // respawning in new sector?
581 if(newsector != "" && newspawnpoint != "") {
582 Sector* sector = level->get_sector(newsector);
583 currentsector = sector;
584 currentsector->activate(newspawnpoint);
585 currentsector->play_music(LEVEL_MUSIC);
586 newsector = newspawnpoint = "";
593 currentsector->draw(*context);
594 drawstatus(*context);
598 int x = screen->h / 20;
599 for(int i = 0; i < x; ++i)
601 context->draw_filled_rect(
602 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
603 -((pause_menu_frame * i)%screen->w)
604 ,(i*20+pause_menu_frame)%screen->h),
605 Vector(screen->w,10),
606 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
608 context->draw_filled_rect(
609 Vector(0,0), Vector(screen->w, screen->h),
610 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
611 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
612 Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
616 sprintf(str1, _("Playing: "));
617 sprintf(str2, level->name.c_str());
619 context->draw_text(blue_text, str1,
620 Vector((screen->w - (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->w - (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);
629 Menu::current()->draw(*context);
630 mouse_cursor->draw(*context);
633 context->do_drawing();
637 GameSession::process_menu()
639 Menu* menu = Menu::current();
644 if(menu == game_menu)
646 switch (game_menu->check())
651 case MNID_ABORTLEVEL:
653 exit_status = ES_LEVEL_ABORT;
657 else if(menu == options_menu)
659 process_options_menu();
661 else if(menu == load_game_menu )
663 process_load_game_menu();
668 GameSession::ExitStatus
671 Menu::set_current(0);
676 // Eat unneeded events
678 while(SDL_PollEvent(&event))
683 Uint32 lastticks = SDL_GetTicks();
684 fps_ticks = SDL_GetTicks();
686 while (exit_status == ES_NONE) {
687 Uint32 ticks = SDL_GetTicks();
688 float elapsed_time = float(ticks - lastticks) / 1000.;
690 global_time += elapsed_time;
694 if(elapsed_time > .025)
698 currentsector->player->input.old_fire = currentsector->player->input.fire;
699 currentsector->player->input.old_up = currentsector->player->input.old_up;
704 // Update the world state and all objects in the world
705 // Do that with a constante time-delta so that the game will run
706 // determistic and not different on different machines
707 if(!game_pause && !Menu::current())
710 check_end_conditions();
711 if (end_sequence == ENDSEQUENCE_RUNNING)
712 action(elapsed_time/2);
713 else if(end_sequence == NO_ENDSEQUENCE)
714 action(elapsed_time);
724 /* Time stops in pause mode */
725 if(game_pause || Menu::current())
730 //frame_rate.update();
733 if (time_left.check() && !end_sequence)
734 currentsector->player->kill(Player::KILL);
737 if (currentsector->player->invincible_timer.started() && !end_sequence)
739 currentsector->play_music(HERRING_MUSIC);
741 /* are we low on time ? */
742 else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
744 currentsector->play_music(HURRYUP_MUSIC);
746 /* or just normal music? */
747 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
749 currentsector->play_music(LEVEL_MUSIC);
752 /* Calculate frames per second */
757 if(SDL_GetTicks() - fps_ticks >= 500)
759 fps_fps = (float) fps_cnt / .5;
761 fps_ticks = SDL_GetTicks();
770 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
773 newspawnpoint = spawnpoint;
777 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
779 reset_sector = sector;
784 GameSession::start_sequence(const std::string& sequencename)
786 if(sequencename == "endsequence" || sequencename == "fireworks") {
790 end_sequence = ENDSEQUENCE_RUNNING;
791 endsequence_timer.start(7.0); // 7 seconds until we finish the map
793 SoundManager::get()->play_music(level_end_song, 0);
794 currentsector->player->invincible_timer.start(7.0);
796 // add left time to stats
797 global_stats.set_points(TIME_NEEDED_STAT,
798 int(time_left.get_period() - time_left.get_timeleft()));
800 if(sequencename == "fireworks") {
801 currentsector->add_object(new Fireworks());
803 } else if(sequencename == "stoptux") {
804 end_sequence = ENDSEQUENCE_WAITING;
806 std::cout << "Unknown sequence '" << sequencename << "'.\n";
812 GameSession::drawstatus(DrawingContext& context)
816 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
817 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
818 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
820 if(st_gl_mode == ST_GL_TEST)
822 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
823 LEFT_ALLIGN, LAYER_FOREGROUND1);
826 if(time_left.get_timeleft() < 0) {
827 context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
828 CENTER_ALLIGN, LAYER_FOREGROUND1);
829 } else if (time_left.get_timeleft() > TIME_WARNING
830 || int(global_time * 2.5) % 2) {
831 sprintf(str, " %d", int(time_left.get_timeleft()));
832 context.draw_text(white_text, _("TIME"),
833 Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
834 context.draw_text(gold_text, str,
835 Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
838 sprintf(str, " %d", player_status.distros);
839 context.draw_text(white_text, _("COINS"),
840 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
841 LEFT_ALLIGN, LAYER_FOREGROUND1);
842 context.draw_text(gold_text, str,
843 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
845 if (player_status.lives >= 5)
847 sprintf(str, "%dx", player_status.lives);
848 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
849 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
850 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
855 for(int i= 0; i < player_status.lives; ++i)
856 context.draw_surface(tux_life,
857 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
861 context.draw_text(white_text, _("LIVES"),
862 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
863 LEFT_ALLIGN, LAYER_FOREGROUND1);
867 sprintf(str, "%2.1f", fps_fps);
868 context.draw_text(white_text, "FPS",
869 Vector(screen->w - white_text->get_text_width("FPS "), 40),
870 LEFT_ALLIGN, LAYER_FOREGROUND1);
871 context.draw_text(gold_text, str,
872 Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
877 GameSession::drawresultscreen()
881 DrawingContext context;
882 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
883 i != currentsector->gameobjects.end(); ++i) {
884 Background* background = dynamic_cast<Background*> (*i);
886 background->draw(context);
890 context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
891 CENTER_ALLIGN, LAYER_FOREGROUND1);
893 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
894 context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
896 sprintf(str, _("COINS: %d"), player_status.distros);
897 context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
899 context.do_drawing();
902 wait_for_event(event,2000,5000,true);
905 std::string slotinfo(int slot)
908 std::string slotfile;
910 std::stringstream stream;
912 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
916 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
918 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
920 throw std::runtime_error("file is not a supertux-savegame.");
922 savegame->get("title", title);
923 } catch(std::exception& e) {
924 return std::string(_("Slot")) + " " + stream.str() + " - " +
925 std::string(_("Free"));
928 return std::string("Slot ") + stream.str() + " - " + title;
931 bool process_load_game_menu()
933 int slot = load_game_menu->check();
935 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
937 std::stringstream stream;
939 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
942 DrawingContext context;
943 context.draw_text(white_text, "Loading...",
944 Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
945 context.do_drawing();
947 WorldMapNS::WorldMap worldmap;
949 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
950 // Load the game or at least set the savegame_file variable
951 worldmap.loadgame(slotfile);
955 Menu::set_current(main_menu);