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 <sys/types.h>
42 #include "app/globals.h"
43 #include "game_session.h"
44 #include "video/screen.h"
45 #include "app/setup.h"
50 #include "player_status.h"
51 #include "object/particlesystem.h"
52 #include "object/background.h"
53 #include "object/tilemap.h"
54 #include "object/camera.h"
55 #include "object/player.h"
56 #include "lisp/lisp.h"
57 #include "lisp/parser.h"
58 #include "resources.h"
59 #include "app/gettext.h"
62 #include "statistics.h"
64 #include "object/fireworks.h"
65 #include "textscroller.h"
66 #include "control/codecontroller.h"
67 #include "control/joystickkeyboardcontroller.h"
70 GameSession* GameSession::current_ = 0;
72 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
73 Statistics* statistics)
74 : level(0), currentsector(0), mode(mode),
75 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
76 levelfile(levelfile_), best_level_statistics(statistics)
83 context = new DrawingContext();
89 GameSession::restart_level()
92 exit_status = ES_NONE;
93 end_sequence = NO_ENDSEQUENCE;
95 main_controller->reset();
102 level->load(levelfile);
104 global_stats.reset();
105 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
106 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
107 global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
109 if(reset_sector != "") {
110 currentsector = level->get_sector(reset_sector);
112 std::stringstream msg;
113 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
114 throw std::runtime_error(msg.str());
116 currentsector->activate(reset_pos);
118 currentsector = level->get_sector("main");
120 throw std::runtime_error("Couldn't find main sector");
121 currentsector->activate("main");
124 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
128 currentsector->play_music(LEVEL_MUSIC);
131 GameSession::~GameSession()
133 delete end_sequence_controller;
139 GameSession::levelintro()
141 sound_manager->halt_music();
145 DrawingContext context;
146 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
147 i != currentsector->gameobjects.end(); ++i) {
148 Background* background = dynamic_cast<Background*> (*i);
150 background->draw(context);
154 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
155 // CENTER_ALLIGN, LAYER_FOREGROUND1);
156 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
159 sprintf(str, "TUX x %d", player_status.lives);
160 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
161 CENTER_ALLIGN, LAYER_FOREGROUND1);
163 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
164 //TODO make author check case/blank-insensitive
165 context.draw_text(white_small_text,
166 std::string(_("contributed by ")) + level->get_author(),
167 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
170 if(best_level_statistics != NULL)
171 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
173 context.do_drawing();
176 wait_for_event(event,1000,3000,true);
181 GameSession::start_timers()
183 time_left.start(level->timelimit);
188 GameSession::on_escape_press()
190 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
191 return; // don't let the player open the menu, when he is dying
193 if(mode == ST_GL_TEST) {
194 exit_status = ES_LEVEL_ABORT;
195 } else if (!Menu::current()) {
196 Menu::set_current(game_menu);
197 game_menu->set_active_item(MNID_CONTINUE);
198 Ticks::pause_start();
207 GameSession::process_events()
209 Player& tux = *currentsector->player;
210 main_controller->update();
212 // end of pause mode?
213 if(!Menu::current() && game_pause) {
218 if (end_sequence != NO_ENDSEQUENCE) {
219 if(end_sequence_controller == 0) {
220 end_sequence_controller = new CodeController();
221 tux.set_controller(end_sequence_controller);
224 end_sequence_controller->press(Controller::RIGHT);
226 if (int(last_x_pos) == int(tux.get_pos().x))
227 end_sequence_controller->press(Controller::JUMP);
228 last_x_pos = tux.get_pos().x;
231 main_controller->update();
233 while (SDL_PollEvent(&event)) {
234 /* Check for menu-events, if the menu is shown */
236 Menu::current()->event(event);
237 main_controller->process_event(event);
238 if(event.type == SDL_QUIT)
239 throw std::runtime_error("Received window close");
244 GameSession::try_cheats()
246 Player& tux = *currentsector->player;
248 // Cheating words (the goal of this is really for debugging,
249 // but could be used for some cheating, nothing wrong with that)
250 if(main_controller->check_cheatcode("grow")) {
251 tux.set_bonus(GROWUP_BONUS, false);
254 if(main_controller->check_cheatcode("fire")) {
255 tux.set_bonus(FIRE_BONUS, false);
258 if(main_controller->check_cheatcode("ice")) {
259 tux.set_bonus(ICE_BONUS, false);
262 if(main_controller->check_cheatcode("lifeup")) {
263 player_status.lives++;
266 if(main_controller->check_cheatcode("lifedown")) {
267 player_status.lives--;
270 if(main_controller->check_cheatcode("grease")) {
271 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
274 if(main_controller->check_cheatcode("invincible")) {
275 // be invincle for the rest of the level
276 tux.invincible_timer.start(10000);
279 if(main_controller->check_cheatcode("shrink")) {
281 tux.kill(tux.SHRINK);
284 if(main_controller->check_cheatcode("kill")) {
285 // kill Tux, but without losing a life
286 player_status.lives++;
291 if(main_controller->check_cheatcode("grid")) {
293 debug_grid = !debug_grid;
297 if(main_controller->check_cheatcode("hover")) {
298 // toggle hover ability on/off
299 tux.enable_hover = !tux.enable_hover;
302 if(main_controller->check_cheatcode("gotoend")) {
303 // goes to the end of the level
305 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
306 currentsector->camera->reset(
307 Vector(tux.get_pos().x, tux.get_pos().y));
310 if(main_controller->check_cheatcode("finish")) {
311 // finish current sector
312 exit_status = ES_LEVEL_FINISHED;
313 // don't add points to stats though...
315 // temporary to help player's choosing a flapping
316 if(main_controller->check_cheatcode("marek")) {
317 tux.flapping_mode = Player::MAREK_FLAP;
320 if(main_controller->check_cheatcode("ricardo")) {
321 tux.flapping_mode = Player::RICARDO_FLAP;
324 if(main_controller->check_cheatcode("ryan")) {
325 tux.flapping_mode = Player::RYAN_FLAP;
331 GameSession::check_end_conditions()
333 Player* tux = currentsector->player;
336 if(end_sequence && endsequence_timer.check()) {
337 exit_status = ES_LEVEL_FINISHED;
339 } else if (!end_sequence && tux->is_dead()) {
340 if (player_status.lives < 0) { // No more lives!?
341 exit_status = ES_GAME_OVER;
342 } else { // Still has lives, so reset Tux to the levelstart
351 GameSession::action(float elapsed_time)
354 if(main_controller->pressed(Controller::PAUSE_MENU))
358 if(!currentsector->player->growing_timer.started()) {
359 // Update Tux and the World
360 currentsector->action(elapsed_time);
363 // respawning in new sector?
364 if(newsector != "" && newspawnpoint != "") {
365 Sector* sector = level->get_sector(newsector);
367 std::cerr << "Sector '" << newsector << "' not found.\n";
369 sector->activate(newspawnpoint);
370 sector->play_music(LEVEL_MUSIC);
371 currentsector = sector;
380 currentsector->draw(*context);
381 drawstatus(*context);
386 if(Menu::current()) {
387 Menu::current()->draw(*context);
388 mouse_cursor->draw(*context);
391 context->do_drawing();
395 GameSession::draw_pause()
397 int x = SCREEN_HEIGHT / 20;
398 for(int i = 0; i < x; ++i) {
399 context->draw_filled_rect(
400 Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
401 -((pause_menu_frame * i)%SCREEN_WIDTH)
402 ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
403 Vector(SCREEN_WIDTH,10),
404 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
407 context->draw_filled_rect(
408 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
409 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
411 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
412 Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
414 const char* str1 = _("Playing: ");
415 const char* str2 = level->get_name().c_str();
417 context->draw_text(blue_text, str1,
418 Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
419 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
420 context->draw_text(white_text, str2,
421 Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
422 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
427 GameSession::process_menu()
429 Menu* menu = Menu::current();
433 if(menu == game_menu) {
434 switch (game_menu->check()) {
436 Menu::set_current(0);
438 case MNID_ABORTLEVEL:
439 Menu::set_current(0);
440 exit_status = ES_LEVEL_ABORT;
443 } else if(menu == options_menu) {
444 process_options_menu();
445 } else if(menu == load_game_menu ) {
446 process_load_game_menu();
452 GameSession::ExitStatus
455 Menu::set_current(0);
459 double fps_nextframe_ticks; // fps regulating code
461 // Eat unneeded events
463 while(SDL_PollEvent(&event))
468 Uint32 lastticks = SDL_GetTicks();
469 fps_ticks = SDL_GetTicks();
470 fps_nextframe_ticks = SDL_GetTicks(); // fps regulating code
472 while (exit_status == ES_NONE) {
473 Uint32 ticks = SDL_GetTicks();
474 float elapsed_time = float(ticks - lastticks) / 1000.;
476 global_time += elapsed_time;
480 if(elapsed_time > 0.025){
481 elapsed_time = 0.025;
484 // fps regualting code
485 const double wantedFps= 60.0; // set to 60 by now
486 while (fps_nextframe_ticks > SDL_GetTicks()){
488 // If we really have to wait long, then do an imprecise SDL_Delay()
489 if (fps_nextframe_ticks - SDL_GetTicks() > 15){
494 float diff = SDL_GetTicks() - fps_nextframe_ticks;
496 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / wantedFps); // sets the ticks that must have elapsed
498 fps_nextframe_ticks += 1000.0 / wantedFps; // sets the ticks that must have elapsed
499 // in order for the next frame to start.
504 // Update the world state and all objects in the world
505 // Do that with a constante time-delta so that the game will run
506 // determistic and not different on different machines
507 if(!game_pause && !Menu::current())
510 check_end_conditions();
511 if (end_sequence == ENDSEQUENCE_RUNNING)
512 action(elapsed_time/2);
513 else if(end_sequence == NO_ENDSEQUENCE)
514 action(elapsed_time);
524 /* Time stops in pause mode */
525 if(game_pause || Menu::current())
530 //frame_rate.update();
533 if (time_left.check() && !end_sequence)
534 currentsector->player->kill(Player::KILL);
537 if (currentsector->player->invincible_timer.started() && !end_sequence)
539 currentsector->play_music(HERRING_MUSIC);
541 /* or just normal music? */
542 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
544 currentsector->play_music(LEVEL_MUSIC);
547 /* Calculate frames per second */
552 if(SDL_GetTicks() - fps_ticks >= 500)
554 fps_fps = (float) fps_cnt / .5;
556 fps_ticks = SDL_GetTicks();
562 main_controller->reset();
567 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
570 newspawnpoint = spawnpoint;
574 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
576 reset_sector = sector;
581 GameSession::display_info_box(const std::string& text)
583 InfoBox* box = new InfoBox(text);
588 main_controller->update();
590 while (SDL_PollEvent(&event)) {
591 main_controller->process_event(event);
592 if(event.type == SDL_QUIT)
593 throw std::runtime_error("Received window close event");
596 if(main_controller->pressed(Controller::JUMP)
597 || main_controller->pressed(Controller::ACTION)
598 || main_controller->pressed(Controller::PAUSE_MENU)
599 || main_controller->pressed(Controller::MENU_SELECT))
609 GameSession::start_sequence(const std::string& sequencename)
611 if(sequencename == "endsequence" || sequencename == "fireworks") {
615 end_sequence = ENDSEQUENCE_RUNNING;
616 endsequence_timer.start(7.0); // 7 seconds until we finish the map
618 sound_manager->play_music(level_end_song, 0);
619 currentsector->player->invincible_timer.start(7.0);
621 // add left time to stats
622 global_stats.set_points(TIME_NEEDED_STAT,
623 int(time_left.get_period() - time_left.get_timeleft()));
625 if(sequencename == "fireworks") {
626 currentsector->add_object(new Fireworks());
628 } else if(sequencename == "stoptux") {
629 end_sequence = ENDSEQUENCE_WAITING;
631 std::cout << "Unknown sequence '" << sequencename << "'.\n";
637 GameSession::drawstatus(DrawingContext& context)
641 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
642 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
643 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
645 if(mode == ST_GL_TEST) {
646 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
647 LEFT_ALLIGN, LAYER_FOREGROUND1);
650 if(time_left.get_timeleft() < 0) {
651 context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, 0),
652 CENTER_ALLIGN, LAYER_FOREGROUND1);
653 } else if (time_left.get_timeleft() > TIME_WARNING
654 || int(global_time * 2.5) % 2) {
655 sprintf(str, " %d", int(time_left.get_timeleft()));
656 context.draw_text(white_text, _("TIME"),
657 Vector(SCREEN_WIDTH/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
658 context.draw_text(gold_text, str,
659 Vector(SCREEN_WIDTH/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
662 sprintf(str, " %d", player_status.coins);
663 context.draw_text(white_text, _("COINS"),
664 Vector(SCREEN_WIDTH - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
665 LEFT_ALLIGN, LAYER_FOREGROUND1);
666 context.draw_text(gold_text, str,
667 Vector(SCREEN_WIDTH - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
669 if (player_status.lives >= 5)
671 sprintf(str, "%dx", player_status.lives);
672 float x = SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w;
673 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
674 context.draw_surface(tux_life, Vector(SCREEN_WIDTH - 16, 20),
679 for(int i= 0; i < player_status.lives; ++i)
680 context.draw_surface(tux_life,
681 Vector(SCREEN_WIDTH - tux_life->w*4 +(tux_life->w*i), 20),
685 context.draw_text(white_text, _("LIVES"),
686 Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
687 LEFT_ALLIGN, LAYER_FOREGROUND1);
689 if(config->show_fps) {
690 sprintf(str, "%2.1f", fps_fps);
691 context.draw_text(white_text, "FPS",
692 Vector(SCREEN_WIDTH -
693 white_text->get_text_width("FPS "), 40),
694 LEFT_ALLIGN, LAYER_FOREGROUND1);
695 context.draw_text(gold_text, str,
696 Vector(SCREEN_WIDTH-4*16, 40),
697 LEFT_ALLIGN, LAYER_FOREGROUND1);
702 GameSession::drawresultscreen()
706 DrawingContext context;
707 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
708 i != currentsector->gameobjects.end(); ++i) {
709 Background* background = dynamic_cast<Background*> (*i);
711 background->draw(context);
715 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
716 CENTER_ALLIGN, LAYER_FOREGROUND1);
718 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
719 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
721 sprintf(str, _("COINS: %d"), player_status.coins);
722 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
724 context.do_drawing();
727 wait_for_event(event,2000,5000,true);
730 std::string slotinfo(int slot)
733 std::string slotfile;
735 std::stringstream stream;
737 slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
741 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
743 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
745 throw std::runtime_error("file is not a supertux-savegame.");
747 savegame->get("title", title);
748 } catch(std::exception& e) {
749 return std::string(_("Slot")) + " " + stream.str() + " - " +
750 std::string(_("Free"));
753 return std::string("Slot ") + stream.str() + " - " + title;
756 bool process_load_game_menu()
758 int slot = load_game_menu->check();
760 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
762 std::stringstream stream;
764 std::string slotfile = user_dir + "/save/slot" + stream.str() + ".stsg";
767 DrawingContext context;
768 context.draw_text(white_text, "Loading...",
769 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
770 context.do_drawing();
772 WorldMapNS::WorldMap worldmap;
774 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
775 // Load the game or at least set the savegame_file variable
776 worldmap.loadgame(slotfile);
780 Menu::set_current(main_menu);