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"
68 // the engine will be run with a logical framerate of 64fps.
69 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
71 static const float LOGICAL_FPS = 64.0;
73 GameSession* GameSession::current_ = 0;
75 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
76 Statistics* statistics)
77 : level(0), currentsector(0), mode(mode),
78 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
79 levelfile(levelfile_), best_level_statistics(statistics),
80 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
86 music_playing = false;
89 context = new DrawingContext();
95 GameSession::restart_level()
98 exit_status = ES_NONE;
99 end_sequence = NO_ENDSEQUENCE;
101 main_controller->reset();
107 level->load(levelfile);
109 global_stats.reset();
110 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
111 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
112 //global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
114 if(reset_sector != "") {
115 currentsector = level->get_sector(reset_sector);
117 std::stringstream msg;
118 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
119 throw std::runtime_error(msg.str());
121 currentsector->activate(reset_pos);
123 currentsector = level->get_sector("main");
125 throw std::runtime_error("Couldn't find main sector");
126 currentsector->activate("main");
129 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
134 currentsector->play_music(LEVEL_MUSIC);
135 music_playing = true;
138 if(capture_file != "")
139 record_demo(capture_file);
142 GameSession::~GameSession()
144 delete capture_demo_stream;
145 delete playback_demo_stream;
146 delete demo_controller;
148 delete end_sequence_controller;
156 GameSession::record_demo(const std::string& filename)
158 delete capture_demo_stream;
160 capture_demo_stream = new std::ofstream(filename.c_str());
161 if(!capture_demo_stream->good()) {
162 std::stringstream msg;
163 msg << "Couldn't open demo file '" << filename << "' for writing.";
164 throw std::runtime_error(msg.str());
166 capture_file = filename;
170 GameSession::play_demo(const std::string& filename)
172 delete playback_demo_stream;
173 delete demo_controller;
175 playback_demo_stream = new std::ifstream(filename.c_str());
176 if(!playback_demo_stream->good()) {
177 std::stringstream msg;
178 msg << "Couldn't open demo file '" << filename << "' for reading.";
179 throw std::runtime_error(msg.str());
182 Player& tux = *currentsector->player;
183 demo_controller = new CodeController();
184 tux.set_controller(demo_controller);
188 GameSession::levelintro()
192 DrawingContext context;
193 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
194 i != currentsector->gameobjects.end(); ++i) {
195 Background* background = dynamic_cast<Background*> (*i);
197 background->draw(context);
201 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
202 // CENTER_ALLIGN, LAYER_FOREGROUND1);
203 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
206 sprintf(str, "TUX x %d", player_status->lives);
207 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
208 CENTER_ALLIGN, LAYER_FOREGROUND1);
210 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
211 //TODO make author check case/blank-insensitive
212 context.draw_text(white_small_text,
213 std::string(_("contributed by ")) + level->get_author(),
214 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
217 if(best_level_statistics != NULL)
218 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
220 context.do_drawing();
222 wait_for_event(1.0, 3.0);
226 GameSession::on_escape_press()
228 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
229 return; // don't let the player open the menu, when he is dying
231 if(mode == ST_GL_TEST) {
232 exit_status = ES_LEVEL_ABORT;
233 } else if (!Menu::current()) {
234 Menu::set_current(game_menu);
235 game_menu->set_active_item(MNID_CONTINUE);
243 GameSession::process_events()
245 Player& tux = *currentsector->player;
246 main_controller->update();
248 // end of pause mode?
249 if(!Menu::current() && game_pause) {
253 if (end_sequence != NO_ENDSEQUENCE) {
254 if(end_sequence_controller == 0) {
255 end_sequence_controller = new CodeController();
256 tux.set_controller(end_sequence_controller);
259 end_sequence_controller->press(Controller::RIGHT);
261 if (int(last_x_pos) == int(tux.get_pos().x))
262 end_sequence_controller->press(Controller::JUMP);
263 last_x_pos = tux.get_pos().x;
266 main_controller->update();
268 while (SDL_PollEvent(&event)) {
269 /* Check for menu-events, if the menu is shown */
271 Menu::current()->event(event);
272 main_controller->process_event(event);
273 if(event.type == SDL_QUIT)
274 throw graceful_shutdown();
278 if(playback_demo_stream != 0) {
279 demo_controller->update();
286 playback_demo_stream->get(left);
287 playback_demo_stream->get(right);
288 playback_demo_stream->get(up);
289 playback_demo_stream->get(down);
290 playback_demo_stream->get(jump);
291 playback_demo_stream->get(action);
292 demo_controller->press(Controller::LEFT, left);
293 demo_controller->press(Controller::RIGHT, right);
294 demo_controller->press(Controller::UP, up);
295 demo_controller->press(Controller::DOWN, down);
296 demo_controller->press(Controller::JUMP, jump);
297 demo_controller->press(Controller::ACTION, action);
300 // save input for demo?
301 if(capture_demo_stream != 0) {
302 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
303 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
304 capture_demo_stream ->put(main_controller->hold(Controller::UP));
305 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
306 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
307 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
312 GameSession::try_cheats()
314 if(currentsector == 0)
316 Player& tux = *currentsector->player;
318 // Cheating words (the goal of this is really for debugging,
319 // but could be used for some cheating, nothing wrong with that)
320 if(main_controller->check_cheatcode("grow")) {
321 tux.set_bonus(GROWUP_BONUS, false);
323 if(main_controller->check_cheatcode("fire")) {
324 tux.set_bonus(FIRE_BONUS, false);
326 if(main_controller->check_cheatcode("ice")) {
327 tux.set_bonus(ICE_BONUS, false);
329 if(main_controller->check_cheatcode("lifeup")) {
330 player_status->lives++;
332 if(main_controller->check_cheatcode("lifedown")) {
333 player_status->lives--;
335 if(main_controller->check_cheatcode("grease")) {
336 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
338 if(main_controller->check_cheatcode("invincible")) {
339 // be invincle for the rest of the level
340 tux.invincible_timer.start(10000);
342 if(main_controller->check_cheatcode("mortal")) {
343 // give up invincibility
344 tux.invincible_timer.stop();
346 if(main_controller->check_cheatcode("shrink")) {
348 tux.kill(tux.SHRINK);
350 if(main_controller->check_cheatcode("kill")) {
351 // kill Tux, but without losing a life
352 player_status->lives++;
355 if(main_controller->check_cheatcode("whereami")) {
356 std::cout << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << "." << std::endl;
359 if(main_controller->check_cheatcode("grid")) {
361 debug_grid = !debug_grid;
364 if(main_controller->check_cheatcode("gotoend")) {
365 // goes to the end of the level
367 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
368 currentsector->camera->reset(
369 Vector(tux.get_pos().x, tux.get_pos().y));
371 if(main_controller->check_cheatcode("finish")) {
372 // finish current sector
373 exit_status = ES_LEVEL_FINISHED;
374 // don't add points to stats though...
379 GameSession::check_end_conditions()
381 Player* tux = currentsector->player;
384 if(end_sequence && endsequence_timer.check()) {
385 exit_status = ES_LEVEL_FINISHED;
387 } else if (!end_sequence && tux->is_dead()) {
388 if (player_status->lives < 0) { // No more lives!?
389 exit_status = ES_GAME_OVER;
390 } else { // Still has lives, so reset Tux to the levelstart
399 GameSession::update(float elapsed_time)
402 if(main_controller->pressed(Controller::PAUSE_MENU))
406 if(!currentsector->player->growing_timer.started()) {
407 // Update Tux and the World
408 currentsector->update(elapsed_time);
411 // respawning in new sector?
412 if(newsector != "" && newspawnpoint != "") {
413 Sector* sector = level->get_sector(newsector);
415 std::cerr << "Sector '" << newsector << "' not found.\n";
417 sector->activate(newspawnpoint);
418 sector->play_music(LEVEL_MUSIC);
419 currentsector = sector;
425 sound_manager->set_listener_position(currentsector->player->get_pos());
431 currentsector->draw(*context);
432 drawstatus(*context);
437 if(Menu::current()) {
438 Menu::current()->draw(*context);
441 context->do_drawing();
445 GameSession::draw_pause()
447 int x = SCREEN_HEIGHT / 20;
448 for(int i = 0; i < x; ++i) {
449 context->draw_filled_rect(
450 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
451 -((pause_menu_frame * i)%SCREEN_WIDTH)
452 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
453 Vector(SCREEN_WIDTH,10),
454 Color(0.1, 0.1, 0.1, static_cast<float>(rand() % 20 + 1) / 255.0),
455 LAYER_FOREGROUND1+1);
458 context->draw_filled_rect(
459 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
461 static_cast<float>(rand() % 50) / 255.0,
462 static_cast<float>(rand() % 50) / 255.0,
463 static_cast<float>(rand() % 50) / 255.0,
464 0.5), LAYER_FOREGROUND1);
466 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
467 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
469 const char* str1 = _("Playing: ");
470 const char* str2 = level->get_name().c_str();
472 context->draw_text(blue_text, str1,
473 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
474 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
475 context->draw_text(white_text, str2,
476 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
477 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
482 GameSession::process_menu()
484 Menu* menu = Menu::current();
488 if(menu == game_menu) {
489 switch (game_menu->check()) {
491 Menu::set_current(0);
493 case MNID_ABORTLEVEL:
494 Menu::set_current(0);
495 exit_status = ES_LEVEL_ABORT;
498 } else if(menu == options_menu) {
499 process_options_menu();
500 } else if(menu == load_game_menu ) {
501 process_load_game_menu();
507 GameSession::ExitStatus
510 Menu::set_current(0);
515 // Eat unneeded events
517 while(SDL_PollEvent(&event))
522 Uint32 fps_ticks = SDL_GetTicks();
523 Uint32 fps_nextframe_ticks = SDL_GetTicks();
525 bool skipdraw = false;
527 while (exit_status == ES_NONE) {
528 // we run in a logical framerate so elapsed time is a constant
529 static const float elapsed_time = 1.0 / LOGICAL_FPS;
530 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
532 game_time += elapsed_time;
535 ticks = SDL_GetTicks();
536 if(ticks > fps_nextframe_ticks) {
537 if(skipdraw == true) {
538 // already skipped last frame? we have to slow down the game then...
540 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
542 // don't draw all frames when we're getting too slow
547 while(fps_nextframe_ticks > ticks) {
549 // If we really have to wait long, then do an imprecise SDL_Delay()
550 Uint32 diff = fps_nextframe_ticks - ticks;
552 SDL_Delay(diff - 10);
554 ticks = SDL_GetTicks();
557 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
560 float diff = SDL_GetTicks() - fps_nextframe_ticks;
562 // sets the ticks that must have elapsed
563 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
565 // sets the ticks that must have elapsed
566 // in order for the next frame to start.
567 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
574 // Update the world state and all objects in the world
575 // Do that with a constante time-delta so that the game will run
576 // determistic and not different on different machines
577 if(!game_pause && !Menu::current())
580 check_end_conditions();
581 if (end_sequence == ENDSEQUENCE_RUNNING)
582 update(elapsed_time/2);
583 else if(end_sequence == NO_ENDSEQUENCE)
584 update(elapsed_time);
595 sound_manager->update();
597 /* Time stops in pause mode */
598 if(game_pause || Menu::current())
603 //frame_rate.update();
606 if (currentsector->player->invincible_timer.started() && !end_sequence)
608 currentsector->play_music(HERRING_MUSIC);
610 /* or just normal music? */
611 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
613 currentsector->play_music(LEVEL_MUSIC);
616 /* Calculate frames per second */
621 if(SDL_GetTicks() - fps_ticks >= 500)
623 fps_fps = (float) fps_cnt / .5;
625 fps_ticks = SDL_GetTicks();
632 main_controller->reset();
637 GameSession::finish(bool win)
640 exit_status = ES_LEVEL_FINISHED;
642 exit_status = ES_LEVEL_ABORT;
646 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
649 newspawnpoint = spawnpoint;
653 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
655 reset_sector = sector;
660 GameSession::get_working_directory()
662 return FileSystem::dirname(levelfile);
666 GameSession::display_info_box(const std::string& text)
668 InfoBox* box = new InfoBox(text);
673 main_controller->update();
675 while (SDL_PollEvent(&event)) {
676 main_controller->process_event(event);
677 if(event.type == SDL_QUIT)
678 throw graceful_shutdown();
681 if(main_controller->pressed(Controller::JUMP)
682 || main_controller->pressed(Controller::ACTION)
683 || main_controller->pressed(Controller::PAUSE_MENU)
684 || main_controller->pressed(Controller::MENU_SELECT))
686 else if(main_controller->pressed(Controller::DOWN))
688 else if(main_controller->pressed(Controller::UP))
692 sound_manager->update();
699 GameSession::start_sequence(const std::string& sequencename)
701 if(sequencename == "endsequence" || sequencename == "fireworks") {
705 end_sequence = ENDSEQUENCE_RUNNING;
706 endsequence_timer.start(7.0); // 7 seconds until we finish the map
708 sound_manager->play_music("music/leveldone.ogg", false);
709 currentsector->player->invincible_timer.start(7.0);
711 if(sequencename == "fireworks") {
712 currentsector->add_object(new Fireworks());
714 } else if(sequencename == "stoptux") {
715 end_sequence = ENDSEQUENCE_WAITING;
717 std::cout << "Unknown sequence '" << sequencename << "'.\n";
723 GameSession::drawstatus(DrawingContext& context)
725 player_status->draw(context);
727 if(config->show_fps) {
729 snprintf(str, sizeof(str), "%2.1f", fps_fps);
730 context.draw_text(white_text, "FPS",
731 Vector(SCREEN_WIDTH -
732 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
733 LEFT_ALLIGN, LAYER_FOREGROUND1);
734 context.draw_text(gold_text, str,
735 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
736 LEFT_ALLIGN, LAYER_FOREGROUND1);
741 GameSession::drawresultscreen()
745 DrawingContext context;
746 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
747 i != currentsector->gameobjects.end(); ++i) {
748 Background* background = dynamic_cast<Background*> (*i);
750 background->draw(context);
754 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
755 CENTER_ALLIGN, LAYER_FOREGROUND1);
757 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
758 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
760 sprintf(str, _("COINS: %d"), player_status->coins);
761 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
763 context.do_drawing();
765 wait_for_event(2.0, 5.0);
768 std::string slotinfo(int slot)
771 std::string slotfile;
773 std::stringstream stream;
775 slotfile = "save/slot" + stream.str() + ".stsg";
779 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
781 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
783 throw std::runtime_error("file is not a supertux-savegame.");
785 savegame->get("title", title);
786 } catch(std::exception& e) {
787 return std::string(_("Slot")) + " " + stream.str() + " - " +
788 std::string(_("Free"));
791 return std::string("Slot ") + stream.str() + " - " + title;
794 bool process_load_game_menu()
796 int slot = load_game_menu->check();
801 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
804 std::stringstream stream;
806 std::string slotfile = "save/slot" + stream.str() + ".stsg";
808 sound_manager->stop_music();
810 DrawingContext context;
811 context.draw_text(white_text, "Loading...",
812 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
813 CENTER_ALLIGN, LAYER_FOREGROUND1);
814 context.do_drawing();
816 WorldMapNS::WorldMap worldmap;
818 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
819 // Load the game or at least set the savegame_file variable
820 worldmap.loadgame(slotfile);
824 Menu::set_current(main_menu);