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();
106 GameSession::restart_level()
109 exit_status = ES_NONE;
110 end_sequence = NO_ENDSEQUENCE;
112 fps_timer.init(true);
113 frame_timer.init(true);
114 random_timer.init(true);
118 Vector tux_pos = Vector(-1,-1);
120 { // Tux has lost a life, so we try to respawn him at the nearest reset point
121 tux_pos = currentsector->player->base;
128 level->load(levelname);
130 level->do_vertical_flip();
132 global_stats.reset();
133 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
134 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
135 global_stats.set_total_points(TIME_NEEDED_STAT, level->time_left);
137 currentsector = level->get_sector("main");
139 Termination::abort("Level has no main sector.", "");
140 currentsector->activate("main");
142 // Set Tux to the nearest reset point
145 tux_pos = currentsector->get_best_spawn_point(tux_pos);
146 currentsector->player->base.x = tux_pos.x;
147 currentsector->player->base.y = tux_pos.y;
149 // has to reset camera on swapping
150 currentsector->camera->reset(Vector(currentsector->player->base.x,
151 currentsector->player->base.y));
154 if (st_gl_mode != ST_GL_DEMO_GAME)
156 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
160 time_left.init(true);
162 currentsector->play_music(LEVEL_MUSIC);
165 GameSession::~GameSession()
172 GameSession::levelintro(void)
174 SoundManager::get()->halt_music();
178 DrawingContext context;
179 currentsector->background->draw(context);
181 context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
182 CENTER_ALLIGN, LAYER_FOREGROUND1);
184 sprintf(str, "TUX x %d", player_status.lives);
185 context.draw_text(white_text, str, Vector(screen->w/2, 210),
186 CENTER_ALLIGN, LAYER_FOREGROUND1);
188 if(level->get_author().size())
189 context.draw_text(white_small_text,
190 std::string(_("by ")) + level->get_author(),
191 Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
195 context.draw_text(white_text,
196 _("Level Vertically Flipped!"),
197 Vector(screen->w/2, 310), CENTER_ALLIGN, LAYER_FOREGROUND1);
199 if(best_level_statistics != NULL)
200 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
202 context.do_drawing();
205 wait_for_event(event,1000,3000,true);
210 GameSession::start_timers()
212 time_left.start(level->time_left*1000);
218 GameSession::on_escape_press()
220 if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
221 return; // don't let the player open the menu, when he is dying
226 if(st_gl_mode == ST_GL_TEST)
228 exit_status = ES_LEVEL_ABORT;
230 else if (!Menu::current())
232 /* Tell Tux that the keys are all down, otherwise
233 it could have nasty bugs, like going allways to the right
234 or whatever that key does */
235 Player& tux = *(currentsector->player);
236 tux.key_event((SDLKey)keymap.jump, UP);
237 tux.key_event((SDLKey)keymap.duck, UP);
238 tux.key_event((SDLKey)keymap.left, UP);
239 tux.key_event((SDLKey)keymap.right, UP);
240 tux.key_event((SDLKey)keymap.fire, UP);
242 Menu::set_current(game_menu);
243 Ticks::pause_start();
248 GameSession::process_events()
250 if (end_sequence != NO_ENDSEQUENCE)
252 Player& tux = *currentsector->player;
256 tux.input.right = DOWN;
259 if (int(last_x_pos) == int(tux.base.x))
264 last_x_pos = tux.base.x;
267 while (SDL_PollEvent(&event))
269 /* Check for menu-events, if the menu is shown */
272 Menu::current()->event(event);
279 case SDL_QUIT: /* Quit event - quit: */
280 Termination::abort("Received window close", "");
283 case SDL_KEYDOWN: /* A keypress! */
285 SDLKey key = event.key.keysym.sym;
289 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
297 case SDL_JOYBUTTONDOWN:
298 if (event.jbutton.button == joystick_keymap.start_button)
306 if(!Menu::current() && !game_pause)
310 while (SDL_PollEvent(&event))
312 /* Check for menu-events, if the menu is shown */
315 Menu::current()->event(event);
321 Player& tux = *currentsector->player;
325 case SDL_QUIT: /* Quit event - quit: */
326 Termination::abort("Received window close", "");
329 case SDL_KEYDOWN: /* A keypress! */
331 SDLKey key = event.key.keysym.sym;
333 if(tux.key_event(key,DOWN))
338 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
346 case SDL_KEYUP: /* A keyrelease! */
348 SDLKey key = event.key.keysym.sym;
350 if(tux.key_event(key, UP))
359 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
360 tux.base.x, tux.base.y);
361 context->draw_text(white_text, buf,
362 Vector(0, screen->h - white_text->get_height()),
363 LEFT_ALLIGN, LAYER_FOREGROUND1);
364 context->do_drawing();
371 // "lifeup" cheat activates pause cause of the 'p'
372 // so work around to ignore it
373 if(compare_last(last_keys, "lifeu"))
384 Ticks::pause_start();
393 /* Check if chacrater is ASCII */
395 if((event.key.keysym.unicode & 0xFF80) == 0)
397 ch[0] = event.key.keysym.unicode & 0x7F;
400 last_keys.append(ch); // add to cheat keys
402 // Cheating words (the goal of this is really for debugging,
403 // but could be used for some cheating, nothing wrong with that)
404 if(compare_last(last_keys, "grow"))
409 if(compare_last(last_keys, "fire"))
412 tux.got_power = tux.FIRE_POWER;
415 if(compare_last(last_keys, "ice"))
418 tux.got_power = tux.ICE_POWER;
421 if(compare_last(last_keys, "lifeup"))
423 player_status.lives++;
426 if(compare_last(last_keys, "lifedown"))
428 player_status.lives--;
431 if(compare_last(last_keys, "invincible"))
432 { // be invincle for the rest of the level
433 tux.invincible_timer.start(time_left.get_left());
436 if(compare_last(last_keys, "shrink"))
438 tux.kill(tux.SHRINK);
441 if(compare_last(last_keys, "kill"))
442 { // kill Tux, but without losing a life
443 player_status.lives++;
447 if(compare_last(last_keys, "hover"))
448 { // toggle hover ability on/off
449 tux.enable_hover = !tux.enable_hover;
452 if(compare_last(last_keys, "gotoend"))
453 { // goes to the end of the level
454 tux.base.x = (currentsector->solids->get_width()*32) - (screen->w*2);
456 currentsector->camera->reset(Vector(tux.base.x, tux.base.y));
461 case SDL_JOYAXISMOTION:
462 if (event.jaxis.axis == joystick_keymap.x_axis)
464 if (event.jaxis.value < -joystick_keymap.dead_zone)
466 tux.input.left = DOWN;
467 tux.input.right = UP;
469 else if (event.jaxis.value > joystick_keymap.dead_zone)
472 tux.input.right = DOWN;
476 tux.input.left = DOWN;
477 tux.input.right = DOWN;
480 else if (event.jaxis.axis == joystick_keymap.y_axis)
482 if (event.jaxis.value > joystick_keymap.dead_zone)
483 tux.input.down = DOWN;
484 else if (event.jaxis.value < -joystick_keymap.dead_zone)
491 case SDL_JOYHATMOTION:
492 if(event.jhat.value & SDL_HAT_UP) {
495 } else if(event.jhat.value & SDL_HAT_DOWN) {
497 tux.input.down = DOWN;
498 } else if(event.jhat.value & SDL_HAT_LEFT) {
499 tux.input.left = DOWN;
500 tux.input.right = UP;
501 } else if(event.jhat.value & SDL_HAT_RIGHT) {
503 tux.input.right = DOWN;
504 } else if(event.jhat.value == SDL_HAT_CENTERED) {
506 tux.input.right = UP;
512 case SDL_JOYBUTTONDOWN:
513 if (event.jbutton.button == joystick_keymap.a_button)
515 else if (event.jbutton.button == joystick_keymap.b_button)
516 tux.input.fire = DOWN;
517 else if (event.jbutton.button == joystick_keymap.start_button)
520 case SDL_JOYBUTTONUP:
521 if (event.jbutton.button == joystick_keymap.a_button)
523 else if (event.jbutton.button == joystick_keymap.b_button)
536 GameSession::check_end_conditions()
538 Player* tux = currentsector->player;
541 Tile* endtile = collision_goal(tux->base);
543 if(end_sequence && !endsequence_timer.check())
545 exit_status = ES_LEVEL_FINISHED;
548 else if(end_sequence == ENDSEQUENCE_RUNNING && endtile && endtile->data >= 1)
550 end_sequence = ENDSEQUENCE_WAITING;
552 else if(!end_sequence && endtile && endtile->data == 0)
554 end_sequence = ENDSEQUENCE_RUNNING;
555 endsequence_timer.start(7000); // 5 seconds until we finish the map
557 SoundManager::get()->play_music(level_end_song, 0);
558 tux->invincible_timer.start(7000); //FIXME: Implement a winning timer for the end sequence (with special winning animation etc.)
560 // add left time to stats
561 global_stats.set_points(TIME_NEEDED_STAT, time_left.get_gone() / 1000);
563 random_timer.start(200); // start 1st firework
565 else if (!end_sequence && tux->is_dead())
567 player_status.bonus = PlayerStatus::NO_BONUS;
569 if (player_status.lives < 0)
571 exit_status = ES_GAME_OVER;
574 { // Still has lives, so reset Tux to the levelstart
583 GameSession::action(double frame_ratio)
585 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
587 // Update Tux and the World
588 currentsector->action(frame_ratio);
591 // respawning in new sector?
592 if(newsector != "" && newspawnpoint != "") {
593 Sector* sector = level->get_sector(newsector);
594 currentsector = sector;
595 currentsector->activate(newspawnpoint);
596 currentsector->play_music(LEVEL_MUSIC);
597 newsector = newspawnpoint = "";
600 // on end sequence make a few fireworks
601 if(end_sequence == ENDSEQUENCE_RUNNING && !random_timer.check() &&
602 currentsector->end_sequence_animation() == FIREWORKS_ENDSEQ_ANIM)
604 Vector epicenter = currentsector->camera->get_translation();
605 epicenter.x += screen->w * ((float)rand() / RAND_MAX);
606 epicenter.y += (screen->h/2) * ((float)rand() / RAND_MAX);
608 int red = rand() % 255; // calculate firework color
609 int green = rand() % red;
610 currentsector->add_particles(epicenter, Vector(1.4,1.4), Vector(0,0),
611 45, Color(red,green,0), 3, 1300);
613 SoundManager::get()->play_sound(IDToSound(SND_FIREWORKS));
614 random_timer.start(rand() % 400 + 600); // next firework
621 currentsector->draw(*context);
622 drawstatus(*context);
626 int x = screen->h / 20;
627 for(int i = 0; i < x; ++i)
629 context->draw_filled_rect(
630 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
631 -((pause_menu_frame * i)%screen->w)
632 ,(i*20+pause_menu_frame)%screen->h),
633 Vector(screen->w,10),
634 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
636 context->draw_filled_rect(
637 Vector(0,0), Vector(screen->w, screen->h),
638 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
639 context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
640 Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
644 sprintf(str1, _("Playing: "));
645 sprintf(str2, level->name.c_str());
647 context->draw_text(blue_text, str1,
648 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
649 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
650 context->draw_text(white_text, str2,
651 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
652 LEFT_ALLIGN, LAYER_FOREGROUND1+2);
657 Menu::current()->draw(*context);
658 mouse_cursor->draw(*context);
661 context->do_drawing();
665 GameSession::process_menu()
667 Menu* menu = Menu::current();
672 if(menu == game_menu)
674 switch (game_menu->check())
679 case MNID_ABORTLEVEL:
681 exit_status = ES_LEVEL_ABORT;
685 else if(menu == options_menu)
687 process_options_menu();
689 else if(menu == load_game_menu )
691 process_load_game_menu();
696 GameSession::ExitStatus
699 Menu::set_current(0);
706 // Eat unneeded events
708 while (SDL_PollEvent(&event)) {}
712 while (exit_status == ES_NONE)
714 /* Calculate the movement-factor */
715 double frame_ratio = frame_rate.get();
717 if(!frame_timer.check())
719 frame_timer.start(25);
720 ++global_frame_counter;
724 currentsector->player->input.old_fire
725 = currentsector->player->input.fire;
730 // Update the world state and all objects in the world
731 // Do that with a constante time-delta so that the game will run
732 // determistic and not different on different machines
733 if(!game_pause && !Menu::current())
736 check_end_conditions();
737 if (end_sequence == ENDSEQUENCE_RUNNING)
738 action(frame_ratio/2);
739 else if(end_sequence == NO_ENDSEQUENCE)
750 /* Time stops in pause mode */
751 if(game_pause || Menu::current())
759 if (!time_left.check() && currentsector->player->dying == DYING_NOT
761 currentsector->player->kill(Player::KILL);
764 if(currentsector->player->invincible_timer.check() && !end_sequence)
766 currentsector->play_music(HERRING_MUSIC);
768 /* are we low on time ? */
769 else if (time_left.get_left() < TIME_WARNING && !end_sequence)
771 currentsector->play_music(HURRYUP_MUSIC);
773 /* or just normal music? */
774 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
776 currentsector->play_music(LEVEL_MUSIC);
779 /* Calculate frames per second */
783 fps_fps = (1000.0 / (float)fps_timer.get_gone()) * (float)fps_cnt;
785 if(!fps_timer.check())
787 fps_timer.start(1000);
797 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
800 newspawnpoint = spawnpoint;
803 /* Bounce a brick: */
804 void bumpbrick(float x, float y)
806 Sector::current()->add_bouncy_brick(Vector(((int)(x + 1) / 32) * 32,
807 (int)(y / 32) * 32));
809 SoundManager::get()->play_sound(IDToSound(SND_BRICK), Vector(x, y), Sector::current()->player->get_pos());
814 GameSession::drawstatus(DrawingContext& context)
818 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
819 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
820 context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
822 if(st_gl_mode == ST_GL_TEST)
824 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
825 LEFT_ALLIGN, LAYER_FOREGROUND1);
828 if(!time_left.check()) {
829 context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
830 CENTER_ALLIGN, LAYER_FOREGROUND1);
831 } else if (time_left.get_left() > TIME_WARNING || (global_frame_counter % 10) < 5) {
832 sprintf(str, " %d", time_left.get_left() / 1000 );
833 context.draw_text(white_text, _("TIME"),
834 Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
835 context.draw_text(gold_text, str,
836 Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
839 sprintf(str, " %d", player_status.distros);
840 context.draw_text(white_text, _("COINS"),
841 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
842 LEFT_ALLIGN, LAYER_FOREGROUND1);
843 context.draw_text(gold_text, str,
844 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
846 if (player_status.lives >= 5)
848 sprintf(str, "%dx", player_status.lives);
849 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
850 context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
851 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
856 for(int i= 0; i < player_status.lives; ++i)
857 context.draw_surface(tux_life,
858 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
862 context.draw_text(white_text, _("LIVES"),
863 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
864 LEFT_ALLIGN, LAYER_FOREGROUND1);
868 sprintf(str, "%2.1f", fps_fps);
869 context.draw_text(white_text, "FPS",
870 Vector(screen->w - white_text->get_text_width("FPS "), 40),
871 LEFT_ALLIGN, LAYER_FOREGROUND1);
872 context.draw_text(gold_text, str,
873 Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
878 GameSession::drawresultscreen(void)
882 DrawingContext context;
883 currentsector->background->draw(context);
885 context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
886 CENTER_ALLIGN, LAYER_FOREGROUND1);
888 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
889 context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
891 sprintf(str, _("COINS: %d"), player_status.distros);
892 context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
894 context.do_drawing();
897 wait_for_event(event,2000,5000,true);
900 std::string slotinfo(int slot)
903 std::string slotfile;
905 std::stringstream stream;
907 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
909 lisp_object_t* savegame = lisp_read_from_file(slotfile.c_str());
912 LispReader reader(lisp_cdr(savegame));
913 reader.read_string("title", title);
917 if (access(slotfile.c_str(), F_OK) == 0)
920 tmp = "Slot " + stream.str() + " - " + title;
922 tmp = "Slot " + stream.str() + " - Savegame";
925 tmp = std::string(_("Slot")) + " " + stream.str() + " - " + std::string(_("Free"));
930 bool process_load_game_menu()
932 int slot = load_game_menu->check();
934 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
936 std::stringstream stream;
938 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
940 if (access(slotfile.c_str(), F_OK) != 0)
945 // shrink_fade(Point((screen->w/2),(screen->h/2)), 1000);
948 DrawingContext context;
949 context.draw_text(white_text, "Loading...",
950 Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
951 context.do_drawing();
953 WorldMapNS::WorldMap worldmap;
955 // Load the game or at least set the savegame_file variable
956 worldmap.loadgame(slotfile);
960 Menu::set_current(main_menu);