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 "game_session.hpp"
39 #include "video/screen.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
45 #include "player_status.hpp"
46 #include "object/particlesystem.hpp"
47 #include "object/background.hpp"
48 #include "object/tilemap.hpp"
49 #include "object/camera.hpp"
50 #include "object/player.hpp"
51 #include "lisp/lisp.hpp"
52 #include "lisp/parser.hpp"
53 #include "resources.hpp"
54 #include "worldmap.hpp"
56 #include "statistics.hpp"
58 #include "object/fireworks.hpp"
59 #include "textscroller.hpp"
60 #include "control/codecontroller.hpp"
61 #include "control/joystickkeyboardcontroller.hpp"
63 #include "file_system.hpp"
64 #include "gameconfig.hpp"
65 #include "gettext.hpp"
67 // the engine will be run with a logical framerate of 64fps.
68 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
70 static const float LOGICAL_FPS = 64.0;
72 GameSession* GameSession::current_ = 0;
74 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
75 Statistics* statistics)
76 : level(0), currentsector(0), mode(mode),
77 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
78 levelfile(levelfile_), best_level_statistics(statistics),
79 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
85 music_playing = false;
88 context = new DrawingContext();
94 GameSession::restart_level()
97 exit_status = ES_NONE;
98 end_sequence = NO_ENDSEQUENCE;
100 main_controller->reset();
106 level->load(levelfile);
108 global_stats.reset();
109 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
110 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
111 //global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
113 if(reset_sector != "") {
114 currentsector = level->get_sector(reset_sector);
116 std::stringstream msg;
117 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
118 throw std::runtime_error(msg.str());
120 currentsector->activate(reset_pos);
122 currentsector = level->get_sector("main");
124 throw std::runtime_error("Couldn't find main sector");
125 currentsector->activate("main");
128 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
133 currentsector->play_music(LEVEL_MUSIC);
134 music_playing = true;
137 if(capture_file != "")
138 record_demo(capture_file);
141 GameSession::~GameSession()
143 delete capture_demo_stream;
144 delete playback_demo_stream;
145 delete demo_controller;
147 delete end_sequence_controller;
153 GameSession::record_demo(const std::string& filename)
155 delete capture_demo_stream;
157 capture_demo_stream = new std::ofstream(filename.c_str());
158 if(!capture_demo_stream->good()) {
159 std::stringstream msg;
160 msg << "Couldn't open demo file '" << filename << "' for writing.";
161 throw std::runtime_error(msg.str());
163 capture_file = filename;
167 GameSession::play_demo(const std::string& filename)
169 delete playback_demo_stream;
170 delete demo_controller;
172 playback_demo_stream = new std::ifstream(filename.c_str());
173 if(!playback_demo_stream->good()) {
174 std::stringstream msg;
175 msg << "Couldn't open demo file '" << filename << "' for reading.";
176 throw std::runtime_error(msg.str());
179 Player& tux = *currentsector->player;
180 demo_controller = new CodeController();
181 tux.set_controller(demo_controller);
185 GameSession::levelintro()
189 DrawingContext context;
190 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
191 i != currentsector->gameobjects.end(); ++i) {
192 Background* background = dynamic_cast<Background*> (*i);
194 background->draw(context);
198 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
199 // CENTER_ALLIGN, LAYER_FOREGROUND1);
200 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
203 sprintf(str, "TUX x %d", player_status->lives);
204 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
205 CENTER_ALLIGN, LAYER_FOREGROUND1);
207 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
208 //TODO make author check case/blank-insensitive
209 context.draw_text(white_small_text,
210 std::string(_("contributed by ")) + level->get_author(),
211 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
214 if(best_level_statistics != NULL)
215 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
217 context.do_drawing();
219 wait_for_event(1.0, 3.0);
223 GameSession::on_escape_press()
225 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
226 return; // don't let the player open the menu, when he is dying
228 if(mode == ST_GL_TEST) {
229 exit_status = ES_LEVEL_ABORT;
230 } else if (!Menu::current()) {
231 Menu::set_current(game_menu);
232 game_menu->set_active_item(MNID_CONTINUE);
240 GameSession::process_events()
242 Player& tux = *currentsector->player;
243 main_controller->update();
245 // end of pause mode?
246 if(!Menu::current() && game_pause) {
250 if (end_sequence != NO_ENDSEQUENCE) {
251 if(end_sequence_controller == 0) {
252 end_sequence_controller = new CodeController();
253 tux.set_controller(end_sequence_controller);
256 end_sequence_controller->press(Controller::RIGHT);
258 if (int(last_x_pos) == int(tux.get_pos().x))
259 end_sequence_controller->press(Controller::JUMP);
260 last_x_pos = tux.get_pos().x;
263 main_controller->update();
265 while (SDL_PollEvent(&event)) {
266 /* Check for menu-events, if the menu is shown */
268 Menu::current()->event(event);
269 main_controller->process_event(event);
270 if(event.type == SDL_QUIT)
271 throw std::runtime_error("Received window close");
275 if(playback_demo_stream != 0) {
276 demo_controller->update();
283 playback_demo_stream->get(left);
284 playback_demo_stream->get(right);
285 playback_demo_stream->get(up);
286 playback_demo_stream->get(down);
287 playback_demo_stream->get(jump);
288 playback_demo_stream->get(action);
289 demo_controller->press(Controller::LEFT, left);
290 demo_controller->press(Controller::RIGHT, right);
291 demo_controller->press(Controller::UP, up);
292 demo_controller->press(Controller::DOWN, down);
293 demo_controller->press(Controller::JUMP, jump);
294 demo_controller->press(Controller::ACTION, action);
297 // save input for demo?
298 if(capture_demo_stream != 0) {
299 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
300 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
301 capture_demo_stream ->put(main_controller->hold(Controller::UP));
302 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
303 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
304 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
309 GameSession::try_cheats()
311 if(currentsector == 0)
313 Player& tux = *currentsector->player;
315 // Cheating words (the goal of this is really for debugging,
316 // but could be used for some cheating, nothing wrong with that)
317 if(main_controller->check_cheatcode("grow")) {
318 tux.set_bonus(GROWUP_BONUS, false);
320 if(main_controller->check_cheatcode("fire")) {
321 tux.set_bonus(FIRE_BONUS, false);
323 if(main_controller->check_cheatcode("ice")) {
324 tux.set_bonus(ICE_BONUS, false);
326 if(main_controller->check_cheatcode("lifeup")) {
327 player_status->lives++;
329 if(main_controller->check_cheatcode("lifedown")) {
330 player_status->lives--;
332 if(main_controller->check_cheatcode("grease")) {
333 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
335 if(main_controller->check_cheatcode("invincible")) {
336 // be invincle for the rest of the level
337 tux.invincible_timer.start(10000);
339 if(main_controller->check_cheatcode("shrink")) {
341 tux.kill(tux.SHRINK);
343 if(main_controller->check_cheatcode("kill")) {
344 // kill Tux, but without losing a life
345 player_status->lives++;
349 if(main_controller->check_cheatcode("grid")) {
351 debug_grid = !debug_grid;
354 if(main_controller->check_cheatcode("hover")) {
355 // toggle hover ability on/off
356 tux.enable_hover = !tux.enable_hover;
358 if(main_controller->check_cheatcode("gotoend")) {
359 // goes to the end of the level
361 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
362 currentsector->camera->reset(
363 Vector(tux.get_pos().x, tux.get_pos().y));
365 if(main_controller->check_cheatcode("finish")) {
366 // finish current sector
367 exit_status = ES_LEVEL_FINISHED;
368 // don't add points to stats though...
370 // temporary to help player's choosing a flapping
371 if(main_controller->check_cheatcode("marek")) {
372 tux.flapping_mode = Player::MAREK_FLAP;
374 if(main_controller->check_cheatcode("ricardo")) {
375 tux.flapping_mode = Player::RICARDO_FLAP;
377 if(main_controller->check_cheatcode("ryan")) {
378 tux.flapping_mode = Player::RYAN_FLAP;
383 GameSession::check_end_conditions()
385 Player* tux = currentsector->player;
388 if(end_sequence && endsequence_timer.check()) {
389 exit_status = ES_LEVEL_FINISHED;
391 } else if (!end_sequence && tux->is_dead()) {
392 if (player_status->lives < 0) { // No more lives!?
393 exit_status = ES_GAME_OVER;
394 } else { // Still has lives, so reset Tux to the levelstart
403 GameSession::update(float elapsed_time)
406 if(main_controller->pressed(Controller::PAUSE_MENU))
410 if(!currentsector->player->growing_timer.started()) {
411 // Update Tux and the World
412 currentsector->update(elapsed_time);
415 // respawning in new sector?
416 if(newsector != "" && newspawnpoint != "") {
417 Sector* sector = level->get_sector(newsector);
419 std::cerr << "Sector '" << newsector << "' not found.\n";
421 sector->activate(newspawnpoint);
422 sector->play_music(LEVEL_MUSIC);
423 currentsector = sector;
429 sound_manager->set_listener_position(currentsector->player->get_pos());
435 currentsector->draw(*context);
436 drawstatus(*context);
441 if(Menu::current()) {
442 Menu::current()->draw(*context);
445 context->do_drawing();
449 GameSession::draw_pause()
451 int x = SCREEN_HEIGHT / 20;
452 for(int i = 0; i < x; ++i) {
453 context->draw_filled_rect(
454 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
455 -((pause_menu_frame * i)%SCREEN_WIDTH)
456 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
457 Vector(SCREEN_WIDTH,10),
458 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
461 context->draw_filled_rect(
462 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
463 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
465 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
466 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
468 const char* str1 = _("Playing: ");
469 const char* str2 = level->get_name().c_str();
471 context->draw_text(blue_text, str1,
472 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
473 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
474 context->draw_text(white_text, str2,
475 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
476 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
481 GameSession::process_menu()
483 Menu* menu = Menu::current();
487 if(menu == game_menu) {
488 switch (game_menu->check()) {
490 Menu::set_current(0);
492 case MNID_ABORTLEVEL:
493 Menu::set_current(0);
494 exit_status = ES_LEVEL_ABORT;
497 } else if(menu == options_menu) {
498 process_options_menu();
499 } else if(menu == load_game_menu ) {
500 process_load_game_menu();
506 GameSession::ExitStatus
509 Menu::set_current(0);
514 // Eat unneeded events
516 while(SDL_PollEvent(&event))
521 Uint32 fps_ticks = SDL_GetTicks();
522 Uint32 fps_nextframe_ticks = SDL_GetTicks();
524 bool skipdraw = false;
526 while (exit_status == ES_NONE) {
527 // we run in a logical framerate so elapsed time is a constant
528 static const float elapsed_time = 1.0 / LOGICAL_FPS;
529 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
531 game_time += elapsed_time;
534 ticks = SDL_GetTicks();
535 if(ticks > fps_nextframe_ticks) {
536 if(skipdraw == true) {
537 // already skipped last frame? we have to slow down the game then...
539 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
541 // don't draw all frames when we're getting too slow
546 while(fps_nextframe_ticks > ticks) {
548 // If we really have to wait long, then do an imprecise SDL_Delay()
549 Uint32 diff = fps_nextframe_ticks - ticks;
551 SDL_Delay(diff - 10);
553 ticks = SDL_GetTicks();
556 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
559 float diff = SDL_GetTicks() - fps_nextframe_ticks;
561 // sets the ticks that must have elapsed
562 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
564 // sets the ticks that must have elapsed
565 // in order for the next frame to start.
566 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
573 // Update the world state and all objects in the world
574 // Do that with a constante time-delta so that the game will run
575 // determistic and not different on different machines
576 if(!game_pause && !Menu::current())
579 check_end_conditions();
580 if (end_sequence == ENDSEQUENCE_RUNNING)
581 update(elapsed_time/2);
582 else if(end_sequence == NO_ENDSEQUENCE)
583 update(elapsed_time);
594 sound_manager->update();
596 /* Time stops in pause mode */
597 if(game_pause || Menu::current())
602 //frame_rate.update();
605 if (currentsector->player->invincible_timer.started() && !end_sequence)
607 currentsector->play_music(HERRING_MUSIC);
609 /* or just normal music? */
610 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
612 currentsector->play_music(LEVEL_MUSIC);
615 /* Calculate frames per second */
620 if(SDL_GetTicks() - fps_ticks >= 500)
622 fps_fps = (float) fps_cnt / .5;
624 fps_ticks = SDL_GetTicks();
631 main_controller->reset();
636 GameSession::finish(bool win)
639 exit_status = ES_LEVEL_FINISHED;
641 exit_status = ES_LEVEL_ABORT;
645 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
648 newspawnpoint = spawnpoint;
652 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
654 reset_sector = sector;
659 GameSession::get_working_directory()
661 return FileSystem::dirname(levelfile);
665 GameSession::display_info_box(const std::string& text)
667 InfoBox* box = new InfoBox(text);
672 main_controller->update();
674 while (SDL_PollEvent(&event)) {
675 main_controller->process_event(event);
676 if(event.type == SDL_QUIT)
677 throw std::runtime_error("Received window close event");
680 if(main_controller->pressed(Controller::JUMP)
681 || main_controller->pressed(Controller::ACTION)
682 || main_controller->pressed(Controller::PAUSE_MENU)
683 || main_controller->pressed(Controller::MENU_SELECT))
687 sound_manager->update();
694 GameSession::start_sequence(const std::string& sequencename)
696 if(sequencename == "endsequence" || sequencename == "fireworks") {
700 end_sequence = ENDSEQUENCE_RUNNING;
701 endsequence_timer.start(7.0); // 7 seconds until we finish the map
703 sound_manager->play_music("music/leveldone.ogg", false);
704 currentsector->player->invincible_timer.start(7.0);
706 if(sequencename == "fireworks") {
707 currentsector->add_object(new Fireworks());
709 } else if(sequencename == "stoptux") {
710 end_sequence = ENDSEQUENCE_WAITING;
712 std::cout << "Unknown sequence '" << sequencename << "'.\n";
718 GameSession::drawstatus(DrawingContext& context)
720 player_status->draw(context);
722 if(config->show_fps) {
724 snprintf(str, sizeof(str), "%2.1f", fps_fps);
725 context.draw_text(white_text, "FPS",
726 Vector(SCREEN_WIDTH -
727 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
728 LEFT_ALLIGN, LAYER_FOREGROUND1);
729 context.draw_text(gold_text, str,
730 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
731 LEFT_ALLIGN, LAYER_FOREGROUND1);
736 GameSession::drawresultscreen()
740 DrawingContext context;
741 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
742 i != currentsector->gameobjects.end(); ++i) {
743 Background* background = dynamic_cast<Background*> (*i);
745 background->draw(context);
749 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
750 CENTER_ALLIGN, LAYER_FOREGROUND1);
752 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
753 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
755 sprintf(str, _("COINS: %d"), player_status->coins);
756 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
758 context.do_drawing();
760 wait_for_event(2.0, 5.0);
763 std::string slotinfo(int slot)
766 std::string slotfile;
768 std::stringstream stream;
770 slotfile = "save/slot" + stream.str() + ".stsg";
774 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
776 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
778 throw std::runtime_error("file is not a supertux-savegame.");
780 savegame->get("title", title);
781 } catch(std::exception& e) {
782 return std::string(_("Slot")) + " " + stream.str() + " - " +
783 std::string(_("Free"));
786 return std::string("Slot ") + stream.str() + " - " + title;
789 bool process_load_game_menu()
791 int slot = load_game_menu->check();
796 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
799 std::stringstream stream;
801 std::string slotfile = "save/slot" + stream.str() + ".stsg";
803 sound_manager->stop_music();
805 DrawingContext context;
806 context.draw_text(white_text, "Loading...",
807 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
808 CENTER_ALLIGN, LAYER_FOREGROUND1);
809 context.do_drawing();
811 WorldMapNS::WorldMap worldmap;
813 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
814 // Load the game or at least set the savegame_file variable
815 worldmap.loadgame(slotfile);
819 Menu::set_current(main_menu);