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"
66 #include "exceptions.hpp"
67 #include "flip_level_transformer.hpp"
69 // the engine will be run with a logical framerate of 64fps.
70 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
72 static const float LOGICAL_FPS = 64.0;
74 GameSession* GameSession::current_ = 0;
76 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
77 Statistics* statistics)
78 : level(0), currentsector(0), mode(mode),
79 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
80 levelfile(levelfile_), best_level_statistics(statistics),
81 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
87 music_playing = false;
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)
135 currentsector->play_music(LEVEL_MUSIC);
136 music_playing = true;
139 if(capture_file != "")
140 record_demo(capture_file);
143 GameSession::~GameSession()
145 delete capture_demo_stream;
146 delete playback_demo_stream;
147 delete demo_controller;
149 delete end_sequence_controller;
157 GameSession::record_demo(const std::string& filename)
159 delete capture_demo_stream;
161 capture_demo_stream = new std::ofstream(filename.c_str());
162 if(!capture_demo_stream->good()) {
163 std::stringstream msg;
164 msg << "Couldn't open demo file '" << filename << "' for writing.";
165 throw std::runtime_error(msg.str());
167 capture_file = filename;
171 GameSession::play_demo(const std::string& filename)
173 delete playback_demo_stream;
174 delete demo_controller;
176 playback_demo_stream = new std::ifstream(filename.c_str());
177 if(!playback_demo_stream->good()) {
178 std::stringstream msg;
179 msg << "Couldn't open demo file '" << filename << "' for reading.";
180 throw std::runtime_error(msg.str());
183 Player& tux = *currentsector->player;
184 demo_controller = new CodeController();
185 tux.set_controller(demo_controller);
189 GameSession::levelintro()
193 DrawingContext context;
194 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
195 i != currentsector->gameobjects.end(); ++i) {
196 Background* background = dynamic_cast<Background*> (*i);
198 background->draw(context);
202 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
203 // CENTER_ALLIGN, LAYER_FOREGROUND1);
204 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
207 sprintf(str, "TUX x %d", player_status->lives);
208 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
209 CENTER_ALLIGN, LAYER_FOREGROUND1);
211 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
212 //TODO make author check case/blank-insensitive
213 context.draw_text(white_small_text,
214 std::string(_("contributed by ")) + level->get_author(),
215 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
218 if(best_level_statistics != NULL)
219 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
221 context.do_drawing();
223 wait_for_event(1.0, 3.0);
227 GameSession::on_escape_press()
229 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
230 return; // don't let the player open the menu, when he is dying
232 if(mode == ST_GL_TEST) {
233 exit_status = ES_LEVEL_ABORT;
234 } else if (!Menu::current()) {
235 Menu::set_current(game_menu);
236 game_menu->set_active_item(MNID_CONTINUE);
244 GameSession::process_events()
246 Player& tux = *currentsector->player;
247 main_controller->update();
249 // end of pause mode?
250 if(!Menu::current() && game_pause) {
254 if (end_sequence != NO_ENDSEQUENCE) {
255 if(end_sequence_controller == 0) {
256 end_sequence_controller = new CodeController();
257 tux.set_controller(end_sequence_controller);
260 end_sequence_controller->press(Controller::RIGHT);
262 if (int(last_x_pos) == int(tux.get_pos().x))
263 end_sequence_controller->press(Controller::JUMP);
264 last_x_pos = tux.get_pos().x;
267 main_controller->update();
269 while (SDL_PollEvent(&event)) {
270 /* Check for menu-events, if the menu is shown */
272 Menu::current()->event(event);
273 main_controller->process_event(event);
274 if(event.type == SDL_QUIT)
275 throw graceful_shutdown();
279 if(playback_demo_stream != 0) {
280 demo_controller->update();
287 playback_demo_stream->get(left);
288 playback_demo_stream->get(right);
289 playback_demo_stream->get(up);
290 playback_demo_stream->get(down);
291 playback_demo_stream->get(jump);
292 playback_demo_stream->get(action);
293 demo_controller->press(Controller::LEFT, left);
294 demo_controller->press(Controller::RIGHT, right);
295 demo_controller->press(Controller::UP, up);
296 demo_controller->press(Controller::DOWN, down);
297 demo_controller->press(Controller::JUMP, jump);
298 demo_controller->press(Controller::ACTION, action);
301 // save input for demo?
302 if(capture_demo_stream != 0) {
303 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
304 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
305 capture_demo_stream ->put(main_controller->hold(Controller::UP));
306 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
307 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
308 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
313 GameSession::try_cheats()
315 if(currentsector == 0)
317 Player& tux = *currentsector->player;
319 // Cheating words (the goal of this is really for debugging,
320 // but could be used for some cheating, nothing wrong with that)
321 if(main_controller->check_cheatcode("grow")) {
322 tux.set_bonus(GROWUP_BONUS, false);
324 if(main_controller->check_cheatcode("fire")) {
325 tux.set_bonus(FIRE_BONUS, false);
327 if(main_controller->check_cheatcode("ice")) {
328 tux.set_bonus(ICE_BONUS, false);
330 if(main_controller->check_cheatcode("lifeup")) {
331 player_status->lives++;
333 if(main_controller->check_cheatcode("lifedown")) {
334 player_status->lives--;
336 if(main_controller->check_cheatcode("grease")) {
337 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
339 if(main_controller->check_cheatcode("invincible")) {
340 // be invincle for the rest of the level
341 tux.invincible_timer.start(10000);
343 if(main_controller->check_cheatcode("mortal")) {
344 // give up invincibility
345 tux.invincible_timer.stop();
347 if(main_controller->check_cheatcode("shrink")) {
349 tux.kill(tux.SHRINK);
351 if(main_controller->check_cheatcode("kill")) {
352 // kill Tux, but without losing a life
353 player_status->lives++;
356 if(main_controller->check_cheatcode("whereami")) {
357 std::cout << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << "." << std::endl;
360 if(main_controller->check_cheatcode("grid")) {
362 debug_grid = !debug_grid;
365 if(main_controller->check_cheatcode("gotoend")) {
366 // goes to the end of the level
368 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
369 currentsector->camera->reset(
370 Vector(tux.get_pos().x, tux.get_pos().y));
372 if(main_controller->check_cheatcode("flip")) {
373 FlipLevelTransformer flip_transformer;
374 flip_transformer.transform(GameSession::current()->get_current_level());
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...
384 GameSession::check_end_conditions()
386 Player* tux = currentsector->player;
389 if(end_sequence && endsequence_timer.check()) {
390 exit_status = ES_LEVEL_FINISHED;
392 } else if (!end_sequence && tux->is_dead()) {
393 if (player_status->lives < 0) { // No more lives!?
394 exit_status = ES_GAME_OVER;
395 } else { // Still has lives, so reset Tux to the levelstart
404 GameSession::update(float elapsed_time)
407 if(main_controller->pressed(Controller::PAUSE_MENU))
411 if(!currentsector->player->growing_timer.started()) {
412 // Update Tux and the World
413 currentsector->update(elapsed_time);
416 // respawning in new sector?
417 if(newsector != "" && newspawnpoint != "") {
418 Sector* sector = level->get_sector(newsector);
420 std::cerr << "Sector '" << newsector << "' not found.\n";
422 sector->activate(newspawnpoint);
423 sector->play_music(LEVEL_MUSIC);
424 currentsector = sector;
430 sound_manager->set_listener_position(currentsector->player->get_pos());
436 currentsector->draw(*context);
437 drawstatus(*context);
442 if(Menu::current()) {
443 Menu::current()->draw(*context);
446 context->do_drawing();
450 GameSession::draw_pause()
452 int x = SCREEN_HEIGHT / 20;
453 for(int i = 0; i < x; ++i) {
454 context->draw_filled_rect(
455 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
456 -((pause_menu_frame * i)%SCREEN_WIDTH)
457 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
458 Vector(SCREEN_WIDTH,10),
459 Color(0.1, 0.1, 0.1, static_cast<float>(rand() % 20 + 1) / 255.0),
460 LAYER_FOREGROUND1+1);
463 context->draw_filled_rect(
464 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
466 static_cast<float>(rand() % 50) / 255.0,
467 static_cast<float>(rand() % 50) / 255.0,
468 static_cast<float>(rand() % 50) / 255.0,
469 0.5), LAYER_FOREGROUND1);
471 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
472 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
474 const char* str1 = _("Playing: ");
475 const char* str2 = level->get_name().c_str();
477 context->draw_text(blue_text, str1,
478 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
479 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
480 context->draw_text(white_text, str2,
481 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
482 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
487 GameSession::process_menu()
489 Menu* menu = Menu::current();
493 if(menu == game_menu) {
494 switch (game_menu->check()) {
496 Menu::set_current(0);
498 case MNID_ABORTLEVEL:
499 Menu::set_current(0);
500 exit_status = ES_LEVEL_ABORT;
503 } else if(menu == options_menu) {
504 process_options_menu();
505 } else if(menu == load_game_menu ) {
506 process_load_game_menu();
512 GameSession::ExitStatus
515 Menu::set_current(0);
520 // Eat unneeded events
522 while(SDL_PollEvent(&event))
527 Uint32 fps_ticks = SDL_GetTicks();
528 Uint32 fps_nextframe_ticks = SDL_GetTicks();
530 bool skipdraw = false;
532 while (exit_status == ES_NONE) {
533 // we run in a logical framerate so elapsed time is a constant
534 static const float elapsed_time = 1.0 / LOGICAL_FPS;
535 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
537 game_time += elapsed_time;
540 ticks = SDL_GetTicks();
541 if(ticks > fps_nextframe_ticks) {
542 if(skipdraw == true) {
543 // already skipped last frame? we have to slow down the game then...
545 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
547 // don't draw all frames when we're getting too slow
552 while(fps_nextframe_ticks > ticks) {
554 // If we really have to wait long, then do an imprecise SDL_Delay()
555 Uint32 diff = fps_nextframe_ticks - ticks;
557 SDL_Delay(diff - 10);
559 ticks = SDL_GetTicks();
562 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
565 float diff = SDL_GetTicks() - fps_nextframe_ticks;
567 // sets the ticks that must have elapsed
568 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
570 // sets the ticks that must have elapsed
571 // in order for the next frame to start.
572 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
579 // Update the world state and all objects in the world
580 // Do that with a constante time-delta so that the game will run
581 // determistic and not different on different machines
582 if(!game_pause && !Menu::current())
585 check_end_conditions();
586 if (end_sequence == ENDSEQUENCE_RUNNING)
587 update(elapsed_time/2);
588 else if(end_sequence == NO_ENDSEQUENCE)
589 update(elapsed_time);
600 sound_manager->update();
602 /* Time stops in pause mode */
603 if(game_pause || Menu::current())
608 //frame_rate.update();
611 if (currentsector->player->invincible_timer.started() && !end_sequence)
613 currentsector->play_music(HERRING_MUSIC);
615 /* or just normal music? */
616 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
618 currentsector->play_music(LEVEL_MUSIC);
621 /* Calculate frames per second */
626 if(SDL_GetTicks() - fps_ticks >= 500)
628 fps_fps = (float) fps_cnt / .5;
630 fps_ticks = SDL_GetTicks();
637 main_controller->reset();
642 GameSession::finish(bool win)
645 exit_status = ES_LEVEL_FINISHED;
647 exit_status = ES_LEVEL_ABORT;
651 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
654 newspawnpoint = spawnpoint;
658 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
660 reset_sector = sector;
665 GameSession::get_working_directory()
667 return FileSystem::dirname(levelfile);
671 GameSession::display_info_box(const std::string& text)
673 InfoBox* box = new InfoBox(text);
678 main_controller->update();
680 while (SDL_PollEvent(&event)) {
681 main_controller->process_event(event);
682 if(event.type == SDL_QUIT)
683 throw graceful_shutdown();
686 if(main_controller->pressed(Controller::JUMP)
687 || main_controller->pressed(Controller::ACTION)
688 || main_controller->pressed(Controller::PAUSE_MENU)
689 || main_controller->pressed(Controller::MENU_SELECT))
691 else if(main_controller->pressed(Controller::DOWN))
693 else if(main_controller->pressed(Controller::UP))
697 sound_manager->update();
704 GameSession::start_sequence(const std::string& sequencename)
706 if(sequencename == "endsequence" || sequencename == "fireworks") {
710 end_sequence = ENDSEQUENCE_RUNNING;
711 endsequence_timer.start(7.0); // 7 seconds until we finish the map
713 sound_manager->play_music("music/leveldone.ogg", false);
714 currentsector->player->invincible_timer.start(7.0);
716 if(sequencename == "fireworks") {
717 currentsector->add_object(new Fireworks());
719 } else if(sequencename == "stoptux") {
720 end_sequence = ENDSEQUENCE_WAITING;
722 std::cout << "Unknown sequence '" << sequencename << "'.\n";
728 GameSession::drawstatus(DrawingContext& context)
730 player_status->draw(context);
732 if(config->show_fps) {
734 snprintf(str, sizeof(str), "%2.1f", fps_fps);
735 context.draw_text(white_text, "FPS",
736 Vector(SCREEN_WIDTH -
737 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
738 LEFT_ALLIGN, LAYER_FOREGROUND1);
739 context.draw_text(gold_text, str,
740 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
741 LEFT_ALLIGN, LAYER_FOREGROUND1);
746 GameSession::drawresultscreen()
750 DrawingContext context;
751 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
752 i != currentsector->gameobjects.end(); ++i) {
753 Background* background = dynamic_cast<Background*> (*i);
755 background->draw(context);
759 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
760 CENTER_ALLIGN, LAYER_FOREGROUND1);
762 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
763 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
765 sprintf(str, _("COINS: %d"), player_status->coins);
766 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
768 context.do_drawing();
770 wait_for_event(2.0, 5.0);
773 std::string slotinfo(int slot)
776 std::string slotfile;
778 std::stringstream stream;
780 slotfile = "save/slot" + stream.str() + ".stsg";
784 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
786 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
788 throw std::runtime_error("file is not a supertux-savegame.");
790 savegame->get("title", title);
791 } catch(std::exception& e) {
792 return std::string(_("Slot")) + " " + stream.str() + " - " +
793 std::string(_("Free"));
796 return std::string("Slot ") + stream.str() + " - " + title;
799 bool process_load_game_menu()
801 int slot = load_game_menu->check();
806 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
809 std::stringstream stream;
811 std::string slotfile = "save/slot" + stream.str() + ".stsg";
813 sound_manager->stop_music();
815 DrawingContext context;
816 context.draw_text(white_text, "Loading...",
817 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
818 CENTER_ALLIGN, LAYER_FOREGROUND1);
819 context.do_drawing();
821 WorldMapNS::WorldMap worldmap;
823 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
824 // Load the game or at least set the savegame_file variable
825 worldmap.loadgame(slotfile);
829 Menu::set_current(main_menu);