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.
39 #include <sys/types.h>
43 #include "app/globals.h"
44 #include "game_session.h"
45 #include "video/screen.h"
46 #include "app/setup.h"
51 #include "player_status.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"
63 #include "statistics.h"
65 #include "object/fireworks.h"
66 #include "textscroller.h"
67 #include "control/codecontroller.h"
68 #include "control/joystickkeyboardcontroller.h"
71 // the engine will be run with a lofical framerate of 64fps.
72 // We choose 64fps here because it is a power of 2, so 1/64 gives an "even"
74 static const float LOGICAL_FPS = 64.0;
76 GameSession* GameSession::current_ = 0;
78 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
79 Statistics* statistics)
80 : level(0), currentsector(0), mode(mode),
81 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
82 levelfile(levelfile_), best_level_statistics(statistics),
83 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
90 context = new DrawingContext();
96 GameSession::restart_level()
99 exit_status = ES_NONE;
100 end_sequence = NO_ENDSEQUENCE;
102 main_controller->reset();
108 level->load(levelfile);
110 global_stats.reset();
111 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
112 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
113 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
115 if(reset_sector != "") {
116 currentsector = level->get_sector(reset_sector);
118 std::stringstream msg;
119 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
120 throw std::runtime_error(msg.str());
122 currentsector->activate(reset_pos);
124 currentsector = level->get_sector("main");
126 throw std::runtime_error("Couldn't find main sector");
127 currentsector->activate("main");
130 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
134 currentsector->play_music(LEVEL_MUSIC);
136 if(capture_file != "")
137 record_demo(capture_file);
140 GameSession::~GameSession()
142 delete capture_demo_stream;
143 delete playback_demo_stream;
144 delete demo_controller;
146 delete end_sequence_controller;
152 GameSession::record_demo(const std::string& filename)
154 delete capture_demo_stream;
156 capture_demo_stream = new std::ofstream(filename.c_str());
157 if(!capture_demo_stream->good()) {
158 std::stringstream msg;
159 msg << "Couldn't open demo file '" << filename << "' for writing.";
160 throw std::runtime_error(msg.str());
162 capture_file = filename;
166 GameSession::play_demo(const std::string& filename)
168 delete playback_demo_stream;
169 delete demo_controller;
171 playback_demo_stream = new std::ifstream(filename.c_str());
172 if(!playback_demo_stream->good()) {
173 std::stringstream msg;
174 msg << "Couldn't open demo file '" << filename << "' for reading.";
175 throw std::runtime_error(msg.str());
178 Player& tux = *currentsector->player;
179 demo_controller = new CodeController();
180 tux.set_controller(demo_controller);
184 GameSession::levelintro()
186 sound_manager->halt_music();
190 DrawingContext context;
191 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
192 i != currentsector->gameobjects.end(); ++i) {
193 Background* background = dynamic_cast<Background*> (*i);
195 background->draw(context);
199 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
200 // CENTER_ALLIGN, LAYER_FOREGROUND1);
201 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
204 sprintf(str, "TUX x %d", player_status.lives);
205 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
206 CENTER_ALLIGN, LAYER_FOREGROUND1);
208 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
209 //TODO make author check case/blank-insensitive
210 context.draw_text(white_small_text,
211 std::string(_("contributed by ")) + level->get_author(),
212 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
215 if(best_level_statistics != NULL)
216 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
218 context.do_drawing();
221 wait_for_event(event,1000,3000,true);
226 GameSession::start_timers()
228 time_left.start(level->timelimit);
233 GameSession::on_escape_press()
235 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
236 return; // don't let the player open the menu, when he is dying
238 if(mode == ST_GL_TEST) {
239 exit_status = ES_LEVEL_ABORT;
240 } else if (!Menu::current()) {
241 Menu::set_current(game_menu);
242 game_menu->set_active_item(MNID_CONTINUE);
243 Ticks::pause_start();
252 GameSession::process_events()
254 Player& tux = *currentsector->player;
255 main_controller->update();
257 // end of pause mode?
258 if(!Menu::current() && game_pause) {
263 if (end_sequence != NO_ENDSEQUENCE) {
264 if(end_sequence_controller == 0) {
265 end_sequence_controller = new CodeController();
266 tux.set_controller(end_sequence_controller);
269 end_sequence_controller->press(Controller::RIGHT);
271 if (int(last_x_pos) == int(tux.get_pos().x))
272 end_sequence_controller->press(Controller::JUMP);
273 last_x_pos = tux.get_pos().x;
276 main_controller->update();
278 while (SDL_PollEvent(&event)) {
279 /* Check for menu-events, if the menu is shown */
281 Menu::current()->event(event);
282 main_controller->process_event(event);
283 if(event.type == SDL_QUIT)
284 throw std::runtime_error("Received window close");
288 if(playback_demo_stream != 0) {
289 demo_controller->update();
296 playback_demo_stream->get(left);
297 playback_demo_stream->get(right);
298 playback_demo_stream->get(up);
299 playback_demo_stream->get(down);
300 playback_demo_stream->get(jump);
301 playback_demo_stream->get(action);
302 demo_controller->press(Controller::LEFT, left);
303 demo_controller->press(Controller::RIGHT, right);
304 demo_controller->press(Controller::UP, up);
305 demo_controller->press(Controller::DOWN, down);
306 demo_controller->press(Controller::JUMP, jump);
307 demo_controller->press(Controller::ACTION, action);
310 // save input for demo?
311 if(capture_demo_stream != 0) {
312 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
313 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
314 capture_demo_stream ->put(main_controller->hold(Controller::UP));
315 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
316 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
317 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
322 GameSession::try_cheats()
324 Player& tux = *currentsector->player;
326 // Cheating words (the goal of this is really for debugging,
327 // but could be used for some cheating, nothing wrong with that)
328 if(main_controller->check_cheatcode("grow")) {
329 tux.set_bonus(GROWUP_BONUS, false);
331 if(main_controller->check_cheatcode("fire")) {
332 tux.set_bonus(FIRE_BONUS, false);
334 if(main_controller->check_cheatcode("ice")) {
335 tux.set_bonus(ICE_BONUS, false);
337 if(main_controller->check_cheatcode("lifeup")) {
338 player_status.lives++;
340 if(main_controller->check_cheatcode("lifedown")) {
341 player_status.lives--;
343 if(main_controller->check_cheatcode("grease")) {
344 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
346 if(main_controller->check_cheatcode("invincible")) {
347 // be invincle for the rest of the level
348 tux.invincible_timer.start(10000);
350 if(main_controller->check_cheatcode("shrink")) {
352 tux.kill(tux.SHRINK);
354 if(main_controller->check_cheatcode("kill")) {
355 // kill Tux, but without losing a life
356 player_status.lives++;
360 if(main_controller->check_cheatcode("grid")) {
362 debug_grid = !debug_grid;
365 if(main_controller->check_cheatcode("hover")) {
366 // toggle hover ability on/off
367 tux.enable_hover = !tux.enable_hover;
369 if(main_controller->check_cheatcode("gotoend")) {
370 // goes to the end of the level
372 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
373 currentsector->camera->reset(
374 Vector(tux.get_pos().x, tux.get_pos().y));
376 if(main_controller->check_cheatcode("finish")) {
377 // finish current sector
378 exit_status = ES_LEVEL_FINISHED;
379 // don't add points to stats though...
381 // temporary to help player's choosing a flapping
382 if(main_controller->check_cheatcode("marek")) {
383 tux.flapping_mode = Player::MAREK_FLAP;
385 if(main_controller->check_cheatcode("ricardo")) {
386 tux.flapping_mode = Player::RICARDO_FLAP;
388 if(main_controller->check_cheatcode("ryan")) {
389 tux.flapping_mode = Player::RYAN_FLAP;
394 GameSession::check_end_conditions()
396 Player* tux = currentsector->player;
399 if(end_sequence && endsequence_timer.check()) {
400 exit_status = ES_LEVEL_FINISHED;
402 } else if (!end_sequence && tux->is_dead()) {
403 if (player_status.lives < 0) { // No more lives!?
404 exit_status = ES_GAME_OVER;
405 } else { // Still has lives, so reset Tux to the levelstart
414 GameSession::action(float elapsed_time)
417 if(main_controller->pressed(Controller::PAUSE_MENU))
421 if(!currentsector->player->growing_timer.started()) {
422 // Update Tux and the World
423 currentsector->action(elapsed_time);
426 // respawning in new sector?
427 if(newsector != "" && newspawnpoint != "") {
428 Sector* sector = level->get_sector(newsector);
430 std::cerr << "Sector '" << newsector << "' not found.\n";
432 sector->activate(newspawnpoint);
433 sector->play_music(LEVEL_MUSIC);
434 currentsector = sector;
443 currentsector->draw(*context);
444 drawstatus(*context);
449 if(Menu::current()) {
450 Menu::current()->draw(*context);
451 mouse_cursor->draw(*context);
454 context->do_drawing();
458 GameSession::draw_pause()
460 int x = SCREEN_HEIGHT / 20;
461 for(int i = 0; i < x; ++i) {
462 context->draw_filled_rect(
463 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
464 -((pause_menu_frame * i)%SCREEN_WIDTH)
465 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
466 Vector(SCREEN_WIDTH,10),
467 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
470 context->draw_filled_rect(
471 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
472 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
474 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
475 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
477 const char* str1 = _("Playing: ");
478 const char* str2 = level->get_name().c_str();
480 context->draw_text(blue_text, str1,
481 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
482 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
483 context->draw_text(white_text, str2,
484 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
485 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
490 GameSession::process_menu()
492 Menu* menu = Menu::current();
496 if(menu == game_menu) {
497 switch (game_menu->check()) {
499 Menu::set_current(0);
501 case MNID_ABORTLEVEL:
502 Menu::set_current(0);
503 exit_status = ES_LEVEL_ABORT;
506 } else if(menu == options_menu) {
507 process_options_menu();
508 } else if(menu == load_game_menu ) {
509 process_load_game_menu();
515 GameSession::ExitStatus
518 Menu::set_current(0);
523 // Eat unneeded events
525 while(SDL_PollEvent(&event))
530 Uint32 fps_ticks = SDL_GetTicks();
531 Uint32 fps_nextframe_ticks = SDL_GetTicks();
533 bool skipdraw = false;
535 while (exit_status == ES_NONE) {
536 // we run in a logical framerate so elapsed time is a constant
537 static const float elapsed_time = 1.0 / LOGICAL_FPS;
538 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
540 global_time += elapsed_time;
545 ticks = SDL_GetTicks();
546 if(ticks > fps_nextframe_ticks) {
547 // don't draw all frames when we're getting too slow
550 while(fps_nextframe_ticks > ticks) {
552 // If we really have to wait long, then do an imprecise SDL_Delay()
553 Uint32 diff = fps_nextframe_ticks - ticks;
555 SDL_Delay(diff - 10);
557 ticks = SDL_GetTicks();
560 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
563 float diff = SDL_GetTicks() - fps_nextframe_ticks;
565 // sets the ticks that must have elapsed
566 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
568 // sets the ticks that must have elapsed
569 // in order for the next frame to start.
570 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
577 // Update the world state and all objects in the world
578 // Do that with a constante time-delta so that the game will run
579 // determistic and not different on different machines
580 if(!game_pause && !Menu::current())
583 check_end_conditions();
584 if (end_sequence == ENDSEQUENCE_RUNNING)
585 action(elapsed_time/2);
586 else if(end_sequence == NO_ENDSEQUENCE)
587 action(elapsed_time);
597 /* Time stops in pause mode */
598 if(game_pause || Menu::current())
603 //frame_rate.update();
606 if (time_left.check() && !end_sequence)
607 currentsector->player->kill(Player::KILL);
610 if (currentsector->player->invincible_timer.started() && !end_sequence)
612 currentsector->play_music(HERRING_MUSIC);
614 /* or just normal music? */
615 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
617 currentsector->play_music(LEVEL_MUSIC);
620 /* Calculate frames per second */
625 if(SDL_GetTicks() - fps_ticks >= 500)
627 fps_fps = (float) fps_cnt / .5;
629 fps_ticks = SDL_GetTicks();
635 main_controller->reset();
640 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
643 newspawnpoint = spawnpoint;
647 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
649 reset_sector = sector;
654 GameSession::display_info_box(const std::string& text)
656 InfoBox* box = new InfoBox(text);
661 main_controller->update();
663 while (SDL_PollEvent(&event)) {
664 main_controller->process_event(event);
665 if(event.type == SDL_QUIT)
666 throw std::runtime_error("Received window close event");
669 if(main_controller->pressed(Controller::JUMP)
670 || main_controller->pressed(Controller::ACTION)
671 || main_controller->pressed(Controller::PAUSE_MENU)
672 || main_controller->pressed(Controller::MENU_SELECT))
682 GameSession::start_sequence(const std::string& sequencename)
684 if(sequencename == "endsequence" || sequencename == "fireworks") {
688 end_sequence = ENDSEQUENCE_RUNNING;
689 endsequence_timer.start(7.0); // 7 seconds until we finish the map
691 sound_manager->play_music(level_end_song, 0);
692 currentsector->player->invincible_timer.start(7.0);
694 // add left time to stats
695 global_stats.set_points(TIME_NEEDED_STAT,
696 int(time_left.get_period() - time_left.get_timeleft()));
698 if(sequencename == "fireworks") {
699 currentsector->add_object(new Fireworks());
701 } else if(sequencename == "stoptux") {
702 end_sequence = ENDSEQUENCE_WAITING;
704 std::cout << "Unknown sequence '" << sequencename << "'.\n";
710 GameSession::drawstatus(DrawingContext& context)
714 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
715 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
716 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
718 if(mode == ST_GL_TEST) {
719 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
720 LEFT_ALLIGN, LAYER_FOREGROUND1);
723 if(time_left.get_timeleft() < 0) {
724 context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, 0),
725 CENTER_ALLIGN, LAYER_FOREGROUND1);
726 } else if (time_left.get_timeleft() > TIME_WARNING
727 || int(global_time * 2.5) % 2) {
728 sprintf(str, " %d", int(time_left.get_timeleft()));
729 context.draw_text(white_text, _("TIME"),
730 Vector(SCREEN_WIDTH/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
731 context.draw_text(gold_text, str,
732 Vector(SCREEN_WIDTH/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
735 sprintf(str, " %d", player_status.coins);
736 context.draw_text(white_text, _("COINS"),
737 Vector(SCREEN_WIDTH - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
738 LEFT_ALLIGN, LAYER_FOREGROUND1);
739 context.draw_text(gold_text, str,
740 Vector(SCREEN_WIDTH - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
742 if (player_status.lives >= 5)
744 sprintf(str, "%dx", player_status.lives);
745 float x = SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w;
746 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
747 context.draw_surface(tux_life, Vector(SCREEN_WIDTH - 16, 20),
752 for(int i= 0; i < player_status.lives; ++i)
753 context.draw_surface(tux_life,
754 Vector(SCREEN_WIDTH - tux_life->w*4 +(tux_life->w*i), 20),
758 context.draw_text(white_text, _("LIVES"),
759 Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
760 LEFT_ALLIGN, LAYER_FOREGROUND1);
762 if(config->show_fps) {
763 sprintf(str, "%2.1f", fps_fps);
764 context.draw_text(white_text, "FPS",
765 Vector(SCREEN_WIDTH -
766 white_text->get_text_width("FPS "), 40),
767 LEFT_ALLIGN, LAYER_FOREGROUND1);
768 context.draw_text(gold_text, str,
769 Vector(SCREEN_WIDTH-4*16, 40),
770 LEFT_ALLIGN, LAYER_FOREGROUND1);
775 GameSession::drawresultscreen()
779 DrawingContext context;
780 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
781 i != currentsector->gameobjects.end(); ++i) {
782 Background* background = dynamic_cast<Background*> (*i);
784 background->draw(context);
788 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
789 CENTER_ALLIGN, LAYER_FOREGROUND1);
791 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
792 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
794 sprintf(str, _("COINS: %d"), player_status.coins);
795 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
797 context.do_drawing();
800 wait_for_event(event,2000,5000,true);
803 std::string slotinfo(int slot)
806 std::string slotfile;
808 std::stringstream stream;
810 slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
814 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
816 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
818 throw std::runtime_error("file is not a supertux-savegame.");
820 savegame->get("title", title);
821 } catch(std::exception& e) {
822 return std::string(_("Slot")) + " " + stream.str() + " - " +
823 std::string(_("Free"));
826 return std::string("Slot ") + stream.str() + " - " + title;
829 bool process_load_game_menu()
831 int slot = load_game_menu->check();
833 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
835 std::stringstream stream;
837 std::string slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
840 DrawingContext context;
841 context.draw_text(white_text, "Loading...",
842 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
843 context.do_drawing();
845 WorldMapNS::WorldMap worldmap;
847 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
848 // Load the game or at least set the savegame_file variable
849 worldmap.loadgame(slotfile);
853 Menu::set_current(main_menu);