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 "gameconfig.h"
70 // the engine will be run with a lofical framerate of 64fps.
71 // We choose 64fps here because it is a power of 2, so 1/64 gives an "even"
73 static const float LOGICAL_FPS = 64.0;
75 GameSession* GameSession::current_ = 0;
77 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
78 Statistics* statistics)
79 : level(0), currentsector(0), mode(mode),
80 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
81 levelfile(levelfile_), best_level_statistics(statistics),
82 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
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)
132 currentsector->play_music(LEVEL_MUSIC);
134 if(capture_file != "")
135 record_demo(capture_file);
138 GameSession::~GameSession()
140 delete capture_demo_stream;
141 delete playback_demo_stream;
142 delete demo_controller;
144 delete end_sequence_controller;
150 GameSession::record_demo(const std::string& filename)
152 delete capture_demo_stream;
154 capture_demo_stream = new std::ofstream(filename.c_str());
155 if(!capture_demo_stream->good()) {
156 std::stringstream msg;
157 msg << "Couldn't open demo file '" << filename << "' for writing.";
158 throw std::runtime_error(msg.str());
160 capture_file = filename;
164 GameSession::play_demo(const std::string& filename)
166 delete playback_demo_stream;
167 delete demo_controller;
169 playback_demo_stream = new std::ifstream(filename.c_str());
170 if(!playback_demo_stream->good()) {
171 std::stringstream msg;
172 msg << "Couldn't open demo file '" << filename << "' for reading.";
173 throw std::runtime_error(msg.str());
176 Player& tux = *currentsector->player;
177 demo_controller = new CodeController();
178 tux.set_controller(demo_controller);
182 GameSession::levelintro()
184 sound_manager->halt_music();
188 DrawingContext context;
189 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
190 i != currentsector->gameobjects.end(); ++i) {
191 Background* background = dynamic_cast<Background*> (*i);
193 background->draw(context);
197 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
198 // CENTER_ALLIGN, LAYER_FOREGROUND1);
199 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
202 sprintf(str, "TUX x %d", player_status.lives);
203 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
204 CENTER_ALLIGN, LAYER_FOREGROUND1);
206 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
207 //TODO make author check case/blank-insensitive
208 context.draw_text(white_small_text,
209 std::string(_("contributed by ")) + level->get_author(),
210 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
213 if(best_level_statistics != NULL)
214 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
216 context.do_drawing();
218 wait_for_event(1.0, 3.0);
222 GameSession::on_escape_press()
224 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
225 return; // don't let the player open the menu, when he is dying
227 if(mode == ST_GL_TEST) {
228 exit_status = ES_LEVEL_ABORT;
229 } else if (!Menu::current()) {
230 Menu::set_current(game_menu);
231 game_menu->set_active_item(MNID_CONTINUE);
239 GameSession::process_events()
241 Player& tux = *currentsector->player;
242 main_controller->update();
244 // end of pause mode?
245 if(!Menu::current() && game_pause) {
249 if (end_sequence != NO_ENDSEQUENCE) {
250 if(end_sequence_controller == 0) {
251 end_sequence_controller = new CodeController();
252 tux.set_controller(end_sequence_controller);
255 end_sequence_controller->press(Controller::RIGHT);
257 if (int(last_x_pos) == int(tux.get_pos().x))
258 end_sequence_controller->press(Controller::JUMP);
259 last_x_pos = tux.get_pos().x;
262 main_controller->update();
264 while (SDL_PollEvent(&event)) {
265 /* Check for menu-events, if the menu is shown */
267 Menu::current()->event(event);
268 main_controller->process_event(event);
269 if(event.type == SDL_QUIT)
270 throw std::runtime_error("Received window close");
274 if(playback_demo_stream != 0) {
275 demo_controller->update();
282 playback_demo_stream->get(left);
283 playback_demo_stream->get(right);
284 playback_demo_stream->get(up);
285 playback_demo_stream->get(down);
286 playback_demo_stream->get(jump);
287 playback_demo_stream->get(action);
288 demo_controller->press(Controller::LEFT, left);
289 demo_controller->press(Controller::RIGHT, right);
290 demo_controller->press(Controller::UP, up);
291 demo_controller->press(Controller::DOWN, down);
292 demo_controller->press(Controller::JUMP, jump);
293 demo_controller->press(Controller::ACTION, action);
296 // save input for demo?
297 if(capture_demo_stream != 0) {
298 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
299 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
300 capture_demo_stream ->put(main_controller->hold(Controller::UP));
301 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
302 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
303 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
308 GameSession::try_cheats()
310 if(currentsector == 0)
312 Player& tux = *currentsector->player;
314 // Cheating words (the goal of this is really for debugging,
315 // but could be used for some cheating, nothing wrong with that)
316 if(main_controller->check_cheatcode("grow")) {
317 tux.set_bonus(GROWUP_BONUS, false);
319 if(main_controller->check_cheatcode("fire")) {
320 tux.set_bonus(FIRE_BONUS, false);
322 if(main_controller->check_cheatcode("ice")) {
323 tux.set_bonus(ICE_BONUS, false);
325 if(main_controller->check_cheatcode("lifeup")) {
326 player_status.lives++;
328 if(main_controller->check_cheatcode("lifedown")) {
329 player_status.lives--;
331 if(main_controller->check_cheatcode("grease")) {
332 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
334 if(main_controller->check_cheatcode("invincible")) {
335 // be invincle for the rest of the level
336 tux.invincible_timer.start(10000);
338 if(main_controller->check_cheatcode("shrink")) {
340 tux.kill(tux.SHRINK);
342 if(main_controller->check_cheatcode("kill")) {
343 // kill Tux, but without losing a life
344 player_status.lives++;
348 if(main_controller->check_cheatcode("grid")) {
350 debug_grid = !debug_grid;
353 if(main_controller->check_cheatcode("hover")) {
354 // toggle hover ability on/off
355 tux.enable_hover = !tux.enable_hover;
357 if(main_controller->check_cheatcode("gotoend")) {
358 // goes to the end of the level
360 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
361 currentsector->camera->reset(
362 Vector(tux.get_pos().x, tux.get_pos().y));
364 if(main_controller->check_cheatcode("finish")) {
365 // finish current sector
366 exit_status = ES_LEVEL_FINISHED;
367 // don't add points to stats though...
369 // temporary to help player's choosing a flapping
370 if(main_controller->check_cheatcode("marek")) {
371 tux.flapping_mode = Player::MAREK_FLAP;
373 if(main_controller->check_cheatcode("ricardo")) {
374 tux.flapping_mode = Player::RICARDO_FLAP;
376 if(main_controller->check_cheatcode("ryan")) {
377 tux.flapping_mode = Player::RYAN_FLAP;
382 GameSession::check_end_conditions()
384 Player* tux = currentsector->player;
387 if(end_sequence && endsequence_timer.check()) {
388 exit_status = ES_LEVEL_FINISHED;
390 } else if (!end_sequence && tux->is_dead()) {
391 if (player_status.lives < 0) { // No more lives!?
392 exit_status = ES_GAME_OVER;
393 } else { // Still has lives, so reset Tux to the levelstart
402 GameSession::update(float elapsed_time)
405 if(main_controller->pressed(Controller::PAUSE_MENU))
409 if(!currentsector->player->growing_timer.started()) {
410 // Update Tux and the World
411 currentsector->update(elapsed_time);
414 // respawning in new sector?
415 if(newsector != "" && newspawnpoint != "") {
416 Sector* sector = level->get_sector(newsector);
418 std::cerr << "Sector '" << newsector << "' not found.\n";
420 sector->activate(newspawnpoint);
421 sector->play_music(LEVEL_MUSIC);
422 currentsector = sector;
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(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
457 context->draw_filled_rect(
458 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
459 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
461 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
462 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
464 const char* str1 = _("Playing: ");
465 const char* str2 = level->get_name().c_str();
467 context->draw_text(blue_text, str1,
468 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
469 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
470 context->draw_text(white_text, str2,
471 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
472 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
477 GameSession::process_menu()
479 Menu* menu = Menu::current();
483 if(menu == game_menu) {
484 switch (game_menu->check()) {
486 Menu::set_current(0);
488 case MNID_ABORTLEVEL:
489 Menu::set_current(0);
490 exit_status = ES_LEVEL_ABORT;
493 } else if(menu == options_menu) {
494 process_options_menu();
495 } else if(menu == load_game_menu ) {
496 process_load_game_menu();
502 GameSession::ExitStatus
505 Menu::set_current(0);
510 // Eat unneeded events
512 while(SDL_PollEvent(&event))
517 Uint32 fps_ticks = SDL_GetTicks();
518 Uint32 fps_nextframe_ticks = SDL_GetTicks();
520 bool skipdraw = false;
522 while (exit_status == ES_NONE) {
523 // we run in a logical framerate so elapsed time is a constant
524 static const float elapsed_time = 1.0 / LOGICAL_FPS;
525 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
527 global_time += elapsed_time;
530 ticks = SDL_GetTicks();
531 if(ticks > fps_nextframe_ticks) {
532 if(skipdraw == true) {
533 // already skipped last frame? we have to slow down the game then...
535 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
537 // don't draw all frames when we're getting too slow
542 while(fps_nextframe_ticks > ticks) {
544 // If we really have to wait long, then do an imprecise SDL_Delay()
545 Uint32 diff = fps_nextframe_ticks - ticks;
547 SDL_Delay(diff - 10);
549 ticks = SDL_GetTicks();
552 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
555 float diff = SDL_GetTicks() - fps_nextframe_ticks;
557 // sets the ticks that must have elapsed
558 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
560 // sets the ticks that must have elapsed
561 // in order for the next frame to start.
562 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
569 // Update the world state and all objects in the world
570 // Do that with a constante time-delta so that the game will run
571 // determistic and not different on different machines
572 if(!game_pause && !Menu::current())
575 check_end_conditions();
576 if (end_sequence == ENDSEQUENCE_RUNNING)
577 update(elapsed_time/2);
578 else if(end_sequence == NO_ENDSEQUENCE)
579 update(elapsed_time);
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::display_info_box(const std::string& text)
654 InfoBox* box = new InfoBox(text);
659 main_controller->update();
661 while (SDL_PollEvent(&event)) {
662 main_controller->process_event(event);
663 if(event.type == SDL_QUIT)
664 throw std::runtime_error("Received window close event");
667 if(main_controller->pressed(Controller::JUMP)
668 || main_controller->pressed(Controller::ACTION)
669 || main_controller->pressed(Controller::PAUSE_MENU)
670 || main_controller->pressed(Controller::MENU_SELECT))
680 GameSession::start_sequence(const std::string& sequencename)
682 if(sequencename == "endsequence" || sequencename == "fireworks") {
686 end_sequence = ENDSEQUENCE_RUNNING;
687 endsequence_timer.start(7.0); // 7 seconds until we finish the map
689 sound_manager->play_music(level_end_song, 0);
690 currentsector->player->invincible_timer.start(7.0);
692 if(sequencename == "fireworks") {
693 currentsector->add_object(new Fireworks());
695 } else if(sequencename == "stoptux") {
696 end_sequence = ENDSEQUENCE_WAITING;
698 std::cout << "Unknown sequence '" << sequencename << "'.\n";
704 GameSession::drawstatus(DrawingContext& context)
706 player_status.draw(context);
708 if(config->show_fps) {
710 snprintf(str, sizeof(str), "%2.1f", fps_fps);
711 context.draw_text(white_text, "FPS",
712 Vector(SCREEN_WIDTH -
713 white_text->get_text_width("FPS "), 40),
714 LEFT_ALLIGN, LAYER_FOREGROUND1);
715 context.draw_text(gold_text, str,
716 Vector(SCREEN_WIDTH-4*16, 40),
717 LEFT_ALLIGN, LAYER_FOREGROUND1);
722 GameSession::drawresultscreen()
726 DrawingContext context;
727 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
728 i != currentsector->gameobjects.end(); ++i) {
729 Background* background = dynamic_cast<Background*> (*i);
731 background->draw(context);
735 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
736 CENTER_ALLIGN, LAYER_FOREGROUND1);
738 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
739 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
741 sprintf(str, _("COINS: %d"), player_status.coins);
742 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
744 context.do_drawing();
746 wait_for_event(2.0, 5.0);
749 std::string slotinfo(int slot)
752 std::string slotfile;
754 std::stringstream stream;
756 slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
760 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
762 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
764 throw std::runtime_error("file is not a supertux-savegame.");
766 savegame->get("title", title);
767 } catch(std::exception& e) {
768 return std::string(_("Slot")) + " " + stream.str() + " - " +
769 std::string(_("Free"));
772 return std::string("Slot ") + stream.str() + " - " + title;
775 bool process_load_game_menu()
777 int slot = load_game_menu->check();
782 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
785 std::stringstream stream;
787 std::string slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
790 DrawingContext context;
791 context.draw_text(white_text, "Loading...",
792 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
793 CENTER_ALLIGN, LAYER_FOREGROUND1);
794 context.do_drawing();
796 WorldMapNS::WorldMap worldmap;
798 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
799 // Load the game or at least set the savegame_file variable
800 worldmap.loadgame(slotfile);
804 Menu::set_current(main_menu);