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 currentsector = level->get_sector("main");
134 Termination::abort("Level has no main sector.", "");
135 currentsector->activate("main");
137 // Set Tux to the nearest reset point
140 tux_pos = currentsector->get_best_spawn_point(tux_pos);
141 currentsector->player->base.x = tux_pos.x;
142 currentsector->player->base.y = tux_pos.y;
144 // has to reset camera on swapping
145 currentsector->camera->reset(Vector(currentsector->player->base.x,
146 currentsector->player->base.y));
149 if (st_gl_mode != ST_GL_DEMO_GAME)
151 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
155 global_stats.reset();
157 time_left.init(true);
159 currentsector->play_music(LEVEL_MUSIC);
162 GameSession::~GameSession()
169 GameSession::levelintro(void)
171 SoundManager::get()->halt_music();
175 DrawingContext context;
176 currentsector->background->draw(context);
178 context.draw_text_center(gold_text, level->get_name(), Vector(0, 220),
181 sprintf(str, "TUX x %d", player_status.lives);
182 context.draw_text_center(white_text, str, Vector(0, 240),
185 if(level->get_author().size())
186 context.draw_text_center(white_small_text,
187 std::string(_("by ")) + level->get_author(),
188 Vector(0, 360), LAYER_FOREGROUND1);
192 context.draw_text_center(white_text,
193 _("Level Vertically Flipped!"),
194 Vector(0, 310), LAYER_FOREGROUND1);
196 if(best_level_statistics != NULL)
197 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
199 context.do_drawing();
202 wait_for_event(event,1000,3000,true);
207 GameSession::start_timers()
209 time_left.start(level->time_left*1000);
215 GameSession::on_escape_press()
217 if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
218 return; // don't let the player open the menu, when he is dying
223 if(st_gl_mode == ST_GL_TEST)
225 exit_status = ES_LEVEL_ABORT;
227 else if (!Menu::current())
229 /* Tell Tux that the keys are all down, otherwise
230 it could have nasty bugs, like going allways to the right
231 or whatever that key does */
232 Player& tux = *(currentsector->player);
233 tux.key_event((SDLKey)keymap.jump, UP);
234 tux.key_event((SDLKey)keymap.duck, UP);
235 tux.key_event((SDLKey)keymap.left, UP);
236 tux.key_event((SDLKey)keymap.right, UP);
237 tux.key_event((SDLKey)keymap.fire, UP);
239 Menu::set_current(game_menu);
240 Ticks::pause_start();
245 GameSession::process_events()
247 if (end_sequence != NO_ENDSEQUENCE)
249 Player& tux = *currentsector->player;
253 tux.input.right = DOWN;
256 if (int(last_x_pos) == int(tux.base.x))
261 last_x_pos = tux.base.x;
264 while (SDL_PollEvent(&event))
266 /* Check for menu-events, if the menu is shown */
269 Menu::current()->event(event);
276 case SDL_QUIT: /* Quit event - quit: */
277 Termination::abort("Received window close", "");
280 case SDL_KEYDOWN: /* A keypress! */
282 SDLKey key = event.key.keysym.sym;
286 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
294 case SDL_JOYBUTTONDOWN:
295 if (event.jbutton.button == joystick_keymap.start_button)
303 if(!Menu::current() && !game_pause)
307 while (SDL_PollEvent(&event))
309 /* Check for menu-events, if the menu is shown */
312 Menu::current()->event(event);
318 Player& tux = *currentsector->player;
322 case SDL_QUIT: /* Quit event - quit: */
323 Termination::abort("Received window close", "");
326 case SDL_KEYDOWN: /* A keypress! */
328 SDLKey key = event.key.keysym.sym;
330 if(tux.key_event(key,DOWN))
335 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
343 case SDL_KEYUP: /* A keyrelease! */
345 SDLKey key = event.key.keysym.sym;
347 if(tux.key_event(key, UP))
356 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
357 tux.base.x, tux.base.y);
358 context->draw_text(white_text, buf,
359 Vector(0, screen->h - white_text->get_height()),
361 context->do_drawing();
376 Ticks::pause_start();
385 /* Check if chacrater is ASCII */
387 if((event.key.keysym.unicode & 0xFF80) == 0)
389 ch[0] = event.key.keysym.unicode & 0x7F;
392 last_keys.append(ch); // add to cheat keys
394 // Cheating words (the goal of this is really for debugging,
395 // but could be used for some cheating, nothing wrong with that)
396 if(compare_last(last_keys, "grow"))
401 if(compare_last(last_keys, "fire"))
404 tux.got_power = tux.FIRE_POWER;
407 if(compare_last(last_keys, "ice"))
410 tux.got_power = tux.ICE_POWER;
413 if(compare_last(last_keys, "lifeup"))
415 player_status.lives++;
417 // "lifeup" activates pause cause of the 'p'
418 // so work around to ignore it
427 Ticks::pause_start();
430 if(compare_last(last_keys, "lifedown"))
432 player_status.lives--;
435 if(compare_last(last_keys, "invincible"))
436 { // be invincle for the rest of the level
437 tux.invincible_timer.start(time_left.get_left());
440 if(compare_last(last_keys, "shrink"))
442 tux.kill(tux.SHRINK);
445 if(compare_last(last_keys, "kill"))
452 case SDL_JOYAXISMOTION:
453 if (event.jaxis.axis == joystick_keymap.x_axis)
455 if (event.jaxis.value < -joystick_keymap.dead_zone)
457 tux.input.left = DOWN;
458 tux.input.right = UP;
460 else if (event.jaxis.value > joystick_keymap.dead_zone)
463 tux.input.right = DOWN;
467 tux.input.left = DOWN;
468 tux.input.right = DOWN;
471 else if (event.jaxis.axis == joystick_keymap.y_axis)
473 if (event.jaxis.value > joystick_keymap.dead_zone)
474 tux.input.down = DOWN;
475 else if (event.jaxis.value < -joystick_keymap.dead_zone)
482 case SDL_JOYHATMOTION:
483 if(event.jhat.value & SDL_HAT_UP) {
486 } else if(event.jhat.value & SDL_HAT_DOWN) {
488 tux.input.down = DOWN;
489 } else if(event.jhat.value & SDL_HAT_LEFT) {
490 tux.input.left = DOWN;
491 tux.input.right = UP;
492 } else if(event.jhat.value & SDL_HAT_RIGHT) {
494 tux.input.right = DOWN;
495 } else if(event.jhat.value == SDL_HAT_CENTERED) {
497 tux.input.right = UP;
503 case SDL_JOYBUTTONDOWN:
504 if (event.jbutton.button == joystick_keymap.a_button)
506 else if (event.jbutton.button == joystick_keymap.b_button)
507 tux.input.fire = DOWN;
508 else if (event.jbutton.button == joystick_keymap.start_button)
511 case SDL_JOYBUTTONUP:
512 if (event.jbutton.button == joystick_keymap.a_button)
514 else if (event.jbutton.button == joystick_keymap.b_button)
527 GameSession::check_end_conditions()
529 Player* tux = currentsector->player;
532 Tile* endtile = collision_goal(tux->base);
534 if(end_sequence && !endsequence_timer.check())
536 exit_status = ES_LEVEL_FINISHED;
539 else if(end_sequence == ENDSEQUENCE_RUNNING && endtile && endtile->data >= 1)
541 end_sequence = ENDSEQUENCE_WAITING;
543 else if(!end_sequence && endtile && endtile->data == 0)
545 end_sequence = ENDSEQUENCE_RUNNING;
546 random_timer.start(200); // start 1st firework
548 SoundManager::get()->play_music(level_end_song, 0);
549 endsequence_timer.start(7000); // 5 seconds until we finish the map
550 tux->invincible_timer.start(7000); //FIXME: Implement a winning timer for the end sequence (with special winning animation etc.)
552 // add left time to stats
553 global_stats.set_points(TIME_NEEDED_STAT, time_left.get_gone() / 1000);
555 else if (!end_sequence && tux->is_dead())
557 player_status.bonus = PlayerStatus::NO_BONUS;
559 if (player_status.lives < 0)
561 exit_status = ES_GAME_OVER;
564 { // Still has lives, so reset Tux to the levelstart
573 GameSession::action(double frame_ratio)
575 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
577 // Update Tux and the World
578 currentsector->action(frame_ratio);
581 // respawning in new sector?
582 if(newsector != "" && newspawnpoint != "") {
583 Sector* sector = level->get_sector(newsector);
584 currentsector = sector;
585 currentsector->activate(newspawnpoint);
586 currentsector->play_music(LEVEL_MUSIC);
587 newsector = newspawnpoint = "";
590 // on end sequence make a few fireworks
591 if(end_sequence == ENDSEQUENCE_RUNNING && !random_timer.check())
593 Vector epicenter = currentsector->camera->get_translation();
594 epicenter.x += screen->w * ((float)rand() / RAND_MAX);
595 epicenter.y += (screen->h/2) * ((float)rand() / RAND_MAX);
597 int red = rand() % 255; // calculate firework color
598 int green = rand() % red;
599 currentsector->add_particles(epicenter, Vector(1.4,1.4), Vector(0,0),
600 45, Color(red,green,0), 3, 1300);
602 SoundManager::get()->play_sound(IDToSound(SND_FIREWORKS));
603 random_timer.start(rand() % 400 + 600); // next firework
610 currentsector->draw(*context);
611 drawstatus(*context);
615 int x = screen->h / 20;
616 for(int i = 0; i < x; ++i)
618 context->draw_filled_rect(
619 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
620 -((pause_menu_frame * i)%screen->w)
621 ,(i*20+pause_menu_frame)%screen->h),
622 Vector(screen->w,10),
623 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
625 context->draw_filled_rect(
626 Vector(0,0), Vector(screen->w, screen->h),
627 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
628 context->draw_text_center(blue_text, _("PAUSE - Press 'P' To Play"),
629 Vector(0, 230), LAYER_FOREGROUND1+2);
633 sprintf(str1, _("Playing: "));
634 sprintf(str2, level->name.c_str());
636 context->draw_text(blue_text, str1,
637 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
638 LAYER_FOREGROUND1+2);
639 context->draw_text(white_text, str2,
640 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
641 LAYER_FOREGROUND1+2);
646 Menu::current()->draw(*context);
647 mouse_cursor->draw(*context);
650 context->do_drawing();
654 GameSession::process_menu()
656 Menu* menu = Menu::current();
661 if(menu == game_menu)
663 switch (game_menu->check())
668 case MNID_ABORTLEVEL:
670 exit_status = ES_LEVEL_ABORT;
674 else if(menu == options_menu)
676 process_options_menu();
678 else if(menu == load_game_menu )
680 process_load_game_menu();
685 GameSession::ExitStatus
688 Menu::set_current(0);
695 // Eat unneeded events
697 while (SDL_PollEvent(&event)) {}
701 while (exit_status == ES_NONE)
703 /* Calculate the movement-factor */
704 double frame_ratio = frame_rate.get();
706 if(!frame_timer.check())
708 frame_timer.start(25);
709 ++global_frame_counter;
713 currentsector->player->input.old_fire
714 = currentsector->player->input.fire;
719 // Update the world state and all objects in the world
720 // Do that with a constante time-delta so that the game will run
721 // determistic and not different on different machines
722 if(!game_pause && !Menu::current())
725 check_end_conditions();
726 if (end_sequence == ENDSEQUENCE_RUNNING)
727 action(frame_ratio/2);
728 else if(end_sequence == NO_ENDSEQUENCE)
739 /* Time stops in pause mode */
740 if(game_pause || Menu::current())
748 if (!time_left.check() && currentsector->player->dying == DYING_NOT
750 currentsector->player->kill(Player::KILL);
753 if(currentsector->player->invincible_timer.check() && !end_sequence)
755 currentsector->play_music(HERRING_MUSIC);
757 /* are we low on time ? */
758 else if (time_left.get_left() < TIME_WARNING && !end_sequence)
760 currentsector->play_music(HURRYUP_MUSIC);
762 /* or just normal music? */
763 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
765 currentsector->play_music(LEVEL_MUSIC);
768 /* Calculate frames per second */
772 fps_fps = (1000.0 / (float)fps_timer.get_gone()) * (float)fps_cnt;
774 if(!fps_timer.check())
776 fps_timer.start(1000);
786 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
789 newspawnpoint = spawnpoint;
792 /* Bounce a brick: */
793 void bumpbrick(float x, float y)
795 Sector::current()->add_bouncy_brick(Vector(((int)(x + 1) / 32) * 32,
796 (int)(y / 32) * 32));
798 SoundManager::get()->play_sound(IDToSound(SND_BRICK), Vector(x, y), Sector::current()->player->get_pos());
803 GameSession::drawstatus(DrawingContext& context)
807 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
808 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LAYER_FOREGROUND1);
809 context.draw_text(gold_text, str, Vector(96, 0), LAYER_FOREGROUND1);
811 if(st_gl_mode == ST_GL_TEST)
813 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
817 if(!time_left.check()) {
818 context.draw_text_center(white_text, _("TIME's UP"), Vector(0, 0),
820 } else if (time_left.get_left() > TIME_WARNING || (global_frame_counter % 10) < 5) {
821 sprintf(str, " %d", time_left.get_left() / 1000 );
822 context.draw_text_center(white_text, _("TIME"),
823 Vector(0, 0), LAYER_FOREGROUND1);
824 context.draw_text_center(gold_text, str,
825 Vector(4*16, 0), LAYER_FOREGROUND1);
828 sprintf(str, " %d", player_status.distros);
829 context.draw_text(white_text, _("COINS"),
830 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
832 context.draw_text(gold_text, str,
833 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LAYER_FOREGROUND1);
835 if (player_status.lives >= 5)
837 sprintf(str, "%dx", player_status.lives);
838 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
839 context.draw_text(gold_text, str, Vector(x, 20), LAYER_FOREGROUND1);
840 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
845 for(int i= 0; i < player_status.lives; ++i)
846 context.draw_surface(tux_life,
847 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
851 context.draw_text(white_text, _("LIVES"),
852 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
857 sprintf(str, "%2.1f", fps_fps);
858 context.draw_text(white_text, "FPS",
859 Vector(screen->w - white_text->get_text_width("FPS "), 40),
861 context.draw_text(gold_text, str,
862 Vector(screen->w-4*16, 40), LAYER_FOREGROUND1);
867 GameSession::drawresultscreen(void)
871 DrawingContext context;
872 currentsector->background->draw(context);
874 context.draw_text_center(blue_text, _("Result:"), Vector(0, 200),
877 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
878 context.draw_text_center(gold_text, str, Vector(0, 224), LAYER_FOREGROUND1);
880 sprintf(str, _("COINS: %d"), player_status.distros);
881 context.draw_text_center(gold_text, str, Vector(0, 256), LAYER_FOREGROUND1);
883 context.do_drawing();
886 wait_for_event(event,2000,5000,true);
889 std::string slotinfo(int slot)
892 std::string slotfile;
894 std::stringstream stream;
896 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
898 lisp_object_t* savegame = lisp_read_from_file(slotfile.c_str());
901 LispReader reader(lisp_cdr(savegame));
902 reader.read_string("title", title);
906 if (access(slotfile.c_str(), F_OK) == 0)
909 tmp = "Slot " + stream.str() + " - " + title;
911 tmp = "Slot " + stream.str() + " - Savegame";
914 tmp = std::string(_("Slot")) + " " + stream.str() + " - " + std::string(_("Free"));
919 bool process_load_game_menu()
921 int slot = load_game_menu->check();
923 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
925 std::stringstream stream;
927 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
929 if (access(slotfile.c_str(), F_OK) != 0)
934 // shrink_fade(Point((screen->w/2),(screen->h/2)), 1000);
937 DrawingContext context;
938 context.draw_text_center(white_text, "Loading...",
939 Vector(0, screen->h/2), LAYER_FOREGROUND1);
940 context.do_drawing();
942 WorldMapNS::WorldMap worldmap;
944 // Load the game or at least set the savegame_file variable
945 worldmap.loadgame(slotfile);
949 Menu::set_current(main_menu);