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)
84 music_playing = false;
87 context = new DrawingContext();
93 GameSession::restart_level()
96 exit_status = ES_NONE;
97 end_sequence = NO_ENDSEQUENCE;
99 main_controller->reset();
105 level->load(levelfile);
107 global_stats.reset();
108 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
109 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
110 //global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
112 if(reset_sector != "") {
113 currentsector = level->get_sector(reset_sector);
115 std::stringstream msg;
116 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
117 throw std::runtime_error(msg.str());
119 currentsector->activate(reset_pos);
121 currentsector = level->get_sector("main");
123 throw std::runtime_error("Couldn't find main sector");
124 currentsector->activate("main");
127 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
132 currentsector->play_music(LEVEL_MUSIC);
133 music_playing = true;
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();
220 wait_for_event(1.0, 3.0);
224 GameSession::on_escape_press()
226 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
227 return; // don't let the player open the menu, when he is dying
229 if(mode == ST_GL_TEST) {
230 exit_status = ES_LEVEL_ABORT;
231 } else if (!Menu::current()) {
232 Menu::set_current(game_menu);
233 game_menu->set_active_item(MNID_CONTINUE);
241 GameSession::process_events()
243 Player& tux = *currentsector->player;
244 main_controller->update();
246 // end of pause mode?
247 if(!Menu::current() && game_pause) {
251 if (end_sequence != NO_ENDSEQUENCE) {
252 if(end_sequence_controller == 0) {
253 end_sequence_controller = new CodeController();
254 tux.set_controller(end_sequence_controller);
257 end_sequence_controller->press(Controller::RIGHT);
259 if (int(last_x_pos) == int(tux.get_pos().x))
260 end_sequence_controller->press(Controller::JUMP);
261 last_x_pos = tux.get_pos().x;
264 main_controller->update();
266 while (SDL_PollEvent(&event)) {
267 /* Check for menu-events, if the menu is shown */
269 Menu::current()->event(event);
270 main_controller->process_event(event);
271 if(event.type == SDL_QUIT)
272 throw std::runtime_error("Received window close");
276 if(playback_demo_stream != 0) {
277 demo_controller->update();
284 playback_demo_stream->get(left);
285 playback_demo_stream->get(right);
286 playback_demo_stream->get(up);
287 playback_demo_stream->get(down);
288 playback_demo_stream->get(jump);
289 playback_demo_stream->get(action);
290 demo_controller->press(Controller::LEFT, left);
291 demo_controller->press(Controller::RIGHT, right);
292 demo_controller->press(Controller::UP, up);
293 demo_controller->press(Controller::DOWN, down);
294 demo_controller->press(Controller::JUMP, jump);
295 demo_controller->press(Controller::ACTION, action);
298 // save input for demo?
299 if(capture_demo_stream != 0) {
300 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
301 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
302 capture_demo_stream ->put(main_controller->hold(Controller::UP));
303 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
304 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
305 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
310 GameSession::try_cheats()
312 if(currentsector == 0)
314 Player& tux = *currentsector->player;
316 // Cheating words (the goal of this is really for debugging,
317 // but could be used for some cheating, nothing wrong with that)
318 if(main_controller->check_cheatcode("grow")) {
319 tux.set_bonus(GROWUP_BONUS, false);
321 if(main_controller->check_cheatcode("fire")) {
322 tux.set_bonus(FIRE_BONUS, false);
324 if(main_controller->check_cheatcode("ice")) {
325 tux.set_bonus(ICE_BONUS, false);
327 if(main_controller->check_cheatcode("lifeup")) {
328 player_status.lives++;
330 if(main_controller->check_cheatcode("lifedown")) {
331 player_status.lives--;
333 if(main_controller->check_cheatcode("grease")) {
334 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
336 if(main_controller->check_cheatcode("invincible")) {
337 // be invincle for the rest of the level
338 tux.invincible_timer.start(10000);
340 if(main_controller->check_cheatcode("shrink")) {
342 tux.kill(tux.SHRINK);
344 if(main_controller->check_cheatcode("kill")) {
345 // kill Tux, but without losing a life
346 player_status.lives++;
350 if(main_controller->check_cheatcode("grid")) {
352 debug_grid = !debug_grid;
355 if(main_controller->check_cheatcode("hover")) {
356 // toggle hover ability on/off
357 tux.enable_hover = !tux.enable_hover;
359 if(main_controller->check_cheatcode("gotoend")) {
360 // goes to the end of the level
362 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
363 currentsector->camera->reset(
364 Vector(tux.get_pos().x, tux.get_pos().y));
366 if(main_controller->check_cheatcode("finish")) {
367 // finish current sector
368 exit_status = ES_LEVEL_FINISHED;
369 // don't add points to stats though...
371 // temporary to help player's choosing a flapping
372 if(main_controller->check_cheatcode("marek")) {
373 tux.flapping_mode = Player::MAREK_FLAP;
375 if(main_controller->check_cheatcode("ricardo")) {
376 tux.flapping_mode = Player::RICARDO_FLAP;
378 if(main_controller->check_cheatcode("ryan")) {
379 tux.flapping_mode = Player::RYAN_FLAP;
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());
431 sound_manager->update();
437 currentsector->draw(*context);
438 drawstatus(*context);
443 if(Menu::current()) {
444 Menu::current()->draw(*context);
447 context->do_drawing();
451 GameSession::draw_pause()
453 int x = SCREEN_HEIGHT / 20;
454 for(int i = 0; i < x; ++i) {
455 context->draw_filled_rect(
456 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
457 -((pause_menu_frame * i)%SCREEN_WIDTH)
458 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
459 Vector(SCREEN_WIDTH,10),
460 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
463 context->draw_filled_rect(
464 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
465 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
467 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
468 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
470 const char* str1 = _("Playing: ");
471 const char* str2 = level->get_name().c_str();
473 context->draw_text(blue_text, str1,
474 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
475 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
476 context->draw_text(white_text, str2,
477 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
478 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
483 GameSession::process_menu()
485 Menu* menu = Menu::current();
489 if(menu == game_menu) {
490 switch (game_menu->check()) {
492 Menu::set_current(0);
494 case MNID_ABORTLEVEL:
495 Menu::set_current(0);
496 exit_status = ES_LEVEL_ABORT;
499 } else if(menu == options_menu) {
500 process_options_menu();
501 } else if(menu == load_game_menu ) {
502 process_load_game_menu();
508 GameSession::ExitStatus
511 Menu::set_current(0);
516 // Eat unneeded events
518 while(SDL_PollEvent(&event))
523 Uint32 fps_ticks = SDL_GetTicks();
524 Uint32 fps_nextframe_ticks = SDL_GetTicks();
526 bool skipdraw = false;
528 while (exit_status == ES_NONE) {
529 // we run in a logical framerate so elapsed time is a constant
530 static const float elapsed_time = 1.0 / LOGICAL_FPS;
531 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
533 global_time += elapsed_time;
536 ticks = SDL_GetTicks();
537 if(ticks > fps_nextframe_ticks) {
538 if(skipdraw == true) {
539 // already skipped last frame? we have to slow down the game then...
541 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
543 // don't draw all frames when we're getting too slow
548 while(fps_nextframe_ticks > ticks) {
550 // If we really have to wait long, then do an imprecise SDL_Delay()
551 Uint32 diff = fps_nextframe_ticks - ticks;
553 SDL_Delay(diff - 10);
555 ticks = SDL_GetTicks();
558 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
561 float diff = SDL_GetTicks() - fps_nextframe_ticks;
563 // sets the ticks that must have elapsed
564 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
566 // sets the ticks that must have elapsed
567 // in order for the next frame to start.
568 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
575 // Update the world state and all objects in the world
576 // Do that with a constante time-delta so that the game will run
577 // determistic and not different on different machines
578 if(!game_pause && !Menu::current())
581 check_end_conditions();
582 if (end_sequence == ENDSEQUENCE_RUNNING)
583 update(elapsed_time/2);
584 else if(end_sequence == NO_ENDSEQUENCE)
585 update(elapsed_time);
595 /* Time stops in pause mode */
596 if(game_pause || Menu::current())
601 //frame_rate.update();
604 if (currentsector->player->invincible_timer.started() && !end_sequence)
606 currentsector->play_music(HERRING_MUSIC);
608 /* or just normal music? */
609 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
611 currentsector->play_music(LEVEL_MUSIC);
614 /* Calculate frames per second */
619 if(SDL_GetTicks() - fps_ticks >= 500)
621 fps_fps = (float) fps_cnt / .5;
623 fps_ticks = SDL_GetTicks();
630 main_controller->reset();
635 GameSession::finish(bool win)
638 exit_status = ES_LEVEL_FINISHED;
640 exit_status = ES_LEVEL_ABORT;
644 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
647 newspawnpoint = spawnpoint;
651 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
653 reset_sector = sector;
658 GameSession::get_working_directory()
660 return FileSystem::dirname(levelfile);
664 GameSession::display_info_box(const std::string& text)
666 InfoBox* box = new InfoBox(text);
671 main_controller->update();
673 while (SDL_PollEvent(&event)) {
674 main_controller->process_event(event);
675 if(event.type == SDL_QUIT)
676 throw std::runtime_error("Received window close event");
679 if(main_controller->pressed(Controller::JUMP)
680 || main_controller->pressed(Controller::ACTION)
681 || main_controller->pressed(Controller::PAUSE_MENU)
682 || main_controller->pressed(Controller::MENU_SELECT))
692 GameSession::start_sequence(const std::string& sequencename)
694 if(sequencename == "endsequence" || sequencename == "fireworks") {
698 end_sequence = ENDSEQUENCE_RUNNING;
699 endsequence_timer.start(7.0); // 7 seconds until we finish the map
701 sound_manager->play_music("music/leveldone.ogg");
702 currentsector->player->invincible_timer.start(7.0);
704 if(sequencename == "fireworks") {
705 currentsector->add_object(new Fireworks());
707 } else if(sequencename == "stoptux") {
708 end_sequence = ENDSEQUENCE_WAITING;
710 std::cout << "Unknown sequence '" << sequencename << "'.\n";
716 GameSession::drawstatus(DrawingContext& context)
718 player_status.draw(context);
720 if(config->show_fps) {
722 snprintf(str, sizeof(str), "%2.1f", fps_fps);
723 context.draw_text(white_text, "FPS",
724 Vector(SCREEN_WIDTH -
725 white_text->get_text_width("FPS "), 40),
726 LEFT_ALLIGN, LAYER_FOREGROUND1);
727 context.draw_text(gold_text, str,
728 Vector(SCREEN_WIDTH-4*16, 40),
729 LEFT_ALLIGN, LAYER_FOREGROUND1);
734 GameSession::drawresultscreen()
738 DrawingContext context;
739 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
740 i != currentsector->gameobjects.end(); ++i) {
741 Background* background = dynamic_cast<Background*> (*i);
743 background->draw(context);
747 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
748 CENTER_ALLIGN, LAYER_FOREGROUND1);
750 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
751 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
753 sprintf(str, _("COINS: %d"), player_status.coins);
754 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
756 context.do_drawing();
758 wait_for_event(2.0, 5.0);
761 std::string slotinfo(int slot)
764 std::string slotfile;
766 std::stringstream stream;
768 slotfile = "save/slot" + stream.str() + ".stsg";
772 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
774 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
776 throw std::runtime_error("file is not a supertux-savegame.");
778 savegame->get("title", title);
779 } catch(std::exception& e) {
780 return std::string(_("Slot")) + " " + stream.str() + " - " +
781 std::string(_("Free"));
784 return std::string("Slot ") + stream.str() + " - " + title;
787 bool process_load_game_menu()
789 int slot = load_game_menu->check();
794 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
797 std::stringstream stream;
799 std::string slotfile = "save/slot" + stream.str() + ".stsg";
802 DrawingContext context;
803 context.draw_text(white_text, "Loading...",
804 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
805 CENTER_ALLIGN, LAYER_FOREGROUND1);
806 context.do_drawing();
808 WorldMapNS::WorldMap worldmap;
810 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
811 // Load the game or at least set the savegame_file variable
812 worldmap.loadgame(slotfile);
816 Menu::set_current(main_menu);