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.
36 #include <sys/types.h>
41 #include "app/globals.h"
43 #include "video/screen.h"
44 #include "app/setup.h"
45 #include "high_scores.h"
53 #include "collision.h"
55 #include "particlesystem.h"
56 #include "resources.h"
57 #include "background.h"
59 #include "app/gettext.h"
64 #include "statistics.h"
66 GameSession* GameSession::current_ = 0;
68 bool compare_last(std::string& haystack, std::string needle)
70 int haystack_size = haystack.size();
71 int needle_size = needle.size();
73 if(haystack_size < needle_size)
76 if(haystack.compare(haystack_size-needle_size, needle_size, needle) == 0)
81 GameSession::GameSession(const std::string& levelname_, int mode, bool flip_level_, Statistics* statistics)
82 : level(0), currentsector(0), st_gl_mode(mode),
83 end_sequence(NO_ENDSEQUENCE), levelname(levelname_), flip_level(flip_level_),
84 best_level_statistics(statistics)
88 global_frame_counter = 0;
93 frame_timer.init(true);
94 random_timer.init(true);
95 frame_rate.set_fps(100);
97 context = new DrawingContext();
102 last_swap_point = Vector(-1, -1);
103 last_swap_stats.reset();
109 GameSession::restart_level()
112 exit_status = ES_NONE;
113 end_sequence = NO_ENDSEQUENCE;
115 fps_timer.init(true);
116 frame_timer.init(true);
117 random_timer.init(true);
121 Vector tux_pos = Vector(-1,-1);
123 { // Tux has lost a life, so we try to respawn him at the nearest reset point
124 tux_pos = currentsector->player->base;
131 level->load(levelname);
133 level->do_vertical_flip();
135 global_stats.reset();
136 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
137 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
138 global_stats.set_total_points(TIME_NEEDED_STAT, level->time_left);
140 currentsector = level->get_sector("main");
142 Termination::abort("Level has no main sector.", "");
143 currentsector->activate("main");
145 // Set Tux to the nearest reset point
148 tux_pos = currentsector->get_best_spawn_point(tux_pos);
150 if(last_swap_point.x > tux_pos.x)
151 tux_pos = last_swap_point;
152 else // new swap point
154 last_swap_point = tux_pos;
156 last_swap_stats += global_stats;
159 currentsector->player->base.x = tux_pos.x;
160 currentsector->player->base.y = tux_pos.y;
162 // has to reset camera on swapping
163 currentsector->camera->reset(Vector(currentsector->player->base.x,
164 currentsector->player->base.y));
167 if (st_gl_mode != ST_GL_DEMO_GAME)
169 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
173 time_left.init(true);
175 currentsector->play_music(LEVEL_MUSIC);
178 GameSession::~GameSession()
185 GameSession::levelintro(void)
187 SoundManager::get()->halt_music();
191 DrawingContext context;
192 currentsector->background->draw(context);
194 // context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
195 // CENTER_ALLIGN, LAYER_FOREGROUND1);
196 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
199 sprintf(str, "TUX x %d", player_status.lives);
200 context.draw_text(white_text, str, Vector(screen->w/2, 210),
201 CENTER_ALLIGN, LAYER_FOREGROUND1);
203 if(level->get_author().size())
204 context.draw_text(white_small_text,
205 std::string(_("by ")) + level->get_author(),
206 Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
210 context.draw_text(white_text,
211 _("Level Vertically Flipped!"),
212 Vector(screen->w/2, 310), 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();
220 wait_for_event(event,1000,3000,true);
225 GameSession::start_timers()
227 time_left.start(level->time_left*1000);
233 GameSession::on_escape_press()
235 if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
236 return; // don't let the player open the menu, when he is dying
241 if(st_gl_mode == ST_GL_TEST)
243 exit_status = ES_LEVEL_ABORT;
245 else if (!Menu::current())
247 /* Tell Tux that the keys are all down, otherwise
248 it could have nasty bugs, like going allways to the right
249 or whatever that key does */
250 Player& tux = *(currentsector->player);
251 tux.key_event((SDLKey)keymap.jump, UP);
252 tux.key_event((SDLKey)keymap.duck, UP);
253 tux.key_event((SDLKey)keymap.left, UP);
254 tux.key_event((SDLKey)keymap.right, UP);
255 tux.key_event((SDLKey)keymap.fire, UP);
257 Menu::set_current(game_menu);
258 Ticks::pause_start();
263 GameSession::process_events()
265 if (end_sequence != NO_ENDSEQUENCE)
267 Player& tux = *currentsector->player;
271 tux.input.right = DOWN;
274 if (int(last_x_pos) == int(tux.base.x))
279 last_x_pos = tux.base.x;
282 while (SDL_PollEvent(&event))
284 /* Check for menu-events, if the menu is shown */
287 Menu::current()->event(event);
294 case SDL_QUIT: /* Quit event - quit: */
295 Termination::abort("Received window close", "");
298 case SDL_KEYDOWN: /* A keypress! */
300 SDLKey key = event.key.keysym.sym;
304 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
312 case SDL_JOYBUTTONDOWN:
313 if (event.jbutton.button == joystick_keymap.start_button)
321 if(!Menu::current() && !game_pause)
325 while (SDL_PollEvent(&event))
327 /* Check for menu-events, if the menu is shown */
330 Menu::current()->event(event);
336 Player& tux = *currentsector->player;
340 case SDL_QUIT: /* Quit event - quit: */
341 Termination::abort("Received window close", "");
344 case SDL_KEYDOWN: /* A keypress! */
346 SDLKey key = event.key.keysym.sym;
348 if(tux.key_event(key,DOWN))
353 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
361 case SDL_KEYUP: /* A keyrelease! */
363 SDLKey key = event.key.keysym.sym;
365 if(tux.key_event(key, UP))
374 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
375 tux.base.x, tux.base.y);
376 context->draw_text(white_text, buf,
377 Vector(0, screen->h - white_text->get_height()),
378 LEFT_ALLIGN, LAYER_FOREGROUND1);
379 context->do_drawing();
386 // "lifeup" cheat activates pause cause of the 'p'
387 // so work around to ignore it
388 if(compare_last(last_keys, "lifeu"))
399 Ticks::pause_start();
408 /* Check if chacrater is ASCII */
410 if((event.key.keysym.unicode & 0xFF80) == 0)
412 ch[0] = event.key.keysym.unicode & 0x7F;
415 last_keys.append(ch); // add to cheat keys
417 // Cheating words (the goal of this is really for debugging,
418 // but could be used for some cheating, nothing wrong with that)
419 if(compare_last(last_keys, "grow"))
424 if(compare_last(last_keys, "fire"))
427 tux.got_power = tux.FIRE_POWER;
430 if(compare_last(last_keys, "ice"))
433 tux.got_power = tux.ICE_POWER;
436 if(compare_last(last_keys, "lifeup"))
438 player_status.lives++;
441 if(compare_last(last_keys, "lifedown"))
443 player_status.lives--;
446 if(compare_last(last_keys, "invincible"))
447 { // be invincle for the rest of the level
448 tux.invincible_timer.start(time_left.get_left());
451 if(compare_last(last_keys, "shrink"))
453 tux.kill(tux.SHRINK);
456 if(compare_last(last_keys, "kill"))
457 { // kill Tux, but without losing a life
458 player_status.lives++;
462 if(compare_last(last_keys, "hover"))
463 { // toggle hover ability on/off
464 tux.enable_hover = !tux.enable_hover;
467 if(compare_last(last_keys, "gotoend"))
468 { // goes to the end of the level
469 tux.base.x = (currentsector->solids->get_width()*32) - (screen->w*2);
471 currentsector->camera->reset(Vector(tux.base.x, tux.base.y));
476 case SDL_JOYAXISMOTION:
477 if (event.jaxis.axis == joystick_keymap.x_axis)
479 if (event.jaxis.value < -joystick_keymap.dead_zone)
481 tux.input.left = DOWN;
482 tux.input.right = UP;
484 else if (event.jaxis.value > joystick_keymap.dead_zone)
487 tux.input.right = DOWN;
491 tux.input.left = DOWN;
492 tux.input.right = DOWN;
495 else if (event.jaxis.axis == joystick_keymap.y_axis)
497 if (event.jaxis.value > joystick_keymap.dead_zone)
498 tux.input.down = DOWN;
499 else if (event.jaxis.value < -joystick_keymap.dead_zone)
506 case SDL_JOYHATMOTION:
507 if(event.jhat.value & SDL_HAT_UP) {
510 } else if(event.jhat.value & SDL_HAT_DOWN) {
512 tux.input.down = DOWN;
513 } else if(event.jhat.value & SDL_HAT_LEFT) {
514 tux.input.left = DOWN;
515 tux.input.right = UP;
516 } else if(event.jhat.value & SDL_HAT_RIGHT) {
518 tux.input.right = DOWN;
519 } else if(event.jhat.value == SDL_HAT_CENTERED) {
521 tux.input.right = UP;
527 case SDL_JOYBUTTONDOWN:
528 if (event.jbutton.button == joystick_keymap.a_button)
530 else if (event.jbutton.button == joystick_keymap.b_button)
531 tux.input.fire = DOWN;
532 else if (event.jbutton.button == joystick_keymap.start_button)
535 case SDL_JOYBUTTONUP:
536 if (event.jbutton.button == joystick_keymap.a_button)
538 else if (event.jbutton.button == joystick_keymap.b_button)
551 GameSession::check_end_conditions()
553 Player* tux = currentsector->player;
556 Tile* endtile = collision_goal(tux->base);
558 if(end_sequence && !endsequence_timer.check())
560 exit_status = ES_LEVEL_FINISHED;
561 global_stats += last_swap_stats; // add swap points stats
564 else if(end_sequence == ENDSEQUENCE_RUNNING && endtile && endtile->data >= 1)
566 end_sequence = ENDSEQUENCE_WAITING;
568 else if(!end_sequence && endtile && endtile->data == 0)
570 end_sequence = ENDSEQUENCE_RUNNING;
571 endsequence_timer.start(7000); // 5 seconds until we finish the map
573 SoundManager::get()->play_music(level_end_song, 0);
574 tux->invincible_timer.start(7000); //FIXME: Implement a winning timer for the end sequence (with special winning animation etc.)
576 // add left time to stats
577 global_stats.set_points(TIME_NEEDED_STAT, time_left.get_gone() / 1000);
579 random_timer.start(200); // start 1st firework
581 else if (!end_sequence && tux->is_dead())
583 player_status.bonus = PlayerStatus::NO_BONUS;
585 if (player_status.lives < 0)
587 exit_status = ES_GAME_OVER;
590 { // Still has lives, so reset Tux to the levelstart
599 GameSession::action(double frame_ratio)
601 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
603 // Update Tux and the World
604 currentsector->action(frame_ratio);
607 // respawning in new sector?
608 if(newsector != "" && newspawnpoint != "") {
609 Sector* sector = level->get_sector(newsector);
610 currentsector = sector;
611 currentsector->activate(newspawnpoint);
612 currentsector->play_music(LEVEL_MUSIC);
613 newsector = newspawnpoint = "";
616 // on end sequence make a few fireworks
617 if(end_sequence == ENDSEQUENCE_RUNNING && !random_timer.check() &&
618 currentsector->end_sequence_animation() == FIREWORKS_ENDSEQ_ANIM)
620 Vector epicenter = currentsector->camera->get_translation();
621 epicenter.x += screen->w * ((float)rand() / RAND_MAX);
622 epicenter.y += (screen->h/2) * ((float)rand() / RAND_MAX);
624 int red = rand() % 255; // calculate firework color
625 int green = rand() % red;
626 currentsector->add_particles(epicenter, Vector(1.4,1.4), Vector(0,0),
627 45, Color(red,green,0), 3, 1300);
629 SoundManager::get()->play_sound(IDToSound(SND_FIREWORKS));
630 random_timer.start(rand() % 400 + 600); // next firework
637 currentsector->draw(*context);
638 drawstatus(*context);
642 int x = screen->h / 20;
643 for(int i = 0; i < x; ++i)
645 context->draw_filled_rect(
646 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
647 -((pause_menu_frame * i)%screen->w)
648 ,(i*20+pause_menu_frame)%screen->h),
649 Vector(screen->w,10),
650 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
652 context->draw_filled_rect(
653 Vector(0,0), Vector(screen->w, screen->h),
654 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
655 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
656 Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
660 sprintf(str1, _("Playing: "));
661 sprintf(str2, level->name.c_str());
663 context->draw_text(blue_text, str1,
664 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
665 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
666 context->draw_text(white_text, str2,
667 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
668 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
673 Menu::current()->draw(*context);
674 mouse_cursor->draw(*context);
677 context->do_drawing();
681 GameSession::process_menu()
683 Menu* menu = Menu::current();
688 if(menu == game_menu)
690 switch (game_menu->check())
695 case MNID_ABORTLEVEL:
697 exit_status = ES_LEVEL_ABORT;
701 else if(menu == options_menu)
703 process_options_menu();
705 else if(menu == load_game_menu )
707 process_load_game_menu();
712 GameSession::ExitStatus
715 Menu::set_current(0);
722 // Eat unneeded events
724 while (SDL_PollEvent(&event)) {}
728 while (exit_status == ES_NONE)
730 /* Calculate the movement-factor */
731 double frame_ratio = frame_rate.get();
733 if(!frame_timer.check())
735 frame_timer.start(25);
736 ++global_frame_counter;
740 currentsector->player->input.old_fire
741 = currentsector->player->input.fire;
746 // Update the world state and all objects in the world
747 // Do that with a constante time-delta so that the game will run
748 // determistic and not different on different machines
749 if(!game_pause && !Menu::current())
752 check_end_conditions();
753 if (end_sequence == ENDSEQUENCE_RUNNING)
754 action(frame_ratio/2);
755 else if(end_sequence == NO_ENDSEQUENCE)
766 /* Time stops in pause mode */
767 if(game_pause || Menu::current())
775 if (!time_left.check() && currentsector->player->dying == DYING_NOT
777 currentsector->player->kill(Player::KILL);
780 if(currentsector->player->invincible_timer.check() && !end_sequence)
782 currentsector->play_music(HERRING_MUSIC);
784 /* are we low on time ? */
785 else if (time_left.get_left() < TIME_WARNING && !end_sequence)
787 currentsector->play_music(HURRYUP_MUSIC);
789 /* or just normal music? */
790 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
792 currentsector->play_music(LEVEL_MUSIC);
795 /* Calculate frames per second */
799 fps_fps = (1000.0 / (float)fps_timer.get_gone()) * (float)fps_cnt;
801 if(!fps_timer.check())
803 fps_timer.start(1000);
813 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
816 newspawnpoint = spawnpoint;
819 /* Bounce a brick: */
820 void bumpbrick(float x, float y)
822 Sector::current()->add_bouncy_brick(Vector(((int)(x + 1) / 32) * 32,
823 (int)(y / 32) * 32));
825 SoundManager::get()->play_sound(IDToSound(SND_BRICK), Vector(x, y), Sector::current()->player->get_pos());
830 GameSession::drawstatus(DrawingContext& context)
834 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
835 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
836 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
838 if(st_gl_mode == ST_GL_TEST)
840 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
841 LEFT_ALLIGN, LAYER_FOREGROUND1);
844 if(!time_left.check()) {
845 context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
846 CENTER_ALLIGN, LAYER_FOREGROUND1);
847 } else if (time_left.get_left() > TIME_WARNING || (global_frame_counter % 10) < 5) {
848 sprintf(str, " %d", time_left.get_left() / 1000 );
849 context.draw_text(white_text, _("TIME"),
850 Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
851 context.draw_text(gold_text, str,
852 Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
855 sprintf(str, " %d", player_status.distros);
856 context.draw_text(white_text, _("COINS"),
857 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
858 LEFT_ALLIGN, LAYER_FOREGROUND1);
859 context.draw_text(gold_text, str,
860 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
862 if (player_status.lives >= 5)
864 sprintf(str, "%dx", player_status.lives);
865 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
866 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
867 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
872 for(int i= 0; i < player_status.lives; ++i)
873 context.draw_surface(tux_life,
874 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
878 context.draw_text(white_text, _("LIVES"),
879 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
880 LEFT_ALLIGN, LAYER_FOREGROUND1);
884 sprintf(str, "%2.1f", fps_fps);
885 context.draw_text(white_text, "FPS",
886 Vector(screen->w - white_text->get_text_width("FPS "), 40),
887 LEFT_ALLIGN, LAYER_FOREGROUND1);
888 context.draw_text(gold_text, str,
889 Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
894 GameSession::drawresultscreen(void)
898 DrawingContext context;
899 currentsector->background->draw(context);
901 context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
902 CENTER_ALLIGN, LAYER_FOREGROUND1);
904 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
905 context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
907 sprintf(str, _("COINS: %d"), player_status.distros);
908 context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
910 context.do_drawing();
913 wait_for_event(event,2000,5000,true);
916 std::string slotinfo(int slot)
919 std::string slotfile;
921 std::stringstream stream;
923 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
925 lisp_object_t* savegame = lisp_read_from_file(slotfile.c_str());
928 LispReader reader(lisp_cdr(savegame));
929 reader.read_string("title", title);
933 if (access(slotfile.c_str(), F_OK) == 0)
936 tmp = "Slot " + stream.str() + " - " + title;
938 tmp = "Slot " + stream.str() + " - Savegame";
941 tmp = std::string(_("Slot")) + " " + stream.str() + " - " + std::string(_("Free"));
946 bool process_load_game_menu()
948 int slot = load_game_menu->check();
950 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
952 std::stringstream stream;
954 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
956 if (access(slotfile.c_str(), F_OK) != 0)
961 // shrink_fade(Point((screen->w/2),(screen->h/2)), 1000);
964 DrawingContext context;
965 context.draw_text(white_text, "Loading...",
966 Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
967 context.do_drawing();
969 WorldMapNS::WorldMap worldmap;
971 worldmap.set_map_filename("icyisland.stwm");
972 // Load the game or at least set the savegame_file variable
973 worldmap.loadgame(slotfile);
977 Menu::set_current(main_menu);