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>
43 #include "app/globals.h"
45 #include "video/screen.h"
46 #include "app/setup.h"
52 #include "object/particlesystem.h"
53 #include "object/background.h"
54 #include "object/tilemap.h"
55 #include "object/camera.h"
56 #include "object/player.h"
57 #include "lisp/lisp.h"
58 #include "lisp/parser.h"
59 #include "resources.h"
60 #include "app/gettext.h"
64 #include "statistics.h"
66 #include "object/fireworks.h"
68 GameSession* GameSession::current_ = 0;
70 bool compare_last(std::string& haystack, std::string needle)
72 int haystack_size = haystack.size();
73 int needle_size = needle.size();
75 if(haystack_size < needle_size)
78 if(haystack.compare(haystack_size-needle_size, needle_size, needle) == 0)
83 GameSession::GameSession(const std::string& levelfile_, int mode,
84 Statistics* statistics)
85 : level(0), currentsector(0), st_gl_mode(mode),
86 end_sequence(NO_ENDSEQUENCE), levelfile(levelfile_),
87 best_level_statistics(statistics)
94 context = new DrawingContext();
96 last_swap_point = Vector(-1, -1);
97 last_swap_stats.reset();
103 GameSession::restart_level()
106 exit_status = ES_NONE;
107 end_sequence = NO_ENDSEQUENCE;
112 Vector tux_pos = Vector(-1,-1);
115 // Tux has lost a life, so we try to respawn him at the nearest reset point
116 tux_pos = currentsector->player->base;
124 level->load(levelfile);
126 global_stats.reset();
127 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
128 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
129 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
131 currentsector = level->get_sector("main");
133 Termination::abort("Level has no main sector.", "");
134 currentsector->activate("main");
137 // Set Tux to the nearest reset point
140 tux_pos = currentsector->get_best_spawn_point(tux_pos);
142 if(last_swap_point.x > tux_pos.x)
143 tux_pos = last_swap_point;
144 else // new swap point
146 last_swap_point = tux_pos;
148 last_swap_stats += global_stats;
151 currentsector->player->base.x = tux_pos.x;
152 currentsector->player->base.y = tux_pos.y;
154 // has to reset camera on swapping
155 currentsector->camera->reset(Vector(currentsector->player->base.x,
156 currentsector->player->base.y));
160 if (st_gl_mode != ST_GL_DEMO_GAME)
162 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
167 currentsector->play_music(LEVEL_MUSIC);
170 GameSession::~GameSession()
177 GameSession::levelintro(void)
179 SoundManager::get()->halt_music();
183 DrawingContext context;
184 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
185 i != currentsector->gameobjects.end(); ++i) {
186 Background* background = dynamic_cast<Background*> (*i);
188 background->draw(context);
192 // context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
193 // CENTER_ALLIGN, LAYER_FOREGROUND1);
194 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
197 sprintf(str, "TUX x %d", player_status.lives);
198 context.draw_text(white_text, str, Vector(screen->w/2, 210),
199 CENTER_ALLIGN, LAYER_FOREGROUND1);
201 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
202 //TODO make author check case/blank-insensitive
203 context.draw_text(white_small_text,
204 std::string(_("contributed by ")) + level->get_author(),
205 Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
208 if(best_level_statistics != NULL)
209 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
211 context.do_drawing();
214 wait_for_event(event,1000,3000,true);
219 GameSession::start_timers()
221 time_left.start(level->timelimit);
226 GameSession::on_escape_press()
228 if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
229 return; // don't let the player open the menu, when he is dying
234 if(st_gl_mode == ST_GL_TEST)
236 exit_status = ES_LEVEL_ABORT;
238 else if (!Menu::current())
240 /* Tell Tux that the keys are all down, otherwise
241 it could have nasty bugs, like going allways to the right
242 or whatever that key does */
243 Player& tux = *(currentsector->player);
244 tux.key_event((SDLKey)keymap.up, UP);
245 tux.key_event((SDLKey)keymap.down, UP);
246 tux.key_event((SDLKey)keymap.left, UP);
247 tux.key_event((SDLKey)keymap.right, UP);
248 tux.key_event((SDLKey)keymap.jump, UP);
249 tux.key_event((SDLKey)keymap.power, UP);
251 Menu::set_current(game_menu);
252 Ticks::pause_start();
257 GameSession::process_events()
259 if (end_sequence != NO_ENDSEQUENCE)
261 Player& tux = *currentsector->player;
265 tux.input.right = DOWN;
268 if (int(last_x_pos) == int(tux.get_pos().x))
273 last_x_pos = tux.get_pos().x;
276 while (SDL_PollEvent(&event))
278 /* Check for menu-events, if the menu is shown */
281 Menu::current()->event(event);
288 case SDL_QUIT: /* Quit event - quit: */
289 Termination::abort("Received window close", "");
292 case SDL_KEYDOWN: /* A keypress! */
294 SDLKey key = event.key.keysym.sym;
298 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
306 case SDL_JOYBUTTONDOWN:
307 if (event.jbutton.button == joystick_keymap.start_button)
315 if(!Menu::current() && !game_pause)
319 while (SDL_PollEvent(&event))
321 /* Check for menu-events, if the menu is shown */
324 Menu::current()->event(event);
330 Player& tux = *currentsector->player;
334 case SDL_QUIT: /* Quit event - quit: */
335 Termination::abort("Received window close", "");
338 case SDL_KEYDOWN: /* A keypress! */
340 SDLKey key = event.key.keysym.sym;
342 if(tux.key_event(key,DOWN))
347 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
355 case SDL_KEYUP: /* A keyrelease! */
357 SDLKey key = event.key.keysym.sym;
359 if(tux.key_event(key, UP))
368 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
369 tux.get_pos().x, tux.get_pos().y);
370 context->draw_text(white_text, buf,
371 Vector(0, screen->h - white_text->get_height()),
372 LEFT_ALLIGN, LAYER_FOREGROUND1);
373 context->do_drawing();
380 // "lifeup" cheat activates pause cause of the 'p'
381 // so work around to ignore it
382 if(compare_last(last_keys, "lifeu"))
393 Ticks::pause_start();
402 /* Check if chacrater is ASCII */
404 if((event.key.keysym.unicode & 0xFF80) == 0)
406 ch[0] = event.key.keysym.unicode & 0x7F;
409 last_keys.append(ch); // add to cheat keys
411 // Cheating words (the goal of this is really for debugging,
412 // but could be used for some cheating, nothing wrong with that)
413 if(compare_last(last_keys, "grow"))
418 if(compare_last(last_keys, "fire"))
421 tux.got_power = tux.FIRE_POWER;
424 if(compare_last(last_keys, "ice"))
427 tux.got_power = tux.ICE_POWER;
430 if(compare_last(last_keys, "lifeup"))
432 player_status.lives++;
435 if(compare_last(last_keys, "lifedown"))
437 player_status.lives--;
440 if(compare_last(last_keys, "grease"))
442 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
445 if(compare_last(last_keys, "invincible"))
446 { // be invincle for the rest of the level
447 tux.invincible_timer.start(10000);
450 if(compare_last(last_keys, "shrink"))
452 tux.kill(tux.SHRINK);
455 if(compare_last(last_keys, "kill"))
456 { // kill Tux, but without losing a life
457 player_status.lives++;
461 if(compare_last(last_keys, "grid"))
462 { // toggle debug grid
463 debug_grid = !debug_grid;
466 if(compare_last(last_keys, "hover"))
467 { // toggle hover ability on/off
468 tux.enable_hover = !tux.enable_hover;
471 if(compare_last(last_keys, "gotoend"))
472 { // goes to the end of the level
474 (currentsector->solids->get_width()*32)
477 currentsector->camera->reset(
478 Vector(tux.get_pos().x, tux.get_pos().y));
481 // temporary to help player's choosing a flapping
482 if(compare_last(last_keys, "marek"))
484 tux.flapping_mode = Player::MAREK_FLAP;
487 if(compare_last(last_keys, "ricardo"))
489 tux.flapping_mode = Player::RICARDO_FLAP;
492 if(compare_last(last_keys, "ryan"))
494 tux.flapping_mode = Player::RYAN_FLAP;
499 case SDL_JOYAXISMOTION:
500 if (event.jaxis.axis == joystick_keymap.x_axis)
502 if (event.jaxis.value < -joystick_keymap.dead_zone)
504 tux.input.left = DOWN;
505 tux.input.right = UP;
507 else if (event.jaxis.value > joystick_keymap.dead_zone)
510 tux.input.right = DOWN;
514 tux.input.left = DOWN;
515 tux.input.right = DOWN;
518 else if (event.jaxis.axis == joystick_keymap.y_axis)
520 if (event.jaxis.value > joystick_keymap.dead_zone)
525 else if (event.jaxis.value < -joystick_keymap.dead_zone)
528 tux.input.down = DOWN;
533 tux.input.down = DOWN;
538 case SDL_JOYHATMOTION:
539 if(event.jhat.value & SDL_HAT_UP) {
542 } else if(event.jhat.value & SDL_HAT_DOWN) {
544 tux.input.down = DOWN;
545 } else if(event.jhat.value & SDL_HAT_LEFT) {
546 tux.input.left = DOWN;
547 tux.input.right = UP;
548 } else if(event.jhat.value & SDL_HAT_RIGHT) {
550 tux.input.right = DOWN;
551 } else if(event.jhat.value == SDL_HAT_CENTERED) {
553 tux.input.right = UP;
559 case SDL_JOYBUTTONDOWN:
560 if (event.jbutton.button == joystick_keymap.a_button)
561 tux.input.jump = DOWN;
562 else if (event.jbutton.button == joystick_keymap.b_button)
563 tux.input.fire = DOWN;
564 else if (event.jbutton.button == joystick_keymap.start_button)
567 case SDL_JOYBUTTONUP:
568 if (event.jbutton.button == joystick_keymap.a_button)
570 else if (event.jbutton.button == joystick_keymap.b_button)
583 GameSession::check_end_conditions()
585 Player* tux = currentsector->player;
588 if(end_sequence && endsequence_timer.check()) {
589 exit_status = ES_LEVEL_FINISHED;
590 global_stats += last_swap_stats; // add swap points stats
592 } else if (!end_sequence && tux->is_dead()) {
593 player_status.bonus = PlayerStatus::NO_BONUS;
595 if (player_status.lives < 0) { // No more lives!?
596 exit_status = ES_GAME_OVER;
597 } else { // Still has lives, so reset Tux to the levelstart
606 GameSession::action(float elapsed_time)
609 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
611 // Update Tux and the World
612 currentsector->action(elapsed_time);
615 // respawning in new sector?
616 if(newsector != "" && newspawnpoint != "") {
617 Sector* sector = level->get_sector(newsector);
618 currentsector = sector;
619 currentsector->activate(newspawnpoint);
620 currentsector->play_music(LEVEL_MUSIC);
621 newsector = newspawnpoint = "";
628 currentsector->draw(*context);
629 drawstatus(*context);
633 int x = screen->h / 20;
634 for(int i = 0; i < x; ++i)
636 context->draw_filled_rect(
637 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
638 -((pause_menu_frame * i)%screen->w)
639 ,(i*20+pause_menu_frame)%screen->h),
640 Vector(screen->w,10),
641 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
643 context->draw_filled_rect(
644 Vector(0,0), Vector(screen->w, screen->h),
645 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
646 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
647 Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
651 sprintf(str1, _("Playing: "));
652 sprintf(str2, level->name.c_str());
654 context->draw_text(blue_text, str1,
655 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
656 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
657 context->draw_text(white_text, str2,
658 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
659 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
664 Menu::current()->draw(*context);
665 mouse_cursor->draw(*context);
668 context->do_drawing();
672 GameSession::process_menu()
674 Menu* menu = Menu::current();
679 if(menu == game_menu)
681 switch (game_menu->check())
686 case MNID_ABORTLEVEL:
688 exit_status = ES_LEVEL_ABORT;
692 else if(menu == options_menu)
694 process_options_menu();
696 else if(menu == load_game_menu )
698 process_load_game_menu();
703 GameSession::ExitStatus
706 Menu::set_current(0);
711 // Eat unneeded events
713 while(SDL_PollEvent(&event))
718 Uint32 lastticks = SDL_GetTicks();
719 fps_ticks = SDL_GetTicks();
721 while (exit_status == ES_NONE) {
722 Uint32 ticks = SDL_GetTicks();
723 float elapsed_time = float(ticks - lastticks) / 1000.;
725 global_time += elapsed_time;
729 if(elapsed_time > .025)
733 currentsector->player->input.old_fire = currentsector->player->input.fire;
734 currentsector->player->input.old_up = currentsector->player->input.old_up;
739 // Update the world state and all objects in the world
740 // Do that with a constante time-delta so that the game will run
741 // determistic and not different on different machines
742 if(!game_pause && !Menu::current())
745 check_end_conditions();
746 if (end_sequence == ENDSEQUENCE_RUNNING)
747 action(elapsed_time/2);
748 else if(end_sequence == NO_ENDSEQUENCE)
749 action(elapsed_time);
759 /* Time stops in pause mode */
760 if(game_pause || Menu::current())
765 //frame_rate.update();
768 if (time_left.check() && currentsector->player->dying == DYING_NOT
770 currentsector->player->kill(Player::KILL);
773 if(currentsector->player->invincible_timer.check() && !end_sequence)
775 currentsector->play_music(HERRING_MUSIC);
777 /* are we low on time ? */
778 else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
780 currentsector->play_music(HURRYUP_MUSIC);
782 /* or just normal music? */
783 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
785 currentsector->play_music(LEVEL_MUSIC);
788 /* Calculate frames per second */
793 if(SDL_GetTicks() - fps_ticks >= 500)
795 fps_fps = (float) fps_cnt / .5;
797 fps_ticks = SDL_GetTicks();
806 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
809 newspawnpoint = spawnpoint;
813 GameSession::start_sequence(const std::string& sequencename)
815 if(sequencename == "endsequence") {
819 end_sequence = ENDSEQUENCE_RUNNING;
820 endsequence_timer.start(7.0); // 7 seconds until we finish the map
822 SoundManager::get()->play_music(level_end_song, 0);
823 currentsector->player->invincible_timer.start(7.0);
825 // add left time to stats
826 global_stats.set_points(TIME_NEEDED_STAT,
827 int(time_left.get_period() - time_left.get_timeleft()));
829 if(level->get_end_sequence_type() == Level::FIREWORKS_ENDSEQ_ANIM) {
830 currentsector->add_object(new Fireworks());
833 std::cout << "Unknown sequence '" << sequencename << "'.\n";
839 GameSession::drawstatus(DrawingContext& context)
843 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
844 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
845 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
847 if(st_gl_mode == ST_GL_TEST)
849 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
850 LEFT_ALLIGN, LAYER_FOREGROUND1);
853 if(time_left.check()) {
854 context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
855 CENTER_ALLIGN, LAYER_FOREGROUND1);
856 } else if (time_left.get_timeleft() > TIME_WARNING
857 || int(global_time * 2.5) % 2) {
858 sprintf(str, " %d", int(time_left.get_timeleft()));
859 context.draw_text(white_text, _("TIME"),
860 Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
861 context.draw_text(gold_text, str,
862 Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
865 sprintf(str, " %d", player_status.distros);
866 context.draw_text(white_text, _("COINS"),
867 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
868 LEFT_ALLIGN, LAYER_FOREGROUND1);
869 context.draw_text(gold_text, str,
870 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
872 if (player_status.lives >= 5)
874 sprintf(str, "%dx", player_status.lives);
875 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
876 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
877 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
882 for(int i= 0; i < player_status.lives; ++i)
883 context.draw_surface(tux_life,
884 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
888 context.draw_text(white_text, _("LIVES"),
889 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
890 LEFT_ALLIGN, LAYER_FOREGROUND1);
894 sprintf(str, "%2.1f", fps_fps);
895 context.draw_text(white_text, "FPS",
896 Vector(screen->w - white_text->get_text_width("FPS "), 40),
897 LEFT_ALLIGN, LAYER_FOREGROUND1);
898 context.draw_text(gold_text, str,
899 Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
904 GameSession::drawresultscreen()
908 DrawingContext context;
909 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
910 i != currentsector->gameobjects.end(); ++i) {
911 Background* background = dynamic_cast<Background*> (*i);
913 background->draw(context);
917 context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
918 CENTER_ALLIGN, LAYER_FOREGROUND1);
920 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
921 context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
923 sprintf(str, _("COINS: %d"), player_status.distros);
924 context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
926 context.do_drawing();
929 wait_for_event(event,2000,5000,true);
932 std::string slotinfo(int slot)
935 std::string slotfile;
937 std::stringstream stream;
939 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
943 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
945 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
947 throw std::runtime_error("file is not a supertux-savegame.");
949 savegame->get("title", title);
950 } catch(std::exception& e) {
951 return std::string(_("Slot")) + " " + stream.str() + " - " +
952 std::string(_("Free"));
955 return std::string("Slot ") + stream.str() + " - " + title;
958 bool process_load_game_menu()
960 int slot = load_game_menu->check();
962 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
964 std::stringstream stream;
966 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
968 if (access(slotfile.c_str(), F_OK) != 0)
970 shrink_fade(Vector(screen->w/2,screen->h/2), 600);
975 DrawingContext context;
976 context.draw_text(white_text, "Loading...",
977 Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
978 context.do_drawing();
980 WorldMapNS::WorldMap worldmap;
982 worldmap.set_map_filename("icyisland.stwm");
983 // Load the game or at least set the savegame_file variable
984 worldmap.loadgame(slotfile);
988 Menu::set_current(main_menu);