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();
94 last_swap_point = Vector(-1, -1);
95 last_swap_stats.reset();
101 GameSession::restart_level()
104 exit_status = ES_NONE;
105 end_sequence = NO_ENDSEQUENCE;
110 Vector tux_pos = Vector(-1,-1);
113 // Tux has lost a life, so we try to respawn him at the nearest reset point
114 tux_pos = currentsector->player->base;
122 level->load(levelfile);
124 global_stats.reset();
125 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
126 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
127 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
129 currentsector = level->get_sector("main");
131 Termination::abort("Level has no main sector.", "");
132 currentsector->activate("main");
135 // Set Tux to the nearest reset point
138 tux_pos = currentsector->get_best_spawn_point(tux_pos);
140 if(last_swap_point.x > tux_pos.x)
141 tux_pos = last_swap_point;
142 else // new swap point
144 last_swap_point = tux_pos;
146 last_swap_stats += global_stats;
149 currentsector->player->base.x = tux_pos.x;
150 currentsector->player->base.y = tux_pos.y;
152 // has to reset camera on swapping
153 currentsector->camera->reset(Vector(currentsector->player->base.x,
154 currentsector->player->base.y));
158 if (st_gl_mode != ST_GL_DEMO_GAME)
160 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
165 currentsector->play_music(LEVEL_MUSIC);
168 GameSession::~GameSession()
175 GameSession::levelintro(void)
177 SoundManager::get()->halt_music();
181 DrawingContext context;
182 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
183 i != currentsector->gameobjects.end(); ++i) {
184 Background* background = dynamic_cast<Background*> (*i);
186 background->draw(context);
190 // context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
191 // CENTER_ALLIGN, LAYER_FOREGROUND1);
192 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
195 sprintf(str, "TUX x %d", player_status.lives);
196 context.draw_text(white_text, str, Vector(screen->w/2, 210),
197 CENTER_ALLIGN, LAYER_FOREGROUND1);
199 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
200 //TODO make author check case/blank-insensitive
201 context.draw_text(white_small_text,
202 std::string(_("contributed by ")) + level->get_author(),
203 Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
206 if(best_level_statistics != NULL)
207 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
209 context.do_drawing();
212 wait_for_event(event,1000,3000,true);
217 GameSession::start_timers()
219 time_left.start(level->timelimit);
224 GameSession::on_escape_press()
226 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
227 return; // don't let the player open the menu, when he is dying
232 if(st_gl_mode == ST_GL_TEST) {
233 exit_status = ES_LEVEL_ABORT;
234 } else if (!Menu::current()) {
235 Menu::set_current(game_menu);
236 Ticks::pause_start();
241 GameSession::process_events()
243 if (end_sequence != NO_ENDSEQUENCE)
245 Player& tux = *currentsector->player;
247 tux.input.fire = false;
248 tux.input.left = false;
249 tux.input.right = true;
250 tux.input.down = false;
252 if (int(last_x_pos) == int(tux.get_pos().x))
255 tux.input.up = false;
257 last_x_pos = tux.get_pos().x;
260 while (SDL_PollEvent(&event))
262 /* Check for menu-events, if the menu is shown */
265 Menu::current()->event(event);
272 case SDL_QUIT: /* Quit event - quit: */
273 Termination::abort("Received window close", "");
276 case SDL_KEYDOWN: /* A keypress! */
278 SDLKey key = event.key.keysym.sym;
282 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
290 case SDL_JOYBUTTONDOWN:
291 if (event.jbutton.button == joystick_keymap.start_button)
299 if(!Menu::current() && !game_pause)
303 while (SDL_PollEvent(&event))
305 /* Check for menu-events, if the menu is shown */
308 Menu::current()->event(event);
314 Player& tux = *currentsector->player;
318 case SDL_QUIT: /* Quit event - quit: */
319 Termination::abort("Received window close", "");
322 case SDL_KEYDOWN: /* A keypress! */
324 SDLKey key = event.key.keysym.sym;
326 if(tux.key_event(key, true))
331 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
339 case SDL_KEYUP: /* A keyrelease! */
341 SDLKey key = event.key.keysym.sym;
343 if(tux.key_event(key, false))
352 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
353 tux.get_pos().x, tux.get_pos().y);
354 context->draw_text(white_text, buf,
355 Vector(0, screen->h - white_text->get_height()),
356 LEFT_ALLIGN, LAYER_FOREGROUND1);
357 context->do_drawing();
364 // "lifeup" cheat activates pause cause of the 'p'
365 // so work around to ignore it
366 if(compare_last(last_keys, "lifeu"))
377 Ticks::pause_start();
386 /* Check if chacrater is ASCII */
388 if((event.key.keysym.unicode & 0xFF80) == 0)
390 ch[0] = event.key.keysym.unicode & 0x7F;
393 last_keys.append(ch); // add to cheat keys
397 case SDL_JOYAXISMOTION:
398 if (event.jaxis.axis == joystick_keymap.x_axis)
400 if (event.jaxis.value < -joystick_keymap.dead_zone)
402 tux.input.left = true;
403 tux.input.right = false;
405 else if (event.jaxis.value > joystick_keymap.dead_zone)
407 tux.input.left = false;
408 tux.input.right = true;
412 tux.input.left = false;
413 tux.input.right = false;
416 else if (event.jaxis.axis == joystick_keymap.y_axis)
418 if (event.jaxis.value > joystick_keymap.dead_zone)
421 tux.input.down = false;
423 else if (event.jaxis.value < -joystick_keymap.dead_zone)
425 tux.input.up = false;
426 tux.input.down = true;
430 tux.input.up = false;
431 tux.input.down = false;
436 case SDL_JOYHATMOTION:
437 if(event.jhat.value & SDL_HAT_UP) {
439 tux.input.down = false;
440 } else if(event.jhat.value & SDL_HAT_DOWN) {
441 tux.input.up = false;
442 tux.input.down = true;
443 } else if(event.jhat.value & SDL_HAT_LEFT) {
444 tux.input.left = true;
445 tux.input.right = false;
446 } else if(event.jhat.value & SDL_HAT_RIGHT) {
447 tux.input.left = false;
448 tux.input.right = true;
449 } else if(event.jhat.value == SDL_HAT_CENTERED) {
450 tux.input.left = false;
451 tux.input.right = false;
452 tux.input.up = false;
453 tux.input.down = false;
457 case SDL_JOYBUTTONDOWN:
458 // FIXME: I assume we have to set old_jump and stuff here?!?
459 if (event.jbutton.button == joystick_keymap.a_button)
460 tux.input.jump = true;
461 else if (event.jbutton.button == joystick_keymap.b_button)
462 tux.input.fire = true;
463 else if (event.jbutton.button == joystick_keymap.start_button)
466 case SDL_JOYBUTTONUP:
467 if (event.jbutton.button == joystick_keymap.a_button)
468 tux.input.jump = false;
469 else if (event.jbutton.button == joystick_keymap.b_button)
470 tux.input.fire = false;
482 GameSession::handle_cheats()
484 Player& tux = *currentsector->player;
486 // Cheating words (the goal of this is really for debugging,
487 // but could be used for some cheating, nothing wrong with that)
488 if(compare_last(last_keys, "grow")) {
492 if(compare_last(last_keys, "fire")) {
494 tux.got_power = tux.FIRE_POWER;
497 if(compare_last(last_keys, "ice")) {
499 tux.got_power = tux.ICE_POWER;
502 if(compare_last(last_keys, "lifeup")) {
503 player_status.lives++;
506 if(compare_last(last_keys, "lifedown")) {
507 player_status.lives--;
510 if(compare_last(last_keys, "grease")) {
511 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
514 if(compare_last(last_keys, "invincible")) {
515 // be invincle for the rest of the level
516 tux.invincible_timer.start(10000);
519 if(compare_last(last_keys, "shrink")) {
521 tux.kill(tux.SHRINK);
524 if(compare_last(last_keys, "kill")) {
525 // kill Tux, but without losing a life
526 player_status.lives++;
530 if(compare_last(last_keys, "grid")) {
532 debug_grid = !debug_grid;
535 if(compare_last(last_keys, "hover")) {
536 // toggle hover ability on/off
537 tux.enable_hover = !tux.enable_hover;
540 if(compare_last(last_keys, "gotoend")) {
541 // goes to the end of the level
543 (currentsector->solids->get_width()*32) - (screen->w*2), 0));
544 currentsector->camera->reset(
545 Vector(tux.get_pos().x, tux.get_pos().y));
548 if(compare_last(last_keys, "finish")) {
549 // finish current sector
550 exit_status = ES_LEVEL_FINISHED;
551 // don't add points to stats though...
553 // temporary to help player's choosing a flapping
554 if(compare_last(last_keys, "marek")) {
555 tux.flapping_mode = Player::MAREK_FLAP;
558 if(compare_last(last_keys, "ricardo")) {
559 tux.flapping_mode = Player::RICARDO_FLAP;
562 if(compare_last(last_keys, "ryan")) {
563 tux.flapping_mode = Player::RYAN_FLAP;
569 GameSession::check_end_conditions()
571 Player* tux = currentsector->player;
574 if(end_sequence && endsequence_timer.check()) {
575 exit_status = ES_LEVEL_FINISHED;
576 global_stats += last_swap_stats; // add swap points stats
578 } else if (!end_sequence && tux->is_dead()) {
579 player_status.bonus = PlayerStatus::NO_BONUS;
581 if (player_status.lives < 0) { // No more lives!?
582 exit_status = ES_GAME_OVER;
583 } else { // Still has lives, so reset Tux to the levelstart
592 GameSession::action(float elapsed_time)
595 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
597 // Update Tux and the World
598 currentsector->action(elapsed_time);
601 // respawning in new sector?
602 if(newsector != "" && newspawnpoint != "") {
603 Sector* sector = level->get_sector(newsector);
604 currentsector = sector;
605 currentsector->activate(newspawnpoint);
606 currentsector->play_music(LEVEL_MUSIC);
607 newsector = newspawnpoint = "";
614 currentsector->draw(*context);
615 drawstatus(*context);
619 int x = screen->h / 20;
620 for(int i = 0; i < x; ++i)
622 context->draw_filled_rect(
623 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
624 -((pause_menu_frame * i)%screen->w)
625 ,(i*20+pause_menu_frame)%screen->h),
626 Vector(screen->w,10),
627 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
629 context->draw_filled_rect(
630 Vector(0,0), Vector(screen->w, screen->h),
631 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
632 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
633 Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
637 sprintf(str1, _("Playing: "));
638 sprintf(str2, level->name.c_str());
640 context->draw_text(blue_text, str1,
641 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
642 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
643 context->draw_text(white_text, str2,
644 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
645 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
650 Menu::current()->draw(*context);
651 mouse_cursor->draw(*context);
654 context->do_drawing();
658 GameSession::process_menu()
660 Menu* menu = Menu::current();
665 if(menu == game_menu)
667 switch (game_menu->check())
672 case MNID_ABORTLEVEL:
674 exit_status = ES_LEVEL_ABORT;
678 else if(menu == options_menu)
680 process_options_menu();
682 else if(menu == load_game_menu )
684 process_load_game_menu();
689 GameSession::ExitStatus
692 Menu::set_current(0);
697 // Eat unneeded events
699 while(SDL_PollEvent(&event))
704 Uint32 lastticks = SDL_GetTicks();
705 fps_ticks = SDL_GetTicks();
707 while (exit_status == ES_NONE) {
708 Uint32 ticks = SDL_GetTicks();
709 float elapsed_time = float(ticks - lastticks) / 1000.;
711 global_time += elapsed_time;
715 if(elapsed_time > .025)
719 currentsector->player->input.old_fire = currentsector->player->input.fire;
720 currentsector->player->input.old_up = currentsector->player->input.old_up;
725 // Update the world state and all objects in the world
726 // Do that with a constante time-delta so that the game will run
727 // determistic and not different on different machines
728 if(!game_pause && !Menu::current())
731 check_end_conditions();
732 if (end_sequence == ENDSEQUENCE_RUNNING)
733 action(elapsed_time/2);
734 else if(end_sequence == NO_ENDSEQUENCE)
735 action(elapsed_time);
745 /* Time stops in pause mode */
746 if(game_pause || Menu::current())
751 //frame_rate.update();
754 if (time_left.check() && !end_sequence)
755 currentsector->player->kill(Player::KILL);
758 if (currentsector->player->invincible_timer.started() && !end_sequence)
760 currentsector->play_music(HERRING_MUSIC);
762 /* are we low on time ? */
763 else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
765 currentsector->play_music(HURRYUP_MUSIC);
767 /* or just normal music? */
768 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
770 currentsector->play_music(LEVEL_MUSIC);
773 /* Calculate frames per second */
778 if(SDL_GetTicks() - fps_ticks >= 500)
780 fps_fps = (float) fps_cnt / .5;
782 fps_ticks = SDL_GetTicks();
791 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
794 newspawnpoint = spawnpoint;
798 GameSession::start_sequence(const std::string& sequencename)
800 if(sequencename == "endsequence" || sequencename == "fireworks") {
804 end_sequence = ENDSEQUENCE_RUNNING;
805 endsequence_timer.start(7.0); // 7 seconds until we finish the map
807 SoundManager::get()->play_music(level_end_song, 0);
808 currentsector->player->invincible_timer.start(7.0);
810 // add left time to stats
811 global_stats.set_points(TIME_NEEDED_STAT,
812 int(time_left.get_period() - time_left.get_timeleft()));
814 if(sequencename == "fireworks") {
815 currentsector->add_object(new Fireworks());
817 } else if(sequencename == "stoptux") {
818 end_sequence = ENDSEQUENCE_WAITING;
820 std::cout << "Unknown sequence '" << sequencename << "'.\n";
826 GameSession::drawstatus(DrawingContext& context)
830 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
831 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
832 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
834 if(st_gl_mode == ST_GL_TEST)
836 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
837 LEFT_ALLIGN, LAYER_FOREGROUND1);
840 if(time_left.get_timeleft() < 0) {
841 context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
842 CENTER_ALLIGN, LAYER_FOREGROUND1);
843 } else if (time_left.get_timeleft() > TIME_WARNING
844 || int(global_time * 2.5) % 2) {
845 sprintf(str, " %d", int(time_left.get_timeleft()));
846 context.draw_text(white_text, _("TIME"),
847 Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
848 context.draw_text(gold_text, str,
849 Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
852 sprintf(str, " %d", player_status.distros);
853 context.draw_text(white_text, _("COINS"),
854 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
855 LEFT_ALLIGN, LAYER_FOREGROUND1);
856 context.draw_text(gold_text, str,
857 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
859 if (player_status.lives >= 5)
861 sprintf(str, "%dx", player_status.lives);
862 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
863 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
864 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
869 for(int i= 0; i < player_status.lives; ++i)
870 context.draw_surface(tux_life,
871 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
875 context.draw_text(white_text, _("LIVES"),
876 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
877 LEFT_ALLIGN, LAYER_FOREGROUND1);
881 sprintf(str, "%2.1f", fps_fps);
882 context.draw_text(white_text, "FPS",
883 Vector(screen->w - white_text->get_text_width("FPS "), 40),
884 LEFT_ALLIGN, LAYER_FOREGROUND1);
885 context.draw_text(gold_text, str,
886 Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
891 GameSession::drawresultscreen()
895 DrawingContext context;
896 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
897 i != currentsector->gameobjects.end(); ++i) {
898 Background* background = dynamic_cast<Background*> (*i);
900 background->draw(context);
904 context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
905 CENTER_ALLIGN, LAYER_FOREGROUND1);
907 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
908 context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
910 sprintf(str, _("COINS: %d"), player_status.distros);
911 context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
913 context.do_drawing();
916 wait_for_event(event,2000,5000,true);
919 std::string slotinfo(int slot)
922 std::string slotfile;
924 std::stringstream stream;
926 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
930 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
932 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
934 throw std::runtime_error("file is not a supertux-savegame.");
936 savegame->get("title", title);
937 } catch(std::exception& e) {
938 return std::string(_("Slot")) + " " + stream.str() + " - " +
939 std::string(_("Free"));
942 return std::string("Slot ") + stream.str() + " - " + title;
945 bool process_load_game_menu()
947 int slot = load_game_menu->check();
949 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
951 std::stringstream stream;
953 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
956 DrawingContext context;
957 context.draw_text(white_text, "Loading...",
958 Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
959 context.do_drawing();
961 WorldMapNS::WorldMap worldmap;
963 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
964 // Load the game or at least set the savegame_file variable
965 worldmap.loadgame(slotfile);
969 Menu::set_current(main_menu);