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"
47 #include "high_scores.h"
53 #include "object/particlesystem.h"
54 #include "object/background.h"
55 #include "object/tilemap.h"
56 #include "object/camera.h"
57 #include "object/player.h"
58 #include "resources.h"
59 #include "app/gettext.h"
63 #include "statistics.h"
65 #include "object/fireworks.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();
95 last_swap_point = Vector(-1, -1);
96 last_swap_stats.reset();
102 GameSession::restart_level()
105 exit_status = ES_NONE;
106 end_sequence = NO_ENDSEQUENCE;
111 Vector tux_pos = Vector(-1,-1);
114 // Tux has lost a life, so we try to respawn him at the nearest reset point
115 tux_pos = currentsector->player->base;
123 level->load(levelfile);
125 global_stats.reset();
126 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
127 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
128 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
130 currentsector = level->get_sector("main");
132 Termination::abort("Level has no main sector.", "");
133 currentsector->activate("main");
136 // Set Tux to the nearest reset point
139 tux_pos = currentsector->get_best_spawn_point(tux_pos);
141 if(last_swap_point.x > tux_pos.x)
142 tux_pos = last_swap_point;
143 else // new swap point
145 last_swap_point = tux_pos;
147 last_swap_stats += global_stats;
150 currentsector->player->base.x = tux_pos.x;
151 currentsector->player->base.y = tux_pos.y;
153 // has to reset camera on swapping
154 currentsector->camera->reset(Vector(currentsector->player->base.x,
155 currentsector->player->base.y));
159 if (st_gl_mode != ST_GL_DEMO_GAME)
161 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
166 currentsector->play_music(LEVEL_MUSIC);
169 GameSession::~GameSession()
176 GameSession::levelintro(void)
178 SoundManager::get()->halt_music();
182 DrawingContext context;
183 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
184 i != currentsector->gameobjects.end(); ++i) {
185 Background* background = dynamic_cast<Background*> (*i);
187 background->draw(context);
191 // context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
192 // CENTER_ALLIGN, LAYER_FOREGROUND1);
193 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
196 sprintf(str, "TUX x %d", player_status.lives);
197 context.draw_text(white_text, str, Vector(screen->w/2, 210),
198 CENTER_ALLIGN, LAYER_FOREGROUND1);
200 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
201 //TODO make author check case/blank-insensitive
202 context.draw_text(white_small_text,
203 std::string(_("contributed by ")) + level->get_author(),
204 Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
207 if(best_level_statistics != NULL)
208 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
210 context.do_drawing();
213 wait_for_event(event,1000,3000,true);
218 GameSession::start_timers()
220 time_left.start(level->timelimit);
225 GameSession::on_escape_press()
227 if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
228 return; // don't let the player open the menu, when he is dying
233 if(st_gl_mode == ST_GL_TEST)
235 exit_status = ES_LEVEL_ABORT;
237 else if (!Menu::current())
239 /* Tell Tux that the keys are all down, otherwise
240 it could have nasty bugs, like going allways to the right
241 or whatever that key does */
242 Player& tux = *(currentsector->player);
243 tux.key_event((SDLKey)keymap.up, UP);
244 tux.key_event((SDLKey)keymap.down, UP);
245 tux.key_event((SDLKey)keymap.left, UP);
246 tux.key_event((SDLKey)keymap.right, UP);
247 tux.key_event((SDLKey)keymap.jump, UP);
248 tux.key_event((SDLKey)keymap.power, UP);
250 Menu::set_current(game_menu);
251 Ticks::pause_start();
256 GameSession::process_events()
258 if (end_sequence != NO_ENDSEQUENCE)
260 Player& tux = *currentsector->player;
264 tux.input.right = DOWN;
267 if (int(last_x_pos) == int(tux.get_pos().x))
272 last_x_pos = tux.get_pos().x;
275 while (SDL_PollEvent(&event))
277 /* Check for menu-events, if the menu is shown */
280 Menu::current()->event(event);
287 case SDL_QUIT: /* Quit event - quit: */
288 Termination::abort("Received window close", "");
291 case SDL_KEYDOWN: /* A keypress! */
293 SDLKey key = event.key.keysym.sym;
297 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
305 case SDL_JOYBUTTONDOWN:
306 if (event.jbutton.button == joystick_keymap.start_button)
314 if(!Menu::current() && !game_pause)
318 while (SDL_PollEvent(&event))
320 /* Check for menu-events, if the menu is shown */
323 Menu::current()->event(event);
329 Player& tux = *currentsector->player;
333 case SDL_QUIT: /* Quit event - quit: */
334 Termination::abort("Received window close", "");
337 case SDL_KEYDOWN: /* A keypress! */
339 SDLKey key = event.key.keysym.sym;
341 if(tux.key_event(key,DOWN))
346 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
354 case SDL_KEYUP: /* A keyrelease! */
356 SDLKey key = event.key.keysym.sym;
358 if(tux.key_event(key, UP))
367 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
368 tux.get_pos().x, tux.get_pos().y);
369 context->draw_text(white_text, buf,
370 Vector(0, screen->h - white_text->get_height()),
371 LEFT_ALLIGN, LAYER_FOREGROUND1);
372 context->do_drawing();
379 // "lifeup" cheat activates pause cause of the 'p'
380 // so work around to ignore it
381 if(compare_last(last_keys, "lifeu"))
392 Ticks::pause_start();
401 /* Check if chacrater is ASCII */
403 if((event.key.keysym.unicode & 0xFF80) == 0)
405 ch[0] = event.key.keysym.unicode & 0x7F;
408 last_keys.append(ch); // add to cheat keys
410 // Cheating words (the goal of this is really for debugging,
411 // but could be used for some cheating, nothing wrong with that)
412 if(compare_last(last_keys, "grow"))
417 if(compare_last(last_keys, "fire"))
420 tux.got_power = tux.FIRE_POWER;
423 if(compare_last(last_keys, "ice"))
426 tux.got_power = tux.ICE_POWER;
429 if(compare_last(last_keys, "lifeup"))
431 player_status.lives++;
434 if(compare_last(last_keys, "lifedown"))
436 player_status.lives--;
439 if(compare_last(last_keys, "grease"))
441 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
444 if(compare_last(last_keys, "invincible"))
445 { // be invincle for the rest of the level
446 tux.invincible_timer.start(10000);
449 if(compare_last(last_keys, "shrink"))
451 tux.kill(tux.SHRINK);
454 if(compare_last(last_keys, "kill"))
455 { // kill Tux, but without losing a life
456 player_status.lives++;
460 if(compare_last(last_keys, "grid"))
461 { // toggle debug grid
462 debug_grid = !debug_grid;
465 if(compare_last(last_keys, "hover"))
466 { // toggle hover ability on/off
467 tux.enable_hover = !tux.enable_hover;
470 if(compare_last(last_keys, "gotoend"))
471 { // goes to the end of the level
473 (currentsector->solids->get_width()*32)
476 currentsector->camera->reset(
477 Vector(tux.get_pos().x, tux.get_pos().y));
480 // temporary to help player's choosing a flapping
481 if(compare_last(last_keys, "marek"))
483 tux.flapping_mode = Player::MAREK_FLAP;
486 if(compare_last(last_keys, "ricardo"))
488 tux.flapping_mode = Player::RICARDO_FLAP;
491 if(compare_last(last_keys, "ryan"))
493 tux.flapping_mode = Player::RYAN_FLAP;
498 case SDL_JOYAXISMOTION:
499 if (event.jaxis.axis == joystick_keymap.x_axis)
501 if (event.jaxis.value < -joystick_keymap.dead_zone)
503 tux.input.left = DOWN;
504 tux.input.right = UP;
506 else if (event.jaxis.value > joystick_keymap.dead_zone)
509 tux.input.right = DOWN;
513 tux.input.left = DOWN;
514 tux.input.right = DOWN;
517 else if (event.jaxis.axis == joystick_keymap.y_axis)
519 if (event.jaxis.value > joystick_keymap.dead_zone)
524 else if (event.jaxis.value < -joystick_keymap.dead_zone)
527 tux.input.down = DOWN;
532 tux.input.down = DOWN;
537 case SDL_JOYHATMOTION:
538 if(event.jhat.value & SDL_HAT_UP) {
541 } else if(event.jhat.value & SDL_HAT_DOWN) {
543 tux.input.down = DOWN;
544 } else if(event.jhat.value & SDL_HAT_LEFT) {
545 tux.input.left = DOWN;
546 tux.input.right = UP;
547 } else if(event.jhat.value & SDL_HAT_RIGHT) {
549 tux.input.right = DOWN;
550 } else if(event.jhat.value == SDL_HAT_CENTERED) {
552 tux.input.right = UP;
558 case SDL_JOYBUTTONDOWN:
559 if (event.jbutton.button == joystick_keymap.a_button)
560 tux.input.jump = DOWN;
561 else if (event.jbutton.button == joystick_keymap.b_button)
562 tux.input.fire = DOWN;
563 else if (event.jbutton.button == joystick_keymap.start_button)
566 case SDL_JOYBUTTONUP:
567 if (event.jbutton.button == joystick_keymap.a_button)
569 else if (event.jbutton.button == joystick_keymap.b_button)
582 GameSession::check_end_conditions()
584 Player* tux = currentsector->player;
587 if(end_sequence && endsequence_timer.check()) {
588 exit_status = ES_LEVEL_FINISHED;
589 global_stats += last_swap_stats; // add swap points stats
591 } else if (!end_sequence && tux->is_dead()) {
592 player_status.bonus = PlayerStatus::NO_BONUS;
594 if (player_status.lives < 0) { // No more lives!?
595 exit_status = ES_GAME_OVER;
596 } else { // Still has lives, so reset Tux to the levelstart
605 GameSession::action(float elapsed_time)
608 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
610 // Update Tux and the World
611 currentsector->action(elapsed_time);
614 // respawning in new sector?
615 if(newsector != "" && newspawnpoint != "") {
616 Sector* sector = level->get_sector(newsector);
617 currentsector = sector;
618 currentsector->activate(newspawnpoint);
619 currentsector->play_music(LEVEL_MUSIC);
620 newsector = newspawnpoint = "";
627 currentsector->draw(*context);
628 drawstatus(*context);
632 int x = screen->h / 20;
633 for(int i = 0; i < x; ++i)
635 context->draw_filled_rect(
636 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
637 -((pause_menu_frame * i)%screen->w)
638 ,(i*20+pause_menu_frame)%screen->h),
639 Vector(screen->w,10),
640 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
642 context->draw_filled_rect(
643 Vector(0,0), Vector(screen->w, screen->h),
644 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
645 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
646 Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
650 sprintf(str1, _("Playing: "));
651 sprintf(str2, level->name.c_str());
653 context->draw_text(blue_text, str1,
654 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
655 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
656 context->draw_text(white_text, str2,
657 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
658 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
663 Menu::current()->draw(*context);
664 mouse_cursor->draw(*context);
667 context->do_drawing();
671 GameSession::process_menu()
673 Menu* menu = Menu::current();
678 if(menu == game_menu)
680 switch (game_menu->check())
685 case MNID_ABORTLEVEL:
687 exit_status = ES_LEVEL_ABORT;
691 else if(menu == options_menu)
693 process_options_menu();
695 else if(menu == load_game_menu )
697 process_load_game_menu();
702 GameSession::ExitStatus
705 Menu::set_current(0);
710 // Eat unneeded events
712 while(SDL_PollEvent(&event))
717 Uint32 lastticks = SDL_GetTicks();
718 fps_ticks = SDL_GetTicks();
720 while (exit_status == ES_NONE) {
721 Uint32 ticks = SDL_GetTicks();
722 float elapsed_time = float(ticks - lastticks) / 1000.;
724 global_time += elapsed_time;
728 if(elapsed_time > .025)
732 currentsector->player->input.old_fire = currentsector->player->input.fire;
733 currentsector->player->input.old_up = currentsector->player->input.old_up;
738 // Update the world state and all objects in the world
739 // Do that with a constante time-delta so that the game will run
740 // determistic and not different on different machines
741 if(!game_pause && !Menu::current())
744 check_end_conditions();
745 if (end_sequence == ENDSEQUENCE_RUNNING)
746 action(elapsed_time/2);
747 else if(end_sequence == NO_ENDSEQUENCE)
748 action(elapsed_time);
758 /* Time stops in pause mode */
759 if(game_pause || Menu::current())
764 //frame_rate.update();
767 if (time_left.check() && currentsector->player->dying == DYING_NOT
769 currentsector->player->kill(Player::KILL);
772 if(currentsector->player->invincible_timer.check() && !end_sequence)
774 currentsector->play_music(HERRING_MUSIC);
776 /* are we low on time ? */
777 else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
779 currentsector->play_music(HURRYUP_MUSIC);
781 /* or just normal music? */
782 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
784 currentsector->play_music(LEVEL_MUSIC);
787 /* Calculate frames per second */
792 if(SDL_GetTicks() - fps_ticks >= 500)
794 fps_fps = (float) fps_cnt / .5;
796 fps_ticks = SDL_GetTicks();
805 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
808 newspawnpoint = spawnpoint;
812 GameSession::start_sequence(const std::string& sequencename)
814 if(sequencename == "endsequence") {
818 end_sequence = ENDSEQUENCE_RUNNING;
819 endsequence_timer.start(7.0); // 7 seconds until we finish the map
821 SoundManager::get()->play_music(level_end_song, 0);
822 currentsector->player->invincible_timer.start(7.0);
824 // add left time to stats
825 global_stats.set_points(TIME_NEEDED_STAT,
826 int(time_left.get_period() - time_left.get_timeleft()));
828 if(level->get_end_sequence_type() == Level::FIREWORKS_ENDSEQ_ANIM) {
829 currentsector->add_object(new Fireworks());
832 std::cout << "Unknown sequence '" << sequencename << "'.\n";
838 GameSession::drawstatus(DrawingContext& context)
842 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
843 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
844 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
846 if(st_gl_mode == ST_GL_TEST)
848 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
849 LEFT_ALLIGN, LAYER_FOREGROUND1);
852 if(time_left.check()) {
853 context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
854 CENTER_ALLIGN, LAYER_FOREGROUND1);
855 } else if (time_left.get_timeleft() > TIME_WARNING
856 || int(global_time * 2.5) % 2) {
857 sprintf(str, " %d", int(time_left.get_timeleft()));
858 context.draw_text(white_text, _("TIME"),
859 Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
860 context.draw_text(gold_text, str,
861 Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
864 sprintf(str, " %d", player_status.distros);
865 context.draw_text(white_text, _("COINS"),
866 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
867 LEFT_ALLIGN, LAYER_FOREGROUND1);
868 context.draw_text(gold_text, str,
869 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
871 if (player_status.lives >= 5)
873 sprintf(str, "%dx", player_status.lives);
874 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
875 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
876 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
881 for(int i= 0; i < player_status.lives; ++i)
882 context.draw_surface(tux_life,
883 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
887 context.draw_text(white_text, _("LIVES"),
888 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
889 LEFT_ALLIGN, LAYER_FOREGROUND1);
893 sprintf(str, "%2.1f", fps_fps);
894 context.draw_text(white_text, "FPS",
895 Vector(screen->w - white_text->get_text_width("FPS "), 40),
896 LEFT_ALLIGN, LAYER_FOREGROUND1);
897 context.draw_text(gold_text, str,
898 Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
903 GameSession::drawresultscreen()
907 DrawingContext context;
908 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
909 i != currentsector->gameobjects.end(); ++i) {
910 Background* background = dynamic_cast<Background*> (*i);
912 background->draw(context);
916 context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
917 CENTER_ALLIGN, LAYER_FOREGROUND1);
919 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
920 context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
922 sprintf(str, _("COINS: %d"), player_status.distros);
923 context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
925 context.do_drawing();
928 wait_for_event(event,2000,5000,true);
931 std::string slotinfo(int slot)
934 std::string slotfile;
936 std::stringstream stream;
938 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
940 lisp_object_t* savegame = lisp_read_from_file(slotfile.c_str());
943 LispReader reader(lisp_cdr(savegame));
944 reader.read_string("title", title);
948 if (access(slotfile.c_str(), F_OK) == 0)
951 tmp = "Slot " + stream.str() + " - " + title;
953 tmp = "Slot " + stream.str() + " - Savegame";
956 tmp = std::string(_("Slot")) + " " + stream.str() + " - " + std::string(_("Free"));
961 bool process_load_game_menu()
963 int slot = load_game_menu->check();
965 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
967 std::stringstream stream;
969 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
971 if (access(slotfile.c_str(), F_OK) != 0)
973 shrink_fade(Vector(screen->w/2,screen->h/2), 600);
978 DrawingContext context;
979 context.draw_text(white_text, "Loading...",
980 Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
981 context.do_drawing();
983 WorldMapNS::WorldMap worldmap;
985 worldmap.set_map_filename("icyisland.stwm");
986 // Load the game or at least set the savegame_file variable
987 worldmap.loadgame(slotfile);
991 Menu::set_current(main_menu);