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)
133 currentsector->play_music(LEVEL_MUSIC);
135 if(capture_file != "")
136 record_demo(capture_file);
139 GameSession::~GameSession()
141 delete capture_demo_stream;
142 delete playback_demo_stream;
143 delete demo_controller;
145 delete end_sequence_controller;
151 GameSession::record_demo(const std::string& filename)
153 delete capture_demo_stream;
155 capture_demo_stream = new std::ofstream(filename.c_str());
156 if(!capture_demo_stream->good()) {
157 std::stringstream msg;
158 msg << "Couldn't open demo file '" << filename << "' for writing.";
159 throw std::runtime_error(msg.str());
161 capture_file = filename;
165 GameSession::play_demo(const std::string& filename)
167 delete playback_demo_stream;
168 delete demo_controller;
170 playback_demo_stream = new std::ifstream(filename.c_str());
171 if(!playback_demo_stream->good()) {
172 std::stringstream msg;
173 msg << "Couldn't open demo file '" << filename << "' for reading.";
174 throw std::runtime_error(msg.str());
177 Player& tux = *currentsector->player;
178 demo_controller = new CodeController();
179 tux.set_controller(demo_controller);
183 GameSession::levelintro()
185 sound_manager->halt_music();
189 DrawingContext context;
190 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
191 i != currentsector->gameobjects.end(); ++i) {
192 Background* background = dynamic_cast<Background*> (*i);
194 background->draw(context);
198 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
199 // CENTER_ALLIGN, LAYER_FOREGROUND1);
200 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
203 sprintf(str, "TUX x %d", player_status.lives);
204 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
205 CENTER_ALLIGN, LAYER_FOREGROUND1);
207 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
208 //TODO make author check case/blank-insensitive
209 context.draw_text(white_small_text,
210 std::string(_("contributed by ")) + level->get_author(),
211 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
214 if(best_level_statistics != NULL)
215 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
217 context.do_drawing();
219 wait_for_event(1.0, 3.0);
224 GameSession::start_timers()
226 time_left.start(level->timelimit);
230 GameSession::on_escape_press()
232 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
233 return; // don't let the player open the menu, when he is dying
235 if(mode == ST_GL_TEST) {
236 exit_status = ES_LEVEL_ABORT;
237 } else if (!Menu::current()) {
238 Menu::set_current(game_menu);
239 game_menu->set_active_item(MNID_CONTINUE);
247 GameSession::process_events()
249 Player& tux = *currentsector->player;
250 main_controller->update();
252 // end of pause mode?
253 if(!Menu::current() && game_pause) {
257 if (end_sequence != NO_ENDSEQUENCE) {
258 if(end_sequence_controller == 0) {
259 end_sequence_controller = new CodeController();
260 tux.set_controller(end_sequence_controller);
263 end_sequence_controller->press(Controller::RIGHT);
265 if (int(last_x_pos) == int(tux.get_pos().x))
266 end_sequence_controller->press(Controller::JUMP);
267 last_x_pos = tux.get_pos().x;
270 main_controller->update();
272 while (SDL_PollEvent(&event)) {
273 /* Check for menu-events, if the menu is shown */
275 Menu::current()->event(event);
276 main_controller->process_event(event);
277 if(event.type == SDL_QUIT)
278 throw std::runtime_error("Received window close");
282 if(playback_demo_stream != 0) {
283 demo_controller->update();
290 playback_demo_stream->get(left);
291 playback_demo_stream->get(right);
292 playback_demo_stream->get(up);
293 playback_demo_stream->get(down);
294 playback_demo_stream->get(jump);
295 playback_demo_stream->get(action);
296 demo_controller->press(Controller::LEFT, left);
297 demo_controller->press(Controller::RIGHT, right);
298 demo_controller->press(Controller::UP, up);
299 demo_controller->press(Controller::DOWN, down);
300 demo_controller->press(Controller::JUMP, jump);
301 demo_controller->press(Controller::ACTION, action);
304 // save input for demo?
305 if(capture_demo_stream != 0) {
306 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
307 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
308 capture_demo_stream ->put(main_controller->hold(Controller::UP));
309 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
310 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
311 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
316 GameSession::try_cheats()
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::action(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->action(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);
445 mouse_cursor->draw(*context);
448 context->do_drawing();
452 GameSession::draw_pause()
454 int x = SCREEN_HEIGHT / 20;
455 for(int i = 0; i < x; ++i) {
456 context->draw_filled_rect(
457 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
458 -((pause_menu_frame * i)%SCREEN_WIDTH)
459 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
460 Vector(SCREEN_WIDTH,10),
461 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
464 context->draw_filled_rect(
465 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
466 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
468 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
469 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
471 const char* str1 = _("Playing: ");
472 const char* str2 = level->get_name().c_str();
474 context->draw_text(blue_text, str1,
475 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
476 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
477 context->draw_text(white_text, str2,
478 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
479 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
484 GameSession::process_menu()
486 Menu* menu = Menu::current();
490 if(menu == game_menu) {
491 switch (game_menu->check()) {
493 Menu::set_current(0);
495 case MNID_ABORTLEVEL:
496 Menu::set_current(0);
497 exit_status = ES_LEVEL_ABORT;
500 } else if(menu == options_menu) {
501 process_options_menu();
502 } else if(menu == load_game_menu ) {
503 process_load_game_menu();
509 GameSession::ExitStatus
512 Menu::set_current(0);
517 // Eat unneeded events
519 while(SDL_PollEvent(&event))
524 Uint32 fps_ticks = SDL_GetTicks();
525 Uint32 fps_nextframe_ticks = SDL_GetTicks();
527 bool skipdraw = false;
529 while (exit_status == ES_NONE) {
530 // we run in a logical framerate so elapsed time is a constant
531 static const float elapsed_time = 1.0 / LOGICAL_FPS;
532 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
534 global_time += elapsed_time;
537 ticks = SDL_GetTicks();
538 if(ticks > fps_nextframe_ticks) {
539 if(skipdraw == true) {
540 // already skipped last frame? we have to slow down the game then...
542 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
544 // don't draw all frames when we're getting too slow
549 while(fps_nextframe_ticks > ticks) {
551 // If we really have to wait long, then do an imprecise SDL_Delay()
552 Uint32 diff = fps_nextframe_ticks - ticks;
554 SDL_Delay(diff - 10);
556 ticks = SDL_GetTicks();
559 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
562 float diff = SDL_GetTicks() - fps_nextframe_ticks;
564 // sets the ticks that must have elapsed
565 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
567 // sets the ticks that must have elapsed
568 // in order for the next frame to start.
569 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
576 // Update the world state and all objects in the world
577 // Do that with a constante time-delta so that the game will run
578 // determistic and not different on different machines
579 if(!game_pause && !Menu::current())
582 check_end_conditions();
583 if (end_sequence == ENDSEQUENCE_RUNNING)
584 action(elapsed_time/2);
585 else if(end_sequence == NO_ENDSEQUENCE)
586 action(elapsed_time);
596 /* Time stops in pause mode */
597 if(game_pause || Menu::current())
602 //frame_rate.update();
605 if (time_left.check() && !end_sequence)
606 currentsector->player->kill(Player::KILL);
609 if (currentsector->player->invincible_timer.started() && !end_sequence)
611 currentsector->play_music(HERRING_MUSIC);
613 /* or just normal music? */
614 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
616 currentsector->play_music(LEVEL_MUSIC);
619 /* Calculate frames per second */
624 if(SDL_GetTicks() - fps_ticks >= 500)
626 fps_fps = (float) fps_cnt / .5;
628 fps_ticks = SDL_GetTicks();
634 main_controller->reset();
639 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
642 newspawnpoint = spawnpoint;
646 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
648 reset_sector = sector;
653 GameSession::display_info_box(const std::string& text)
655 InfoBox* box = new InfoBox(text);
660 main_controller->update();
662 while (SDL_PollEvent(&event)) {
663 main_controller->process_event(event);
664 if(event.type == SDL_QUIT)
665 throw std::runtime_error("Received window close event");
668 if(main_controller->pressed(Controller::JUMP)
669 || main_controller->pressed(Controller::ACTION)
670 || main_controller->pressed(Controller::PAUSE_MENU)
671 || main_controller->pressed(Controller::MENU_SELECT))
681 GameSession::start_sequence(const std::string& sequencename)
683 if(sequencename == "endsequence" || sequencename == "fireworks") {
687 end_sequence = ENDSEQUENCE_RUNNING;
688 endsequence_timer.start(7.0); // 7 seconds until we finish the map
690 sound_manager->play_music(level_end_song, 0);
691 currentsector->player->invincible_timer.start(7.0);
693 // add left time to stats
694 global_stats.set_points(TIME_NEEDED_STAT,
695 int(time_left.get_period() - time_left.get_timeleft()));
697 if(sequencename == "fireworks") {
698 currentsector->add_object(new Fireworks());
700 } else if(sequencename == "stoptux") {
701 end_sequence = ENDSEQUENCE_WAITING;
703 std::cout << "Unknown sequence '" << sequencename << "'.\n";
709 GameSession::drawstatus(DrawingContext& context)
713 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
714 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
715 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
717 if(mode == ST_GL_TEST) {
718 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
719 LEFT_ALLIGN, LAYER_FOREGROUND1);
722 if(time_left.get_timeleft() < 0) {
723 context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, 0),
724 CENTER_ALLIGN, LAYER_FOREGROUND1);
725 } else if (time_left.get_timeleft() > TIME_WARNING
726 || int(global_time * 2.5) % 2) {
727 sprintf(str, " %d", int(time_left.get_timeleft()));
728 context.draw_text(white_text, _("TIME"),
729 Vector(SCREEN_WIDTH/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
730 context.draw_text(gold_text, str,
731 Vector(SCREEN_WIDTH/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
734 sprintf(str, " %d", player_status.coins);
735 context.draw_text(white_text, _("COINS"),
736 Vector(SCREEN_WIDTH - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
737 LEFT_ALLIGN, LAYER_FOREGROUND1);
738 context.draw_text(gold_text, str,
739 Vector(SCREEN_WIDTH - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
741 if (player_status.lives >= 5)
743 sprintf(str, "%dx", player_status.lives);
744 float x = SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w;
745 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
746 context.draw_surface(tux_life, Vector(SCREEN_WIDTH - 16, 20),
751 for(int i= 0; i < player_status.lives; ++i)
752 context.draw_surface(tux_life,
753 Vector(SCREEN_WIDTH - tux_life->w*4 +(tux_life->w*i), 20),
757 context.draw_text(white_text, _("LIVES"),
758 Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
759 LEFT_ALLIGN, LAYER_FOREGROUND1);
761 if(config->show_fps) {
762 sprintf(str, "%2.1f", fps_fps);
763 context.draw_text(white_text, "FPS",
764 Vector(SCREEN_WIDTH -
765 white_text->get_text_width("FPS "), 40),
766 LEFT_ALLIGN, LAYER_FOREGROUND1);
767 context.draw_text(gold_text, str,
768 Vector(SCREEN_WIDTH-4*16, 40),
769 LEFT_ALLIGN, LAYER_FOREGROUND1);
774 GameSession::drawresultscreen()
778 DrawingContext context;
779 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
780 i != currentsector->gameobjects.end(); ++i) {
781 Background* background = dynamic_cast<Background*> (*i);
783 background->draw(context);
787 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
788 CENTER_ALLIGN, LAYER_FOREGROUND1);
790 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
791 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
793 sprintf(str, _("COINS: %d"), player_status.coins);
794 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
796 context.do_drawing();
798 wait_for_event(2.0, 5.0);
801 std::string slotinfo(int slot)
804 std::string slotfile;
806 std::stringstream stream;
808 slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
812 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
814 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
816 throw std::runtime_error("file is not a supertux-savegame.");
818 savegame->get("title", title);
819 } catch(std::exception& e) {
820 return std::string(_("Slot")) + " " + stream.str() + " - " +
821 std::string(_("Free"));
824 return std::string("Slot ") + stream.str() + " - " + title;
827 bool process_load_game_menu()
829 int slot = load_game_menu->check();
834 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
837 std::stringstream stream;
839 std::string slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
842 DrawingContext context;
843 context.draw_text(white_text, "Loading...",
844 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
845 CENTER_ALLIGN, LAYER_FOREGROUND1);
846 context.do_drawing();
848 WorldMapNS::WorldMap worldmap;
850 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
851 // Load the game or at least set the savegame_file variable
852 worldmap.loadgame(slotfile);
856 Menu::set_current(main_menu);