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_)
82 : level(0), currentsector(0), st_gl_mode(mode),
83 end_sequence(NO_ENDSEQUENCE), levelname(levelname_), flip_level(flip_level_)
87 global_frame_counter = 0;
92 frame_timer.init(true);
93 random_timer.init(true);
94 frame_rate.set_fps(100);
96 context = new DrawingContext();
105 GameSession::restart_level()
108 exit_status = ES_NONE;
109 end_sequence = NO_ENDSEQUENCE;
111 fps_timer.init(true);
112 frame_timer.init(true);
113 random_timer.init(true);
117 Vector tux_pos = Vector(-1,-1);
119 { // Tux has lost a life, so we try to respawn him at the nearest reset point
120 tux_pos = currentsector->player->base;
127 level->load(levelname);
129 level->do_vertical_flip();
131 currentsector = level->get_sector("main");
133 Termination::abort("Level has no main sector.", "");
134 currentsector->activate("main");
136 // Set Tux to the nearest reset point
139 tux_pos = currentsector->get_best_spawn_point(tux_pos);
140 currentsector->player->base.x = tux_pos.x;
141 currentsector->player->base.y = tux_pos.y;
143 // has to reset camera on swapping
144 currentsector->camera->reset(Vector(currentsector->player->base.x,
145 currentsector->player->base.y));
148 if (st_gl_mode != ST_GL_DEMO_GAME)
150 if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
154 global_stats.reset();
156 time_left.init(true);
158 currentsector->play_music(LEVEL_MUSIC);
161 GameSession::~GameSession()
168 GameSession::levelintro(void)
170 SoundManager::get()->halt_music();
174 DrawingContext context;
175 currentsector->background->draw(context);
177 context.draw_text_center(gold_text, level->get_name(), Vector(0, 220),
180 sprintf(str, "TUX x %d", player_status.lives);
181 context.draw_text_center(white_text, str, Vector(0, 240),
184 if(level->get_author().size())
185 context.draw_text_center(white_small_text,
186 std::string(_("by ")) + level->get_author(),
187 Vector(0, 400), LAYER_FOREGROUND1);
191 context.draw_text_center(white_text,
192 _("Level Vertically Flipped!"),
193 Vector(0, 310), LAYER_FOREGROUND1);
195 context.do_drawing();
198 wait_for_event(event,1000,3000,true);
203 GameSession::start_timers()
205 time_left.start(level->time_left*1000);
211 GameSession::on_escape_press()
213 if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
214 return; // don't let the player open the menu, when he is dying
219 if(st_gl_mode == ST_GL_TEST)
221 exit_status = ES_LEVEL_ABORT;
223 else if (!Menu::current())
225 /* Tell Tux that the keys are all down, otherwise
226 it could have nasty bugs, like going allways to the right
227 or whatever that key does */
228 Player& tux = *(currentsector->player);
229 tux.key_event((SDLKey)keymap.jump, UP);
230 tux.key_event((SDLKey)keymap.duck, UP);
231 tux.key_event((SDLKey)keymap.left, UP);
232 tux.key_event((SDLKey)keymap.right, UP);
233 tux.key_event((SDLKey)keymap.fire, UP);
235 Menu::set_current(game_menu);
236 Ticks::pause_start();
241 GameSession::process_events()
243 if (end_sequence != NO_ENDSEQUENCE)
245 Player& tux = *currentsector->player;
249 tux.input.right = DOWN;
252 if (int(last_x_pos) == int(tux.base.x))
257 last_x_pos = tux.base.x;
260 while (SDL_PollEvent(&event))
262 /* Check for menu-events, if the menu is shown */
265 Menu::current()->event(event);
272 case SDL_QUIT: /* Quit event - quit: */
273 Termination::abort("Received window close", "");
276 case SDL_KEYDOWN: /* A keypress! */
278 SDLKey key = event.key.keysym.sym;
282 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
290 case SDL_JOYBUTTONDOWN:
291 if (event.jbutton.button == joystick_keymap.start_button)
299 if(!Menu::current() && !game_pause)
303 while (SDL_PollEvent(&event))
305 /* Check for menu-events, if the menu is shown */
308 Menu::current()->event(event);
314 Player& tux = *currentsector->player;
318 case SDL_QUIT: /* Quit event - quit: */
319 Termination::abort("Received window close", "");
322 case SDL_KEYDOWN: /* A keypress! */
324 SDLKey key = event.key.keysym.sym;
326 if(tux.key_event(key,DOWN))
331 case SDLK_ESCAPE: /* Escape: Open/Close the menu: */
339 case SDL_KEYUP: /* A keyrelease! */
341 SDLKey key = event.key.keysym.sym;
343 if(tux.key_event(key, UP))
352 snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
353 tux.base.x, tux.base.y);
354 context->draw_text(white_text, buf,
355 Vector(0, screen->h - white_text->get_height()),
357 context->do_drawing();
372 Ticks::pause_start();
381 /* Check if chacrater is ASCII */
383 if((event.key.keysym.unicode & 0xFF80) == 0)
385 ch[0] = event.key.keysym.unicode & 0x7F;
388 last_keys.append(ch); // add to cheat keys
390 // Cheating words (the goal of this is really for debugging,
391 // but could be used for some cheating, nothing wrong with that)
392 if(compare_last(last_keys, "grow"))
397 if(compare_last(last_keys, "fire"))
400 tux.got_power = tux.FIRE_POWER;
403 if(compare_last(last_keys, "ice"))
406 tux.got_power = tux.ICE_POWER;
409 if(compare_last(last_keys, "lifeup"))
411 player_status.lives++;
413 // "lifeup" activates pause cause of the 'p'
414 // so work around to ignore it
423 Ticks::pause_start();
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"))
448 case SDL_JOYAXISMOTION:
449 if (event.jaxis.axis == joystick_keymap.x_axis)
451 if (event.jaxis.value < -joystick_keymap.dead_zone)
453 tux.input.left = DOWN;
454 tux.input.right = UP;
456 else if (event.jaxis.value > joystick_keymap.dead_zone)
459 tux.input.right = DOWN;
463 tux.input.left = DOWN;
464 tux.input.right = DOWN;
467 else if (event.jaxis.axis == joystick_keymap.y_axis)
469 if (event.jaxis.value > joystick_keymap.dead_zone)
470 tux.input.down = DOWN;
471 else if (event.jaxis.value < -joystick_keymap.dead_zone)
478 case SDL_JOYHATMOTION:
479 if(event.jhat.value & SDL_HAT_UP) {
482 } else if(event.jhat.value & SDL_HAT_DOWN) {
484 tux.input.down = DOWN;
485 } else if(event.jhat.value & SDL_HAT_LEFT) {
486 tux.input.left = DOWN;
487 tux.input.right = UP;
488 } else if(event.jhat.value & SDL_HAT_RIGHT) {
490 tux.input.right = DOWN;
491 } else if(event.jhat.value == SDL_HAT_CENTERED) {
493 tux.input.right = UP;
499 case SDL_JOYBUTTONDOWN:
500 if (event.jbutton.button == joystick_keymap.a_button)
502 else if (event.jbutton.button == joystick_keymap.b_button)
503 tux.input.fire = DOWN;
504 else if (event.jbutton.button == joystick_keymap.start_button)
507 case SDL_JOYBUTTONUP:
508 if (event.jbutton.button == joystick_keymap.a_button)
510 else if (event.jbutton.button == joystick_keymap.b_button)
523 GameSession::check_end_conditions()
525 Player* tux = currentsector->player;
528 Tile* endtile = collision_goal(tux->base);
530 if(end_sequence && !endsequence_timer.check())
532 exit_status = ES_LEVEL_FINISHED;
535 else if(end_sequence == ENDSEQUENCE_RUNNING && endtile && endtile->data >= 1)
537 end_sequence = ENDSEQUENCE_WAITING;
539 else if(!end_sequence && endtile && endtile->data == 0)
541 end_sequence = ENDSEQUENCE_RUNNING;
542 random_timer.start(200); // start 1st firework
544 SoundManager::get()->play_music(level_end_song, 0);
545 endsequence_timer.start(7000); // 5 seconds until we finish the map
546 tux->invincible_timer.start(7000); //FIXME: Implement a winning timer for the end sequence (with special winning animation etc.)
548 // add left time to stats
549 global_stats.set_points(TIME_NEEDED_STAT, time_left.get_gone());
551 else if (!end_sequence && tux->is_dead())
553 player_status.bonus = PlayerStatus::NO_BONUS;
555 if (player_status.lives < 0)
557 exit_status = ES_GAME_OVER;
560 { // Still has lives, so reset Tux to the levelstart
569 GameSession::action(double frame_ratio)
571 if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
573 // Update Tux and the World
574 currentsector->action(frame_ratio);
577 // respawning in new sector?
578 if(newsector != "" && newspawnpoint != "") {
579 Sector* sector = level->get_sector(newsector);
580 currentsector = sector;
581 currentsector->activate(newspawnpoint);
582 currentsector->play_music(LEVEL_MUSIC);
583 newsector = newspawnpoint = "";
586 // on end sequence make a few fireworks
587 if(end_sequence == ENDSEQUENCE_RUNNING && !random_timer.check())
589 Vector epicenter = currentsector->camera->get_translation();
590 epicenter.x += screen->w * ((float)rand() / RAND_MAX);
591 epicenter.y += (screen->h/2) * ((float)rand() / RAND_MAX);
593 int red = rand() % 255; // calculate firework color
594 int green = rand() % red;
595 currentsector->add_particles(epicenter, Vector(1.4,1.4), Vector(0,0),
596 45, Color(red,green,0), 3, 1300);
598 SoundManager::get()->play_sound(IDToSound(SND_FIREWORKS));
599 random_timer.start(rand() % 400 + 600); // next firework
606 currentsector->draw(*context);
607 drawstatus(*context);
611 int x = screen->h / 20;
612 for(int i = 0; i < x; ++i)
614 context->draw_filled_rect(
615 Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
616 -((pause_menu_frame * i)%screen->w)
617 ,(i*20+pause_menu_frame)%screen->h),
618 Vector(screen->w,10),
619 Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
621 context->draw_filled_rect(
622 Vector(0,0), Vector(screen->w, screen->h),
623 Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
624 context->draw_text_center(blue_text, _("PAUSE - Press 'P' To Play"),
625 Vector(0, 230), LAYER_FOREGROUND1+2);
629 sprintf(str1, _("Playing: "));
630 sprintf(str2, level->name.c_str());
632 context->draw_text(blue_text, str1,
633 Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
634 LAYER_FOREGROUND1+2);
635 context->draw_text(white_text, str2,
636 Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
637 LAYER_FOREGROUND1+2);
642 Menu::current()->draw(*context);
643 mouse_cursor->draw(*context);
646 context->do_drawing();
650 GameSession::process_menu()
652 Menu* menu = Menu::current();
657 if(menu == game_menu)
659 switch (game_menu->check())
664 case MNID_ABORTLEVEL:
666 exit_status = ES_LEVEL_ABORT;
670 else if(menu == options_menu)
672 process_options_menu();
674 else if(menu == load_game_menu )
676 process_load_game_menu();
681 GameSession::ExitStatus
684 Menu::set_current(0);
691 // Eat unneeded events
693 while (SDL_PollEvent(&event)) {}
697 while (exit_status == ES_NONE)
699 /* Calculate the movement-factor */
700 double frame_ratio = frame_rate.get();
702 if(!frame_timer.check())
704 frame_timer.start(25);
705 ++global_frame_counter;
709 currentsector->player->input.old_fire
710 = currentsector->player->input.fire;
715 // Update the world state and all objects in the world
716 // Do that with a constante time-delta so that the game will run
717 // determistic and not different on different machines
718 if(!game_pause && !Menu::current())
721 check_end_conditions();
722 if (end_sequence == ENDSEQUENCE_RUNNING)
723 action(frame_ratio/2);
724 else if(end_sequence == NO_ENDSEQUENCE)
735 /* Time stops in pause mode */
736 if(game_pause || Menu::current())
744 if (!time_left.check() && currentsector->player->dying == DYING_NOT
746 currentsector->player->kill(Player::KILL);
749 if(currentsector->player->invincible_timer.check() && !end_sequence)
751 currentsector->play_music(HERRING_MUSIC);
753 /* are we low on time ? */
754 else if (time_left.get_left() < TIME_WARNING && !end_sequence)
756 currentsector->play_music(HURRYUP_MUSIC);
758 /* or just normal music? */
759 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
761 currentsector->play_music(LEVEL_MUSIC);
764 /* Calculate frames per second */
768 fps_fps = (1000.0 / (float)fps_timer.get_gone()) * (float)fps_cnt;
770 if(!fps_timer.check())
772 fps_timer.start(1000);
782 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
785 newspawnpoint = spawnpoint;
788 /* Bounce a brick: */
789 void bumpbrick(float x, float y)
791 Sector::current()->add_bouncy_brick(Vector(((int)(x + 1) / 32) * 32,
792 (int)(y / 32) * 32));
794 SoundManager::get()->play_sound(IDToSound(SND_BRICK), Vector(x, y), Sector::current()->player->get_pos());
799 GameSession::drawstatus(DrawingContext& context)
803 snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
804 context.draw_text(white_text, _("SCORE"), Vector(0, 0), LAYER_FOREGROUND1);
805 context.draw_text(gold_text, str, Vector(96, 0), LAYER_FOREGROUND1);
807 if(st_gl_mode == ST_GL_TEST)
809 context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
813 if(!time_left.check()) {
814 context.draw_text_center(white_text, _("TIME's UP"), Vector(0, 0),
816 } else if (time_left.get_left() > TIME_WARNING || (global_frame_counter % 10) < 5) {
817 sprintf(str, " %d", time_left.get_left() / 1000 );
818 context.draw_text_center(white_text, _("TIME"),
819 Vector(0, 0), LAYER_FOREGROUND1);
820 context.draw_text_center(gold_text, str,
821 Vector(4*16, 0), LAYER_FOREGROUND1);
824 sprintf(str, " %d", player_status.distros);
825 context.draw_text(white_text, _("COINS"),
826 Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width(" 99"), 0),
828 context.draw_text(gold_text, str,
829 Vector(screen->w - gold_text->get_text_width(" 99"), 0),LAYER_FOREGROUND1);
831 if (player_status.lives >= 5)
833 sprintf(str, "%dx", player_status.lives);
834 float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
835 context.draw_text(gold_text, str, Vector(x, 20), LAYER_FOREGROUND1);
836 context.draw_surface(tux_life, Vector(screen->w - 16, 20),
841 for(int i= 0; i < player_status.lives; ++i)
842 context.draw_surface(tux_life,
843 Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
847 context.draw_text(white_text, _("LIVES"),
848 Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width(" 99"), 20),
853 sprintf(str, "%2.1f", fps_fps);
854 context.draw_text(white_text, "FPS",
855 Vector(screen->w - white_text->get_text_width("FPS "), 40),
857 context.draw_text(gold_text, str,
858 Vector(screen->w-4*16, 40), LAYER_FOREGROUND1);
863 GameSession::drawresultscreen(void)
867 DrawingContext context;
868 currentsector->background->draw(context);
870 context.draw_text_center(blue_text, _("Result:"), Vector(0, 200),
873 sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
874 context.draw_text_center(gold_text, str, Vector(0, 224), LAYER_FOREGROUND1);
876 sprintf(str, _("COINS: %d"), player_status.distros);
877 context.draw_text_center(gold_text, str, Vector(0, 256), LAYER_FOREGROUND1);
879 context.do_drawing();
882 wait_for_event(event,2000,5000,true);
885 std::string slotinfo(int slot)
888 std::string slotfile;
890 std::stringstream stream;
892 slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
894 lisp_object_t* savegame = lisp_read_from_file(slotfile.c_str());
897 LispReader reader(lisp_cdr(savegame));
898 reader.read_string("title", title);
902 if (access(slotfile.c_str(), F_OK) == 0)
905 tmp = "Slot " + stream.str() + " - " + title;
907 tmp = "Slot " + stream.str() + " - Savegame";
910 tmp = std::string(_("Slot")) + " " + stream.str() + " - " + std::string(_("Free"));
915 bool process_load_game_menu()
917 int slot = load_game_menu->check();
919 if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
921 std::stringstream stream;
923 std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
925 if (access(slotfile.c_str(), F_OK) != 0)
930 // shrink_fade(Point((screen->w/2),(screen->h/2)), 1000);
933 DrawingContext context;
934 context.draw_text_center(white_text, "Loading...",
935 Vector(0, screen->h/2), LAYER_FOREGROUND1);
936 context.do_drawing();
938 WorldMapNS::WorldMap worldmap;
940 // Load the game or at least set the savegame_file variable
941 worldmap.loadgame(slotfile);
945 Menu::set_current(main_menu);