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;
155 GameSession::record_demo(const std::string& filename)
157 delete capture_demo_stream;
159 capture_demo_stream = new std::ofstream(filename.c_str());
160 if(!capture_demo_stream->good()) {
161 std::stringstream msg;
162 msg << "Couldn't open demo file '" << filename << "' for writing.";
163 throw std::runtime_error(msg.str());
165 capture_file = filename;
169 GameSession::play_demo(const std::string& filename)
171 delete playback_demo_stream;
172 delete demo_controller;
174 playback_demo_stream = new std::ifstream(filename.c_str());
175 if(!playback_demo_stream->good()) {
176 std::stringstream msg;
177 msg << "Couldn't open demo file '" << filename << "' for reading.";
178 throw std::runtime_error(msg.str());
181 Player& tux = *currentsector->player;
182 demo_controller = new CodeController();
183 tux.set_controller(demo_controller);
187 GameSession::levelintro()
191 DrawingContext context;
192 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
193 i != currentsector->gameobjects.end(); ++i) {
194 Background* background = dynamic_cast<Background*> (*i);
196 background->draw(context);
200 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
201 // CENTER_ALLIGN, LAYER_FOREGROUND1);
202 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
205 sprintf(str, "TUX x %d", player_status->lives);
206 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
207 CENTER_ALLIGN, LAYER_FOREGROUND1);
209 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
210 //TODO make author check case/blank-insensitive
211 context.draw_text(white_small_text,
212 std::string(_("contributed by ")) + level->get_author(),
213 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
216 if(best_level_statistics != NULL)
217 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
219 context.do_drawing();
221 wait_for_event(1.0, 3.0);
225 GameSession::on_escape_press()
227 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
228 return; // don't let the player open the menu, when he is dying
230 if(mode == ST_GL_TEST) {
231 exit_status = ES_LEVEL_ABORT;
232 } else if (!Menu::current()) {
233 Menu::set_current(game_menu);
234 game_menu->set_active_item(MNID_CONTINUE);
242 GameSession::process_events()
244 Player& tux = *currentsector->player;
245 main_controller->update();
247 // end of pause mode?
248 if(!Menu::current() && game_pause) {
252 if (end_sequence != NO_ENDSEQUENCE) {
253 if(end_sequence_controller == 0) {
254 end_sequence_controller = new CodeController();
255 tux.set_controller(end_sequence_controller);
258 end_sequence_controller->press(Controller::RIGHT);
260 if (int(last_x_pos) == int(tux.get_pos().x))
261 end_sequence_controller->press(Controller::JUMP);
262 last_x_pos = tux.get_pos().x;
265 main_controller->update();
267 while (SDL_PollEvent(&event)) {
268 /* Check for menu-events, if the menu is shown */
270 Menu::current()->event(event);
271 main_controller->process_event(event);
272 if(event.type == SDL_QUIT)
273 throw std::runtime_error("Received window close");
277 if(playback_demo_stream != 0) {
278 demo_controller->update();
285 playback_demo_stream->get(left);
286 playback_demo_stream->get(right);
287 playback_demo_stream->get(up);
288 playback_demo_stream->get(down);
289 playback_demo_stream->get(jump);
290 playback_demo_stream->get(action);
291 demo_controller->press(Controller::LEFT, left);
292 demo_controller->press(Controller::RIGHT, right);
293 demo_controller->press(Controller::UP, up);
294 demo_controller->press(Controller::DOWN, down);
295 demo_controller->press(Controller::JUMP, jump);
296 demo_controller->press(Controller::ACTION, action);
299 // save input for demo?
300 if(capture_demo_stream != 0) {
301 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
302 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
303 capture_demo_stream ->put(main_controller->hold(Controller::UP));
304 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
305 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
306 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
311 GameSession::try_cheats()
313 if(currentsector == 0)
315 Player& tux = *currentsector->player;
317 // Cheating words (the goal of this is really for debugging,
318 // but could be used for some cheating, nothing wrong with that)
319 if(main_controller->check_cheatcode("grow")) {
320 tux.set_bonus(GROWUP_BONUS, false);
322 if(main_controller->check_cheatcode("fire")) {
323 tux.set_bonus(FIRE_BONUS, false);
325 if(main_controller->check_cheatcode("ice")) {
326 tux.set_bonus(ICE_BONUS, false);
328 if(main_controller->check_cheatcode("lifeup")) {
329 player_status->lives++;
331 if(main_controller->check_cheatcode("lifedown")) {
332 player_status->lives--;
334 if(main_controller->check_cheatcode("grease")) {
335 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
337 if(main_controller->check_cheatcode("invincible")) {
338 // be invincle for the rest of the level
339 tux.invincible_timer.start(10000);
341 if(main_controller->check_cheatcode("shrink")) {
343 tux.kill(tux.SHRINK);
345 if(main_controller->check_cheatcode("kill")) {
346 // kill Tux, but without losing a life
347 player_status->lives++;
351 if(main_controller->check_cheatcode("grid")) {
353 debug_grid = !debug_grid;
356 if(main_controller->check_cheatcode("gotoend")) {
357 // goes to the end of the level
359 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
360 currentsector->camera->reset(
361 Vector(tux.get_pos().x, tux.get_pos().y));
363 if(main_controller->check_cheatcode("finish")) {
364 // finish current sector
365 exit_status = ES_LEVEL_FINISHED;
366 // don't add points to stats though...
371 GameSession::check_end_conditions()
373 Player* tux = currentsector->player;
376 if(end_sequence && endsequence_timer.check()) {
377 exit_status = ES_LEVEL_FINISHED;
379 } else if (!end_sequence && tux->is_dead()) {
380 if (player_status->lives < 0) { // No more lives!?
381 exit_status = ES_GAME_OVER;
382 } else { // Still has lives, so reset Tux to the levelstart
391 GameSession::update(float elapsed_time)
394 if(main_controller->pressed(Controller::PAUSE_MENU))
398 if(!currentsector->player->growing_timer.started()) {
399 // Update Tux and the World
400 currentsector->update(elapsed_time);
403 // respawning in new sector?
404 if(newsector != "" && newspawnpoint != "") {
405 Sector* sector = level->get_sector(newsector);
407 std::cerr << "Sector '" << newsector << "' not found.\n";
409 sector->activate(newspawnpoint);
410 sector->play_music(LEVEL_MUSIC);
411 currentsector = sector;
417 sound_manager->set_listener_position(currentsector->player->get_pos());
423 currentsector->draw(*context);
424 drawstatus(*context);
429 if(Menu::current()) {
430 Menu::current()->draw(*context);
433 context->do_drawing();
437 GameSession::draw_pause()
439 int x = SCREEN_HEIGHT / 20;
440 for(int i = 0; i < x; ++i) {
441 context->draw_filled_rect(
442 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
443 -((pause_menu_frame * i)%SCREEN_WIDTH)
444 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
445 Vector(SCREEN_WIDTH,10),
446 Color(0.1, 0.1, 0.1, static_cast<float>(rand() % 20 + 1) / 255.0),
447 LAYER_FOREGROUND1+1);
450 context->draw_filled_rect(
451 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
453 static_cast<float>(rand() % 50) / 255.0,
454 static_cast<float>(rand() % 50) / 255.0,
455 static_cast<float>(rand() % 50) / 255.0,
456 0.5), LAYER_FOREGROUND1);
458 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
459 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
461 const char* str1 = _("Playing: ");
462 const char* str2 = level->get_name().c_str();
464 context->draw_text(blue_text, str1,
465 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
466 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
467 context->draw_text(white_text, str2,
468 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
469 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
474 GameSession::process_menu()
476 Menu* menu = Menu::current();
480 if(menu == game_menu) {
481 switch (game_menu->check()) {
483 Menu::set_current(0);
485 case MNID_ABORTLEVEL:
486 Menu::set_current(0);
487 exit_status = ES_LEVEL_ABORT;
490 } else if(menu == options_menu) {
491 process_options_menu();
492 } else if(menu == load_game_menu ) {
493 process_load_game_menu();
499 GameSession::ExitStatus
502 Menu::set_current(0);
507 // Eat unneeded events
509 while(SDL_PollEvent(&event))
514 Uint32 fps_ticks = SDL_GetTicks();
515 Uint32 fps_nextframe_ticks = SDL_GetTicks();
517 bool skipdraw = false;
519 while (exit_status == ES_NONE) {
520 // we run in a logical framerate so elapsed time is a constant
521 static const float elapsed_time = 1.0 / LOGICAL_FPS;
522 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
524 game_time += elapsed_time;
527 ticks = SDL_GetTicks();
528 if(ticks > fps_nextframe_ticks) {
529 if(skipdraw == true) {
530 // already skipped last frame? we have to slow down the game then...
532 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
534 // don't draw all frames when we're getting too slow
539 while(fps_nextframe_ticks > ticks) {
541 // If we really have to wait long, then do an imprecise SDL_Delay()
542 Uint32 diff = fps_nextframe_ticks - ticks;
544 SDL_Delay(diff - 10);
546 ticks = SDL_GetTicks();
549 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
552 float diff = SDL_GetTicks() - fps_nextframe_ticks;
554 // sets the ticks that must have elapsed
555 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
557 // sets the ticks that must have elapsed
558 // in order for the next frame to start.
559 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
566 // Update the world state and all objects in the world
567 // Do that with a constante time-delta so that the game will run
568 // determistic and not different on different machines
569 if(!game_pause && !Menu::current())
572 check_end_conditions();
573 if (end_sequence == ENDSEQUENCE_RUNNING)
574 update(elapsed_time/2);
575 else if(end_sequence == NO_ENDSEQUENCE)
576 update(elapsed_time);
587 sound_manager->update();
589 /* Time stops in pause mode */
590 if(game_pause || Menu::current())
595 //frame_rate.update();
598 if (currentsector->player->invincible_timer.started() && !end_sequence)
600 currentsector->play_music(HERRING_MUSIC);
602 /* or just normal music? */
603 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
605 currentsector->play_music(LEVEL_MUSIC);
608 /* Calculate frames per second */
613 if(SDL_GetTicks() - fps_ticks >= 500)
615 fps_fps = (float) fps_cnt / .5;
617 fps_ticks = SDL_GetTicks();
624 main_controller->reset();
629 GameSession::finish(bool win)
632 exit_status = ES_LEVEL_FINISHED;
634 exit_status = ES_LEVEL_ABORT;
638 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
641 newspawnpoint = spawnpoint;
645 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
647 reset_sector = sector;
652 GameSession::get_working_directory()
654 return FileSystem::dirname(levelfile);
658 GameSession::display_info_box(const std::string& text)
660 InfoBox* box = new InfoBox(text);
665 main_controller->update();
667 while (SDL_PollEvent(&event)) {
668 main_controller->process_event(event);
669 if(event.type == SDL_QUIT)
670 throw std::runtime_error("Received window close event");
673 if(main_controller->pressed(Controller::JUMP)
674 || main_controller->pressed(Controller::ACTION)
675 || main_controller->pressed(Controller::PAUSE_MENU)
676 || main_controller->pressed(Controller::MENU_SELECT))
680 sound_manager->update();
687 GameSession::start_sequence(const std::string& sequencename)
689 if(sequencename == "endsequence" || sequencename == "fireworks") {
693 end_sequence = ENDSEQUENCE_RUNNING;
694 endsequence_timer.start(7.0); // 7 seconds until we finish the map
696 sound_manager->play_music("music/leveldone.ogg", false);
697 currentsector->player->invincible_timer.start(7.0);
699 if(sequencename == "fireworks") {
700 currentsector->add_object(new Fireworks());
702 } else if(sequencename == "stoptux") {
703 end_sequence = ENDSEQUENCE_WAITING;
705 std::cout << "Unknown sequence '" << sequencename << "'.\n";
711 GameSession::drawstatus(DrawingContext& context)
713 player_status->draw(context);
715 if(config->show_fps) {
717 snprintf(str, sizeof(str), "%2.1f", fps_fps);
718 context.draw_text(white_text, "FPS",
719 Vector(SCREEN_WIDTH -
720 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
721 LEFT_ALLIGN, LAYER_FOREGROUND1);
722 context.draw_text(gold_text, str,
723 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
724 LEFT_ALLIGN, LAYER_FOREGROUND1);
729 GameSession::drawresultscreen()
733 DrawingContext context;
734 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
735 i != currentsector->gameobjects.end(); ++i) {
736 Background* background = dynamic_cast<Background*> (*i);
738 background->draw(context);
742 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
743 CENTER_ALLIGN, LAYER_FOREGROUND1);
745 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
746 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
748 sprintf(str, _("COINS: %d"), player_status->coins);
749 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
751 context.do_drawing();
753 wait_for_event(2.0, 5.0);
756 std::string slotinfo(int slot)
759 std::string slotfile;
761 std::stringstream stream;
763 slotfile = "save/slot" + stream.str() + ".stsg";
767 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
769 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
771 throw std::runtime_error("file is not a supertux-savegame.");
773 savegame->get("title", title);
774 } catch(std::exception& e) {
775 return std::string(_("Slot")) + " " + stream.str() + " - " +
776 std::string(_("Free"));
779 return std::string("Slot ") + stream.str() + " - " + title;
782 bool process_load_game_menu()
784 int slot = load_game_menu->check();
789 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
792 std::stringstream stream;
794 std::string slotfile = "save/slot" + stream.str() + ".stsg";
796 sound_manager->stop_music();
798 DrawingContext context;
799 context.draw_text(white_text, "Loading...",
800 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
801 CENTER_ALLIGN, LAYER_FOREGROUND1);
802 context.do_drawing();
804 WorldMapNS::WorldMap worldmap;
806 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
807 // Load the game or at least set the savegame_file variable
808 worldmap.loadgame(slotfile);
812 Menu::set_current(main_menu);