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.
39 #include <sys/types.h>
43 #include "game_session.h"
44 #include "video/screen.h"
49 #include "player_status.h"
50 #include "object/particlesystem.h"
51 #include "object/background.h"
52 #include "object/tilemap.h"
53 #include "object/camera.h"
54 #include "object/player.h"
55 #include "lisp/lisp.h"
56 #include "lisp/parser.h"
57 #include "resources.h"
60 #include "statistics.h"
62 #include "object/fireworks.h"
63 #include "textscroller.h"
64 #include "control/codecontroller.h"
65 #include "control/joystickkeyboardcontroller.h"
67 #include "file_system.h"
68 #include "gameconfig.h"
71 // the engine will be run with a logical framerate of 64fps.
72 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
74 static const float LOGICAL_FPS = 64.0;
76 GameSession* GameSession::current_ = 0;
78 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
79 Statistics* statistics)
80 : level(0), currentsector(0), mode(mode),
81 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
82 levelfile(levelfile_), best_level_statistics(statistics),
83 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
88 music_playing = false;
91 context = new DrawingContext();
97 GameSession::restart_level()
100 exit_status = ES_NONE;
101 end_sequence = NO_ENDSEQUENCE;
103 main_controller->reset();
109 level->load(levelfile);
111 global_stats.reset();
112 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
113 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
114 //global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
116 if(reset_sector != "") {
117 currentsector = level->get_sector(reset_sector);
119 std::stringstream msg;
120 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
121 throw std::runtime_error(msg.str());
123 currentsector->activate(reset_pos);
125 currentsector = level->get_sector("main");
127 throw std::runtime_error("Couldn't find main sector");
128 currentsector->activate("main");
131 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
136 currentsector->play_music(LEVEL_MUSIC);
137 music_playing = true;
140 if(capture_file != "")
141 record_demo(capture_file);
144 GameSession::~GameSession()
146 delete capture_demo_stream;
147 delete playback_demo_stream;
148 delete demo_controller;
150 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()
190 //sound_manager->halt_music();
194 DrawingContext context;
195 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
196 i != currentsector->gameobjects.end(); ++i) {
197 Background* background = dynamic_cast<Background*> (*i);
199 background->draw(context);
203 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
204 // CENTER_ALLIGN, LAYER_FOREGROUND1);
205 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
208 sprintf(str, "TUX x %d", player_status.lives);
209 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
210 CENTER_ALLIGN, LAYER_FOREGROUND1);
212 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
213 //TODO make author check case/blank-insensitive
214 context.draw_text(white_small_text,
215 std::string(_("contributed by ")) + level->get_author(),
216 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
219 if(best_level_statistics != NULL)
220 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
222 context.do_drawing();
224 wait_for_event(1.0, 3.0);
228 GameSession::on_escape_press()
230 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
231 return; // don't let the player open the menu, when he is dying
233 if(mode == ST_GL_TEST) {
234 exit_status = ES_LEVEL_ABORT;
235 } else if (!Menu::current()) {
236 Menu::set_current(game_menu);
237 game_menu->set_active_item(MNID_CONTINUE);
245 GameSession::process_events()
247 Player& tux = *currentsector->player;
248 main_controller->update();
250 // end of pause mode?
251 if(!Menu::current() && game_pause) {
255 if (end_sequence != NO_ENDSEQUENCE) {
256 if(end_sequence_controller == 0) {
257 end_sequence_controller = new CodeController();
258 tux.set_controller(end_sequence_controller);
261 end_sequence_controller->press(Controller::RIGHT);
263 if (int(last_x_pos) == int(tux.get_pos().x))
264 end_sequence_controller->press(Controller::JUMP);
265 last_x_pos = tux.get_pos().x;
268 main_controller->update();
270 while (SDL_PollEvent(&event)) {
271 /* Check for menu-events, if the menu is shown */
273 Menu::current()->event(event);
274 main_controller->process_event(event);
275 if(event.type == SDL_QUIT)
276 throw std::runtime_error("Received window close");
280 if(playback_demo_stream != 0) {
281 demo_controller->update();
288 playback_demo_stream->get(left);
289 playback_demo_stream->get(right);
290 playback_demo_stream->get(up);
291 playback_demo_stream->get(down);
292 playback_demo_stream->get(jump);
293 playback_demo_stream->get(action);
294 demo_controller->press(Controller::LEFT, left);
295 demo_controller->press(Controller::RIGHT, right);
296 demo_controller->press(Controller::UP, up);
297 demo_controller->press(Controller::DOWN, down);
298 demo_controller->press(Controller::JUMP, jump);
299 demo_controller->press(Controller::ACTION, action);
302 // save input for demo?
303 if(capture_demo_stream != 0) {
304 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
305 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
306 capture_demo_stream ->put(main_controller->hold(Controller::UP));
307 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
308 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
309 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
314 GameSession::try_cheats()
316 if(currentsector == 0)
318 Player& tux = *currentsector->player;
320 // Cheating words (the goal of this is really for debugging,
321 // but could be used for some cheating, nothing wrong with that)
322 if(main_controller->check_cheatcode("grow")) {
323 tux.set_bonus(GROWUP_BONUS, false);
325 if(main_controller->check_cheatcode("fire")) {
326 tux.set_bonus(FIRE_BONUS, false);
328 if(main_controller->check_cheatcode("ice")) {
329 tux.set_bonus(ICE_BONUS, false);
331 if(main_controller->check_cheatcode("lifeup")) {
332 player_status.lives++;
334 if(main_controller->check_cheatcode("lifedown")) {
335 player_status.lives--;
337 if(main_controller->check_cheatcode("grease")) {
338 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
340 if(main_controller->check_cheatcode("invincible")) {
341 // be invincle for the rest of the level
342 tux.invincible_timer.start(10000);
344 if(main_controller->check_cheatcode("shrink")) {
346 tux.kill(tux.SHRINK);
348 if(main_controller->check_cheatcode("kill")) {
349 // kill Tux, but without losing a life
350 player_status.lives++;
354 if(main_controller->check_cheatcode("grid")) {
356 debug_grid = !debug_grid;
359 if(main_controller->check_cheatcode("hover")) {
360 // toggle hover ability on/off
361 tux.enable_hover = !tux.enable_hover;
363 if(main_controller->check_cheatcode("gotoend")) {
364 // goes to the end of the level
366 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
367 currentsector->camera->reset(
368 Vector(tux.get_pos().x, tux.get_pos().y));
370 if(main_controller->check_cheatcode("finish")) {
371 // finish current sector
372 exit_status = ES_LEVEL_FINISHED;
373 // don't add points to stats though...
375 // temporary to help player's choosing a flapping
376 if(main_controller->check_cheatcode("marek")) {
377 tux.flapping_mode = Player::MAREK_FLAP;
379 if(main_controller->check_cheatcode("ricardo")) {
380 tux.flapping_mode = Player::RICARDO_FLAP;
382 if(main_controller->check_cheatcode("ryan")) {
383 tux.flapping_mode = Player::RYAN_FLAP;
388 GameSession::check_end_conditions()
390 Player* tux = currentsector->player;
393 if(end_sequence && endsequence_timer.check()) {
394 exit_status = ES_LEVEL_FINISHED;
396 } else if (!end_sequence && tux->is_dead()) {
397 if (player_status.lives < 0) { // No more lives!?
398 exit_status = ES_GAME_OVER;
399 } else { // Still has lives, so reset Tux to the levelstart
408 GameSession::update(float elapsed_time)
411 if(main_controller->pressed(Controller::PAUSE_MENU))
415 if(!currentsector->player->growing_timer.started()) {
416 // Update Tux and the World
417 currentsector->update(elapsed_time);
420 // respawning in new sector?
421 if(newsector != "" && newspawnpoint != "") {
422 Sector* sector = level->get_sector(newsector);
424 std::cerr << "Sector '" << newsector << "' not found.\n";
426 sector->activate(newspawnpoint);
427 sector->play_music(LEVEL_MUSIC);
428 currentsector = sector;
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(level_end_song, 0);
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);