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 lofical framerate of 64fps.
72 // We choose 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)
90 context = new DrawingContext();
96 GameSession::restart_level()
99 exit_status = ES_NONE;
100 end_sequence = NO_ENDSEQUENCE;
102 main_controller->reset();
108 level->load(levelfile);
110 global_stats.reset();
111 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
112 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
113 //global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
115 if(reset_sector != "") {
116 currentsector = level->get_sector(reset_sector);
118 std::stringstream msg;
119 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
120 throw std::runtime_error(msg.str());
122 currentsector->activate(reset_pos);
124 currentsector = level->get_sector("main");
126 throw std::runtime_error("Couldn't find main sector");
127 currentsector->activate("main");
130 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);
223 GameSession::on_escape_press()
225 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
226 return; // don't let the player open the menu, when he is dying
228 if(mode == ST_GL_TEST) {
229 exit_status = ES_LEVEL_ABORT;
230 } else if (!Menu::current()) {
231 Menu::set_current(game_menu);
232 game_menu->set_active_item(MNID_CONTINUE);
240 GameSession::process_events()
242 Player& tux = *currentsector->player;
243 main_controller->update();
245 // end of pause mode?
246 if(!Menu::current() && game_pause) {
250 if (end_sequence != NO_ENDSEQUENCE) {
251 if(end_sequence_controller == 0) {
252 end_sequence_controller = new CodeController();
253 tux.set_controller(end_sequence_controller);
256 end_sequence_controller->press(Controller::RIGHT);
258 if (int(last_x_pos) == int(tux.get_pos().x))
259 end_sequence_controller->press(Controller::JUMP);
260 last_x_pos = tux.get_pos().x;
263 main_controller->update();
265 while (SDL_PollEvent(&event)) {
266 /* Check for menu-events, if the menu is shown */
268 Menu::current()->event(event);
269 main_controller->process_event(event);
270 if(event.type == SDL_QUIT)
271 throw std::runtime_error("Received window close");
275 if(playback_demo_stream != 0) {
276 demo_controller->update();
283 playback_demo_stream->get(left);
284 playback_demo_stream->get(right);
285 playback_demo_stream->get(up);
286 playback_demo_stream->get(down);
287 playback_demo_stream->get(jump);
288 playback_demo_stream->get(action);
289 demo_controller->press(Controller::LEFT, left);
290 demo_controller->press(Controller::RIGHT, right);
291 demo_controller->press(Controller::UP, up);
292 demo_controller->press(Controller::DOWN, down);
293 demo_controller->press(Controller::JUMP, jump);
294 demo_controller->press(Controller::ACTION, action);
297 // save input for demo?
298 if(capture_demo_stream != 0) {
299 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
300 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
301 capture_demo_stream ->put(main_controller->hold(Controller::UP));
302 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
303 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
304 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
309 GameSession::try_cheats()
311 if(currentsector == 0)
313 Player& tux = *currentsector->player;
315 // Cheating words (the goal of this is really for debugging,
316 // but could be used for some cheating, nothing wrong with that)
317 if(main_controller->check_cheatcode("grow")) {
318 tux.set_bonus(GROWUP_BONUS, false);
320 if(main_controller->check_cheatcode("fire")) {
321 tux.set_bonus(FIRE_BONUS, false);
323 if(main_controller->check_cheatcode("ice")) {
324 tux.set_bonus(ICE_BONUS, false);
326 if(main_controller->check_cheatcode("lifeup")) {
327 player_status.lives++;
329 if(main_controller->check_cheatcode("lifedown")) {
330 player_status.lives--;
332 if(main_controller->check_cheatcode("grease")) {
333 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
335 if(main_controller->check_cheatcode("invincible")) {
336 // be invincle for the rest of the level
337 tux.invincible_timer.start(10000);
339 if(main_controller->check_cheatcode("shrink")) {
341 tux.kill(tux.SHRINK);
343 if(main_controller->check_cheatcode("kill")) {
344 // kill Tux, but without losing a life
345 player_status.lives++;
349 if(main_controller->check_cheatcode("grid")) {
351 debug_grid = !debug_grid;
354 if(main_controller->check_cheatcode("hover")) {
355 // toggle hover ability on/off
356 tux.enable_hover = !tux.enable_hover;
358 if(main_controller->check_cheatcode("gotoend")) {
359 // goes to the end of the level
361 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
362 currentsector->camera->reset(
363 Vector(tux.get_pos().x, tux.get_pos().y));
365 if(main_controller->check_cheatcode("finish")) {
366 // finish current sector
367 exit_status = ES_LEVEL_FINISHED;
368 // don't add points to stats though...
370 // temporary to help player's choosing a flapping
371 if(main_controller->check_cheatcode("marek")) {
372 tux.flapping_mode = Player::MAREK_FLAP;
374 if(main_controller->check_cheatcode("ricardo")) {
375 tux.flapping_mode = Player::RICARDO_FLAP;
377 if(main_controller->check_cheatcode("ryan")) {
378 tux.flapping_mode = Player::RYAN_FLAP;
383 GameSession::check_end_conditions()
385 Player* tux = currentsector->player;
388 if(end_sequence && endsequence_timer.check()) {
389 exit_status = ES_LEVEL_FINISHED;
391 } else if (!end_sequence && tux->is_dead()) {
392 if (player_status.lives < 0) { // No more lives!?
393 exit_status = ES_GAME_OVER;
394 } else { // Still has lives, so reset Tux to the levelstart
403 GameSession::update(float elapsed_time)
406 if(main_controller->pressed(Controller::PAUSE_MENU))
410 if(!currentsector->player->growing_timer.started()) {
411 // Update Tux and the World
412 currentsector->update(elapsed_time);
415 // respawning in new sector?
416 if(newsector != "" && newspawnpoint != "") {
417 Sector* sector = level->get_sector(newsector);
419 std::cerr << "Sector '" << newsector << "' not found.\n";
421 sector->activate(newspawnpoint);
422 sector->play_music(LEVEL_MUSIC);
423 currentsector = sector;
432 currentsector->draw(*context);
433 drawstatus(*context);
438 if(Menu::current()) {
439 Menu::current()->draw(*context);
442 context->do_drawing();
446 GameSession::draw_pause()
448 int x = SCREEN_HEIGHT / 20;
449 for(int i = 0; i < x; ++i) {
450 context->draw_filled_rect(
451 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
452 -((pause_menu_frame * i)%SCREEN_WIDTH)
453 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
454 Vector(SCREEN_WIDTH,10),
455 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
458 context->draw_filled_rect(
459 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
460 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
462 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
463 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
465 const char* str1 = _("Playing: ");
466 const char* str2 = level->get_name().c_str();
468 context->draw_text(blue_text, str1,
469 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
470 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
471 context->draw_text(white_text, str2,
472 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
473 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
478 GameSession::process_menu()
480 Menu* menu = Menu::current();
484 if(menu == game_menu) {
485 switch (game_menu->check()) {
487 Menu::set_current(0);
489 case MNID_ABORTLEVEL:
490 Menu::set_current(0);
491 exit_status = ES_LEVEL_ABORT;
494 } else if(menu == options_menu) {
495 process_options_menu();
496 } else if(menu == load_game_menu ) {
497 process_load_game_menu();
503 GameSession::ExitStatus
506 Menu::set_current(0);
511 // Eat unneeded events
513 while(SDL_PollEvent(&event))
518 Uint32 fps_ticks = SDL_GetTicks();
519 Uint32 fps_nextframe_ticks = SDL_GetTicks();
521 bool skipdraw = false;
523 while (exit_status == ES_NONE) {
524 // we run in a logical framerate so elapsed time is a constant
525 static const float elapsed_time = 1.0 / LOGICAL_FPS;
526 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
528 global_time += elapsed_time;
531 ticks = SDL_GetTicks();
532 if(ticks > fps_nextframe_ticks) {
533 if(skipdraw == true) {
534 // already skipped last frame? we have to slow down the game then...
536 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
538 // don't draw all frames when we're getting too slow
543 while(fps_nextframe_ticks > ticks) {
545 // If we really have to wait long, then do an imprecise SDL_Delay()
546 Uint32 diff = fps_nextframe_ticks - ticks;
548 SDL_Delay(diff - 10);
550 ticks = SDL_GetTicks();
553 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
556 float diff = SDL_GetTicks() - fps_nextframe_ticks;
558 // sets the ticks that must have elapsed
559 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
561 // sets the ticks that must have elapsed
562 // in order for the next frame to start.
563 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
570 // Update the world state and all objects in the world
571 // Do that with a constante time-delta so that the game will run
572 // determistic and not different on different machines
573 if(!game_pause && !Menu::current())
576 check_end_conditions();
577 if (end_sequence == ENDSEQUENCE_RUNNING)
578 update(elapsed_time/2);
579 else if(end_sequence == NO_ENDSEQUENCE)
580 update(elapsed_time);
590 /* Time stops in pause mode */
591 if(game_pause || Menu::current())
596 //frame_rate.update();
599 if (currentsector->player->invincible_timer.started() && !end_sequence)
601 currentsector->play_music(HERRING_MUSIC);
603 /* or just normal music? */
604 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
606 currentsector->play_music(LEVEL_MUSIC);
609 /* Calculate frames per second */
614 if(SDL_GetTicks() - fps_ticks >= 500)
616 fps_fps = (float) fps_cnt / .5;
618 fps_ticks = SDL_GetTicks();
625 main_controller->reset();
630 GameSession::finish(bool win)
633 exit_status = ES_LEVEL_FINISHED;
635 exit_status = ES_LEVEL_ABORT;
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::get_working_directory()
655 return FileSystem::dirname(levelfile);
659 GameSession::display_info_box(const std::string& text)
661 InfoBox* box = new InfoBox(text);
666 main_controller->update();
668 while (SDL_PollEvent(&event)) {
669 main_controller->process_event(event);
670 if(event.type == SDL_QUIT)
671 throw std::runtime_error("Received window close event");
674 if(main_controller->pressed(Controller::JUMP)
675 || main_controller->pressed(Controller::ACTION)
676 || main_controller->pressed(Controller::PAUSE_MENU)
677 || main_controller->pressed(Controller::MENU_SELECT))
687 GameSession::start_sequence(const std::string& sequencename)
689 if(sequencename == "endsequence" || sequencename == "fireworks") {
693 end_sequence = ENDSEQUENCE_RUNNING;
694 endsequence_timer.start(7.0); // 7 seconds until we finish the map
696 sound_manager->play_music(level_end_song, 0);
697 currentsector->player->invincible_timer.start(7.0);
699 if(sequencename == "fireworks") {
700 currentsector->add_object(new Fireworks());
702 } else if(sequencename == "stoptux") {
703 end_sequence = ENDSEQUENCE_WAITING;
705 std::cout << "Unknown sequence '" << sequencename << "'.\n";
711 GameSession::drawstatus(DrawingContext& context)
713 player_status.draw(context);
715 if(config->show_fps) {
717 snprintf(str, sizeof(str), "%2.1f", fps_fps);
718 context.draw_text(white_text, "FPS",
719 Vector(SCREEN_WIDTH -
720 white_text->get_text_width("FPS "), 40),
721 LEFT_ALLIGN, LAYER_FOREGROUND1);
722 context.draw_text(gold_text, str,
723 Vector(SCREEN_WIDTH-4*16, 40),
724 LEFT_ALLIGN, LAYER_FOREGROUND1);
729 GameSession::drawresultscreen()
733 DrawingContext context;
734 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
735 i != currentsector->gameobjects.end(); ++i) {
736 Background* background = dynamic_cast<Background*> (*i);
738 background->draw(context);
742 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
743 CENTER_ALLIGN, LAYER_FOREGROUND1);
745 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
746 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
748 sprintf(str, _("COINS: %d"), player_status.coins);
749 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
751 context.do_drawing();
753 wait_for_event(2.0, 5.0);
756 std::string slotinfo(int slot)
759 std::string slotfile;
761 std::stringstream stream;
763 slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
767 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
769 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
771 throw std::runtime_error("file is not a supertux-savegame.");
773 savegame->get("title", title);
774 } catch(std::exception& e) {
775 return std::string(_("Slot")) + " " + stream.str() + " - " +
776 std::string(_("Free"));
779 return std::string("Slot ") + stream.str() + " - " + title;
782 bool process_load_game_menu()
784 int slot = load_game_menu->check();
789 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
792 std::stringstream stream;
794 std::string slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
797 DrawingContext context;
798 context.draw_text(white_text, "Loading...",
799 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
800 CENTER_ALLIGN, LAYER_FOREGROUND1);
801 context.do_drawing();
803 WorldMapNS::WorldMap worldmap;
805 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
806 // Load the game or at least set the savegame_file variable
807 worldmap.loadgame(slotfile);
811 Menu::set_current(main_menu);