Separated EndSequence logic from GameSession. This will allow for nice hierarchy...
[supertux.git] / src / object / player.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <typeinfo>
22 #include <cmath>
23 #include <iostream>
24 #include <cassert>
25
26 #include "gettext.hpp"
27 #include "sprite/sprite_manager.hpp"
28 #include "audio/sound_manager.hpp"
29 #include "player.hpp"
30 #include "tile.hpp"
31 #include "sprite/sprite.hpp"
32 #include "sector.hpp"
33 #include "resources.hpp"
34 #include "statistics.hpp"
35 #include "game_session.hpp"
36 #include "object/tilemap.hpp"
37 #include "object/camera.hpp"
38 #include "object/particles.hpp"
39 #include "object/portable.hpp"
40 #include "object/bullet.hpp"
41 #include "trigger/trigger_base.hpp"
42 #include "control/joystickkeyboardcontroller.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "main.hpp"
45 #include "platform.hpp"
46 #include "badguy/badguy.hpp"
47 #include "player_status.hpp"
48 #include "log.hpp"
49 #include "falling_coin.hpp"
50 #include "random_generator.hpp"
51 #include "object/sprite_particle.hpp"
52
53 static const int TILES_FOR_BUTTJUMP = 3;
54 static const float SHOOTING_TIME = .150;
55 /// time before idle animation starts
56 static const float IDLE_TIME = 2.5;
57
58 static const float WALK_ACCELERATION_X = 300;
59 static const float RUN_ACCELERATION_X = 400;
60 static const float SKID_XM = 200;
61 static const float SKID_TIME = .3;
62 static const float MAX_WALK_XM = 230;
63 static const float MAX_RUN_XM = 320;
64 static const float WALK_SPEED = 100;
65
66 static const float KICK_TIME = .3;
67 static const float CHEER_TIME = 1;
68
69 static const float UNDUCK_HURT_TIME = 0.25; /**< if Tux cannot unduck for this long, he will get hurt */
70
71 // growing animation
72 Surface* growingtux_left[GROWING_FRAMES];
73 Surface* growingtux_right[GROWING_FRAMES];
74
75 Surface* tux_life = 0;
76
77 TuxBodyParts* small_tux = 0;
78 TuxBodyParts* big_tux = 0;
79 TuxBodyParts* fire_tux = 0;
80 TuxBodyParts* ice_tux = 0;
81
82 namespace{
83   bool no_water = true;
84 }
85 void
86 TuxBodyParts::set_action(std::string action, int loops)
87 {
88   if(head != NULL)
89     head->set_action(action, loops);
90   if(body != NULL)
91     body->set_action(action, loops);
92   if(arms != NULL)
93     arms->set_action(action, loops);
94   if(feet != NULL)
95     feet->set_action(action, loops);
96 }
97
98 void
99 TuxBodyParts::draw(DrawingContext& context, const Vector& pos, int layer)
100 {
101   if(head != NULL)
102     head->draw(context, pos, layer-1);
103   if(body != NULL)
104     body->draw(context, pos, layer-3);
105   if(arms != NULL)
106     arms->draw(context, pos, layer+10);
107   if(feet != NULL)
108     feet->draw(context, pos, layer-2);
109 }
110
111 Player::Player(PlayerStatus* _player_status, const std::string& name)
112   : player_status(_player_status), grabbed_object(NULL), ghost_mode(false)
113 {
114   this->name = name;
115   controller = main_controller;
116   smalltux_gameover = sprite_manager->create("images/creatures/tux_small/smalltux-gameover.sprite");
117   smalltux_star = sprite_manager->create("images/creatures/tux_small/smalltux-star.sprite");
118   bigtux_star = sprite_manager->create("images/creatures/tux_big/bigtux-star.sprite");
119   airarrow.reset(new Surface("images/engine/hud/airarrow.png"));
120
121   sound_manager->preload("sounds/bigjump.wav");
122   sound_manager->preload("sounds/jump.wav");
123   sound_manager->preload("sounds/hurt.wav");
124   sound_manager->preload("sounds/skid.wav");
125   sound_manager->preload("sounds/flip.wav");
126   sound_manager->preload("sounds/invincible.wav");
127   sound_manager->preload("sounds/splash.ogg");
128
129
130   init();
131 }
132
133 Player::~Player()
134 {
135   delete smalltux_gameover;
136   delete smalltux_star;
137   delete bigtux_star;
138 }
139
140 void
141 Player::init()
142 {
143   if(is_big())
144     set_size(31.8, 62.8);
145   else
146     set_size(31.8, 30.8);
147
148   dir = RIGHT;
149   old_dir = dir;
150   duck = false;
151   dead = false;
152
153   dying = false;
154   peeking = AUTO;
155   last_ground_y = 0;
156   fall_mode = ON_GROUND;
157   jumping = false;
158   can_jump = true;
159   butt_jump = false;
160   deactivated = false;
161   backflipping = false;
162   backflip_direction = 0;
163   visible = true;
164   swimming = false;
165
166   on_ground_flag = false;
167   grabbed_object = NULL;
168
169   physic.reset();
170 }
171
172 void
173 Player::expose(HSQUIRRELVM vm, SQInteger table_idx)
174 {
175   if (name.empty())
176     return;
177
178   Scripting::expose_object(vm, table_idx, dynamic_cast<Scripting::Player *>(this), name, false);
179 }
180
181 void
182 Player::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
183 {
184   if (name.empty())
185     return;
186
187   Scripting::unexpose_object(vm, table_idx, name);
188 }
189
190 void
191 Player::set_controller(Controller* controller)
192 {
193   this->controller = controller;
194 }
195
196 bool
197 Player::adjust_height(float new_height)
198 {
199   Rect bbox2 = bbox;
200   bbox2.move(Vector(0, bbox.get_height() - new_height));
201   bbox2.set_height(new_height);
202
203   if(new_height > bbox.get_height()) {
204     Rect additional_space = bbox2;
205     additional_space.set_height(new_height - bbox.get_height());
206     if(!Sector::current()->is_free_of_statics(additional_space, this))
207       return false;
208   }
209
210   // adjust bbox accordingly
211   // note that we use members of moving_object for this, so we can run this during CD, too
212   set_pos(bbox2.p1);
213   set_size(bbox2.get_width(), bbox2.get_height());
214   return true;
215 }
216
217 void
218 Player::trigger_sequence(std::string sequence_name)
219 {
220   GameSession::current()->start_sequence(sequence_name);
221 }
222
223 void
224 Player::update(float elapsed_time)
225 {
226   if( no_water ){
227     swimming = false;
228   }
229   no_water = true;
230
231   if(dying && dying_timer.check()) {
232     dead = true;
233     return;
234   }
235
236   if(!dying && !deactivated)
237     handle_input();
238
239   // handle_input() calls apply_friction() when Tux is not walking, so we'll have to do this ourselves
240   if (deactivated)
241     apply_friction();
242
243   // extend/shrink tux collision rectangle so that we fall through/walk over 1
244   // tile holes
245   if(fabsf(physic.get_velocity_x()) > MAX_WALK_XM) {
246     set_width(34);
247   } else {
248     set_width(31.8);
249   }
250
251   // on downward slopes, adjust vertical velocity so tux walks smoothly down
252   if (on_ground()) {
253     if(floor_normal.y != 0) {
254       if ((floor_normal.x * physic.get_velocity_x()) >= 0) {
255         physic.set_velocity_y(250);
256       }
257     }
258   }
259
260   // handle backflipping
261   if (backflipping) {
262     //prevent player from changing direction when backflipping
263     dir = (backflip_direction == 1) ? LEFT : RIGHT;
264     if (backflip_timer.started()) physic.set_velocity_x(100 * backflip_direction);
265   }
266
267   // set fall mode...
268   if(on_ground()) {
269     fall_mode = ON_GROUND;
270     last_ground_y = get_pos().y;
271   } else {
272     if(get_pos().y > last_ground_y)
273       fall_mode = FALLING;
274     else if(fall_mode == ON_GROUND)
275       fall_mode = JUMPING;
276   }
277
278   // check if we landed
279   if(on_ground()) {
280     jumping = false;
281     if (backflipping && (!backflip_timer.started())) {
282       backflipping = false;
283       backflip_direction = 0;
284
285       // if controls are currently deactivated, we take care of standing up ourselves
286       if (deactivated)
287         do_standup();
288     }
289   }
290
291   // calculate movement for this frame
292   movement = physic.get_movement(elapsed_time);
293
294   if(grabbed_object != NULL && !dying) {
295     Vector pos = get_pos() +
296       Vector(dir == LEFT ? -16 : 16, get_bbox().get_height()*0.66666 - 32);
297     grabbed_object->grab(*this, pos, dir);
298   }
299
300   if(grabbed_object != NULL && dying){
301     grabbed_object->ungrab(*this, dir);
302     grabbed_object = NULL;
303   }
304
305   on_ground_flag = false;
306
307   // when invincible, spawn particles
308   if (invincible_timer.started() && !dying)
309   {
310     if (systemRandom.rand(0, 2) == 0) {
311       float px = systemRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
312       float py = systemRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
313       Vector ppos = Vector(px, py);
314       Vector pspeed = Vector(0, 0);
315       Vector paccel = Vector(0, 0);
316       // draw bright sparkle when there is lots of time left, dark sparkle when invincibility is about to end
317       if (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING) {
318         // make every other a longer sparkle to make trail a bit fuzzy
319         if (size_t(game_time*20)%2) {
320           Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "small", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
321         } else {
322           Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "medium", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
323         }
324       } else {
325         Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "dark", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
326       }
327     }
328   }
329
330 }
331
332 bool
333 Player::on_ground()
334 {
335   return on_ground_flag;
336 }
337
338 bool
339 Player::is_big()
340 {
341   if(player_status->bonus == NO_BONUS)
342     return false;
343
344   return true;
345 }
346
347 void
348 Player::apply_friction()
349 {
350   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
351     physic.set_velocity_x(0);
352     physic.set_acceleration_x(0);
353   } else if(physic.get_velocity_x() < 0) {
354     physic.set_acceleration_x(WALK_ACCELERATION_X * 1.5);
355     } else if(physic.get_velocity_x() > 0) {
356     physic.set_acceleration_x(WALK_ACCELERATION_X * -1.5);
357   }
358 }
359
360 void
361 Player::handle_horizontal_input()
362 {
363   float vx = physic.get_velocity_x();
364   float vy = physic.get_velocity_y();
365   float ax = physic.get_acceleration_x();
366   float ay = physic.get_acceleration_y();
367
368   float dirsign = 0;
369   if(!duck || physic.get_velocity_y() != 0) {
370     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
371       old_dir = dir;
372       dir = LEFT;
373       dirsign = -1;
374     } else if(!controller->hold(Controller::LEFT)
375               && controller->hold(Controller::RIGHT)) {
376       old_dir = dir;
377       dir = RIGHT;
378       dirsign = 1;
379     }
380   }
381
382   // only run if action key is pressed and we're not holding anything
383   if (!(controller->hold(Controller::ACTION) && (!grabbed_object))) {
384     ax = dirsign * WALK_ACCELERATION_X;
385     // limit speed
386     if(vx >= MAX_WALK_XM && dirsign > 0) {
387       vx = MAX_WALK_XM;
388       ax = 0;
389     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
390       vx = -MAX_WALK_XM;
391       ax = 0;
392     }
393   } else {
394     ax = dirsign * RUN_ACCELERATION_X;
395     // limit speed
396     if(vx >= MAX_RUN_XM && dirsign > 0) {
397       vx = MAX_RUN_XM;
398       ax = 0;
399     } else if(vx <= -MAX_RUN_XM && dirsign < 0) {
400       vx = -MAX_RUN_XM;
401       ax = 0;
402     }
403   }
404
405   // we can reach WALK_SPEED without any acceleration
406   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
407     vx = dirsign * WALK_SPEED;
408   }
409
410   // changing directions?
411   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
412     // let's skid!
413     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
414       skidding_timer.start(SKID_TIME);
415       sound_manager->play("sounds/skid.wav");
416       // dust some particles
417       Sector::current()->add_object(
418         new Particles(
419           Vector(dir == RIGHT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
420           dir == RIGHT ? 270+20 : 90-40, dir == RIGHT ? 270+40 : 90-20,
421           Vector(280, -260), Vector(0, 300), 3, Color(.4, .4, .4), 3, .8,
422           LAYER_OBJECTS+1));
423
424       ax *= 2.5;
425     } else {
426       ax *= 2;
427     }
428   }
429
430   physic.set_velocity(vx, vy);
431   physic.set_acceleration(ax, ay);
432
433   // we get slower when not pressing any keys
434   if(dirsign == 0) {
435     apply_friction();
436   }
437
438 }
439
440 void
441 Player::do_cheer()
442 {
443   do_duck();
444   do_backflip();
445   do_standup();
446 }
447
448 void
449 Player::do_duck() {
450   if (duck)
451     return;
452   if (!is_big())
453     return;
454
455   if (physic.get_velocity_y() != 0)
456     return;
457   if (!on_ground())
458     return;
459
460   if (adjust_height(31.8)) {
461     duck = true;
462     unduck_hurt_timer.stop();
463   } else {
464     // FIXME: what now?
465   }
466 }
467
468 void
469 Player::do_standup() {
470   if (!duck)
471     return;
472   if (!is_big())
473     return;
474   if (backflipping)
475     return;
476
477   if (adjust_height(63.8)) {
478     duck = false;
479     unduck_hurt_timer.stop();
480   } else {
481     // if timer is not already running, start it.
482     if (unduck_hurt_timer.get_period() == 0) {
483       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
484     }
485     else if (unduck_hurt_timer.check()) {
486       kill(false);
487     }
488   }
489
490 }
491
492 void
493 Player::do_backflip() {
494   if (!duck)
495     return;
496   if (!on_ground())
497     return;
498
499   // TODO: we don't have an animation for firetux backflipping, so let's revert to bigtux
500   set_bonus(GROWUP_BONUS, true);
501
502   backflip_direction = (dir == LEFT)?(+1):(-1);
503   backflipping = true;
504   do_jump(-580);
505   sound_manager->play("sounds/flip.wav");
506   backflip_timer.start(0.15);
507 }
508
509 void
510 Player::do_jump(float yspeed) {
511   if (!on_ground())
512     return;
513
514   physic.set_velocity_y(yspeed);
515   //bbox.move(Vector(0, -1));
516   jumping = true;
517   on_ground_flag = false;
518   can_jump = false;
519
520   // play sound
521   if (is_big()) {
522     sound_manager->play("sounds/bigjump.wav");
523   } else {
524     sound_manager->play("sounds/jump.wav");
525   }
526 }
527
528 void
529 Player::handle_vertical_input()
530 {
531   // Press jump key
532   if(controller->pressed(Controller::JUMP) && (can_jump)) {
533     if (duck) {
534       // when running, only jump a little bit; else do a backflip
535       if ((physic.get_velocity_x() != 0) || (controller->hold(Controller::LEFT)) || (controller->hold(Controller::RIGHT))) do_jump(-300); else do_backflip();
536     } else {
537       // jump a bit higher if we are running; else do a normal jump
538       if (fabs(physic.get_velocity_x()) > MAX_WALK_XM) do_jump(-580); else do_jump(-520);
539     }
540   }
541   // Let go of jump key
542   else if(!controller->hold(Controller::JUMP)) {
543     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
544       jumping = false;
545       physic.set_velocity_y(0);
546     }
547   }
548
549   /* In case the player has pressed Down while in a certain range of air,
550      enable butt jump action */
551   if (controller->hold(Controller::DOWN) && !butt_jump && !duck && is_big() && jumping) {
552     butt_jump = true;
553   }
554
555   /* When Down is not held anymore, disable butt jump */
556   if(butt_jump && !controller->hold(Controller::DOWN))
557     butt_jump = false;
558
559   // swimming
560   physic.set_acceleration_y(0);
561   if (swimming) {
562     if (controller->hold(Controller::UP) || controller->hold(Controller::JUMP))
563       physic.set_acceleration_y(-2000);
564     physic.set_velocity_y(physic.get_velocity_y() * 0.94);
565   }
566 }
567
568 void
569 Player::handle_input()
570 {
571   if (ghost_mode) {
572     handle_input_ghost();
573     return;
574   }
575
576   /* Peeking */
577   if( controller->released( Controller::PEEK_LEFT ) ) {
578     peeking = AUTO;
579   }
580   if( controller->released( Controller::PEEK_RIGHT ) ) {
581     peeking = AUTO;
582   }
583   if( controller->pressed( Controller::PEEK_LEFT ) ) {
584     peeking = LEFT;
585   }
586   if( controller->pressed( Controller::PEEK_RIGHT ) ) {
587     peeking = RIGHT;
588   }
589
590   /* Handle horizontal movement: */
591   if (!backflipping) handle_horizontal_input();
592
593   /* Jump/jumping? */
594   if (on_ground() && !controller->hold(Controller::JUMP))
595     can_jump = true;
596
597   /* Handle vertical movement: */
598   handle_vertical_input();
599
600   /* Shoot! */
601   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
602     if(Sector::current()->add_bullet(
603          get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2)
604                       : Vector(32, bbox.get_height()/2)),
605          physic.get_velocity_x(), dir))
606       shooting_timer.start(SHOOTING_TIME);
607   }
608
609   /* Duck or Standup! */
610   if (controller->hold(Controller::DOWN)) {
611     do_duck();
612   } else {
613     do_standup();
614   }
615
616   /* grabbing */
617   try_grab();
618
619   if(!controller->hold(Controller::ACTION) && grabbed_object) {
620     // move the grabbed object a bit away from tux
621     Vector pos = get_pos() +
622         Vector(dir == LEFT ? -bbox.get_width()-1 : bbox.get_width()+1,
623                 bbox.get_height()*0.66666 - 32);
624     Rect dest(pos, pos + Vector(32, 32));
625     if(Sector::current()->is_free_of_movingstatics(dest)) {
626       MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
627       if(moving_object) {
628         moving_object->set_pos(pos);
629       } else {
630         log_debug << "Non MovingObjetc grabbed?!?" << std::endl;
631       }
632       grabbed_object->ungrab(*this, dir);
633       grabbed_object = NULL;
634     }
635   }
636 }
637
638 void 
639 Player::try_grab()
640 {
641   if(controller->hold(Controller::ACTION) && !grabbed_object
642       && !duck) {
643   Sector* sector = Sector::current();
644     Vector pos;
645     if(dir == LEFT) {
646       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
647     } else {
648       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
649     }
650
651     for(Sector::Portables::iterator i = sector->portables.begin();
652         i != sector->portables.end(); ++i) {
653       Portable* portable = *i;
654       if(!portable->is_portable())
655         continue;
656
657       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
658       assert(portable);
659       if(moving_object == NULL)
660         continue;
661
662       if(moving_object->get_bbox().contains(pos)) {
663         grabbed_object = portable;
664         grabbed_object->grab(*this, get_pos(), dir);
665         break;
666       }
667     }
668   }
669 }
670
671 void
672 Player::handle_input_ghost()
673 {
674   float vx = 0;
675   float vy = 0;
676   if (controller->hold(Controller::LEFT)) {
677     dir = LEFT;
678     vx -= MAX_RUN_XM * 2;
679   }
680   if (controller->hold(Controller::RIGHT)) {
681     dir = RIGHT;
682     vx += MAX_RUN_XM * 2;
683   }
684   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
685     vy -= MAX_RUN_XM * 2;
686   }
687   if (controller->hold(Controller::DOWN)) {
688     vy += MAX_RUN_XM * 2;
689   }
690   if (controller->hold(Controller::ACTION)) {
691     set_ghost_mode(false);
692   }
693   physic.set_velocity(vx, vy);
694   physic.set_acceleration(0, 0);
695 }
696
697 void
698 Player::add_coins(int count)
699 {
700   player_status->add_coins(count);
701 }
702
703 int
704 Player::get_coins()
705 {
706   return player_status->coins;
707 }
708
709 bool
710 Player::add_bonus(const std::string& bonustype)
711 {
712   BonusType type = NO_BONUS;
713
714   if(bonustype == "grow") {
715     type = GROWUP_BONUS;
716   } else if(bonustype == "fireflower") {
717     type = FIRE_BONUS;
718   } else if(bonustype == "iceflower") {
719     type = ICE_BONUS;
720   } else if(bonustype == "none") {
721     type = NO_BONUS;
722   } else {
723     std::ostringstream msg;
724     msg << "Unknown bonus type "  << bonustype;
725     throw std::runtime_error(msg.str());
726   }
727
728   return add_bonus(type);
729 }
730
731 bool
732 Player::add_bonus(BonusType type, bool animate)
733 {
734   // always ignore NO_BONUS
735   if (type == NO_BONUS) {
736     return true;
737   }
738
739   // ignore GROWUP_BONUS if we're already big
740   if (type == GROWUP_BONUS) {
741     if (player_status->bonus == GROWUP_BONUS)
742       return true;
743     if (player_status->bonus == FIRE_BONUS)
744       return true;
745     if (player_status->bonus == ICE_BONUS)
746       return true;
747   }
748
749   return set_bonus(type, animate);
750 }
751
752 bool
753 Player::set_bonus(BonusType type, bool animate)
754 {
755   if(player_status->bonus == NO_BONUS) {
756     if (!adjust_height(62.8)) {
757       printf("can't adjust\n");
758       return false;
759     }
760     if(animate)
761       growing_timer.start(GROWING_TIME);
762   }
763
764   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
765     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
766       // visually lose helmet
767       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
768       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
769       Vector paccel = Vector(0, 1000);
770       std::string action = (dir==LEFT)?"left":"right";
771       Sector::current()->add_object(new SpriteParticle("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
772     }
773     if ((player_status->bonus == ICE_BONUS) && (animate)) {
774       // visually lose cap
775       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
776       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
777       Vector paccel = Vector(0, 1000);
778       std::string action = (dir==LEFT)?"left":"right";
779       Sector::current()->add_object(new SpriteParticle("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
780     }
781     player_status->max_fire_bullets = 0;
782     player_status->max_ice_bullets = 0;
783   }
784   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
785   if (type == ICE_BONUS) player_status->max_ice_bullets++;
786
787   player_status->bonus = type;
788   return true;
789 }
790
791 void
792 Player::set_visible(bool visible)
793 {
794   this->visible = visible;
795   if( visible )
796     set_group(COLGROUP_MOVING);
797   else
798     set_group(COLGROUP_DISABLED);
799 }
800
801 bool
802 Player::get_visible()
803 {
804   return visible;
805 }
806
807 void
808 Player::kick()
809 {
810   kick_timer.start(KICK_TIME);
811 }
812
813 void
814 Player::draw(DrawingContext& context)
815 {
816   if(!visible)
817     return;
818
819   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
820   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
821     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
822     float py = Sector::current()->camera->get_translation().y;
823     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
824     context.draw_surface(airarrow.get(), Vector(px, py), LAYER_HUD - 1);
825   }
826
827   TuxBodyParts* tux_body;
828
829   if (player_status->bonus == GROWUP_BONUS)
830     tux_body = big_tux;
831   else if (player_status->bonus == FIRE_BONUS)
832     tux_body = fire_tux;
833   else if (player_status->bonus == ICE_BONUS)
834     tux_body = ice_tux;
835   else
836     tux_body = small_tux;
837
838   int layer = LAYER_OBJECTS + 1;
839
840   /* Set Tux sprite action */
841   if (backflipping)
842     {
843     if(dir == LEFT)
844       tux_body->set_action("backflip-left");
845     else // dir == RIGHT
846       tux_body->set_action("backflip-right");
847     }
848   else if (duck && is_big())
849     {
850     if(dir == LEFT)
851       tux_body->set_action("duck-left");
852     else // dir == RIGHT
853       tux_body->set_action("duck-right");
854     }
855   else if (skidding_timer.started() && !skidding_timer.check())
856     {
857     if(dir == LEFT)
858       tux_body->set_action("skid-left");
859     else // dir == RIGHT
860       tux_body->set_action("skid-right");
861     }
862   else if (kick_timer.started() && !kick_timer.check())
863     {
864     if(dir == LEFT)
865       tux_body->set_action("kick-left");
866     else // dir == RIGHT
867       tux_body->set_action("kick-right");
868     }
869   else if (butt_jump && is_big())
870     {
871     if(dir == LEFT)
872       tux_body->set_action("buttjump-left");
873     else // dir == RIGHT
874       tux_body->set_action("buttjump-right");
875     }
876   else if (!on_ground())
877     {
878     if(dir == LEFT)
879       tux_body->set_action("jump-left");
880     else // dir == RIGHT
881       tux_body->set_action("jump-right");
882     }
883   else
884     {
885     if (fabsf(physic.get_velocity_x()) < 1.0f) // standing
886       {
887       if(dir == LEFT)
888         tux_body->set_action("stand-left");
889       else // dir == RIGHT
890         tux_body->set_action("stand-right");
891       }
892     else // moving
893       {
894       if(dir == LEFT)
895         tux_body->set_action("walk-left");
896       else // dir == RIGHT
897         tux_body->set_action("walk-right");
898       }
899     }
900
901   if(idle_timer.check())
902     {
903     if(is_big())
904       {
905       if(dir == LEFT)
906         tux_body->head->set_action("idle-left", 1);
907       else // dir == RIGHT
908         tux_body->head->set_action("idle-right", 1);
909       }
910
911     }
912
913   // Tux is holding something
914   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
915       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check()))
916     {
917     if (duck)
918       {
919       if(dir == LEFT)
920         tux_body->arms->set_action("duck+grab-left");
921       else // dir == RIGHT
922         tux_body->arms->set_action("duck+grab-right");
923       }
924     else
925       {
926       if(dir == LEFT)
927         tux_body->arms->set_action("grab-left");
928       else // dir == RIGHT
929         tux_body->arms->set_action("grab-right");
930       }
931     }
932
933   /* Draw Tux */
934   if(dying) {
935     smalltux_gameover->draw(context, get_pos(), LAYER_FLOATINGOBJECTS + 1);
936   }
937   else if ((growing_timer.get_timeleft() > 0) && (!duck)) {
938       if (dir == RIGHT) {
939         context.draw_surface(growingtux_right[int((growing_timer.get_timegone() *
940                  GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
941       } else {
942         context.draw_surface(growingtux_left[int((growing_timer.get_timegone() *
943                 GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
944       }
945     }
946   else if (safe_timer.started() && size_t(game_time*40)%2)
947     ;  // don't draw Tux
948   else
949     tux_body->draw(context, get_pos(), layer);
950
951 }
952
953 void
954 Player::collision_tile(uint32_t tile_attributes)
955 {
956   if(tile_attributes & Tile::HURTS)
957     kill(false);
958
959   if( swimming ){
960     if( tile_attributes & Tile::WATER ){
961       no_water = false;
962     } else {
963       swimming = false;
964     }
965   } else {
966     if( tile_attributes & Tile::WATER ){
967       swimming = true;
968       no_water = false;
969       sound_manager->play( "sounds/splash.ogg" );
970     }
971   }
972 }
973
974 void
975 Player::collision_solid(const CollisionHit& hit)
976 {
977   if(hit.bottom) {
978     if(physic.get_velocity_y() > 0)
979       physic.set_velocity_y(0);
980
981     on_ground_flag = true;
982     floor_normal = hit.slope_normal;
983   } else if(hit.top) {
984     if(physic.get_velocity_y() < 0)
985       physic.set_velocity_y(.2);
986   }
987
988   if(hit.left || hit.right) {
989     physic.set_velocity_x(0);
990   }
991
992   // crushed?
993   if(hit.crush) {
994     if(hit.left || hit.right) {
995       kill(true);
996     } else if(hit.top || hit.bottom) {
997       kill(false);
998     }
999   }
1000 }
1001
1002 HitResponse
1003 Player::collision(GameObject& other, const CollisionHit& hit)
1004 {
1005   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1006   if(bullet) {
1007     return FORCE_MOVE;
1008   }
1009
1010   if(hit.left || hit.right) {
1011     try_grab(); //grab objects right now, in update it will be too late
1012   }
1013 #ifdef DEBUG
1014   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1015 #endif
1016   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1017   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1018     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1019     if(trigger) {
1020       if(controller->pressed(Controller::UP))
1021         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1022     }
1023
1024     return FORCE_MOVE;
1025   }
1026
1027   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1028   if(badguy != NULL) {
1029     if(safe_timer.started() || invincible_timer.started())
1030       return FORCE_MOVE;
1031
1032     return CONTINUE;
1033   }
1034
1035   return CONTINUE;
1036 }
1037
1038 void
1039 Player::make_invincible()
1040 {
1041   sound_manager->play("sounds/invincible.wav");
1042   invincible_timer.start(TUX_INVINCIBLE_TIME);
1043   Sector::current()->play_music(HERRING_MUSIC);
1044 }
1045
1046 /* Kill Player! */
1047 void
1048 Player::kill(bool completely)
1049 {
1050   if(dying || deactivated)
1051     return;
1052
1053   if(!completely && (safe_timer.started() || invincible_timer.started()))
1054     return;
1055
1056   sound_manager->play("sounds/hurt.wav");
1057
1058   physic.set_velocity_x(0);
1059
1060   if(!completely && (is_big() || growing_timer.started())) {
1061     if(player_status->bonus == FIRE_BONUS
1062         || player_status->bonus == ICE_BONUS) {
1063       safe_timer.start(TUX_SAFE_TIME);
1064       set_bonus(GROWUP_BONUS, true);
1065     } else if(player_status->bonus == GROWUP_BONUS) {
1066       //growing_timer.start(GROWING_TIME);
1067       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1068       adjust_height(30.8);
1069       duck = false;
1070       set_bonus(NO_BONUS, true);
1071     } else if(player_status->bonus == NO_BONUS) {
1072       growing_timer.stop();
1073       safe_timer.start(TUX_SAFE_TIME);
1074       adjust_height(30.8);
1075       duck = false;
1076     }
1077   } else {
1078     for (int i = 0; (i < 5) && (i < player_status->coins); i++)
1079     {
1080       // the numbers: starting x, starting y, velocity y
1081       Sector::current()->add_object(new FallingCoin(get_pos() +
1082             Vector(systemRandom.rand(5), systemRandom.rand(-32,18)),
1083             systemRandom.rand(-100,100)));
1084     }
1085     physic.enable_gravity(true);
1086     physic.set_acceleration(0, 0);
1087     physic.set_velocity(0, -700);
1088     player_status->coins -= 25;
1089     set_bonus(NO_BONUS, true);
1090     dying = true;
1091     dying_timer.start(3.0);
1092     set_group(COLGROUP_DISABLED);
1093
1094     DisplayEffect* effect = new DisplayEffect();
1095     effect->fade_out(3.0);
1096     Sector::current()->add_object(effect);
1097     sound_manager->stop_music(3.0);
1098   }
1099 }
1100
1101 void
1102 Player::move(const Vector& vector)
1103 {
1104   set_pos(vector);
1105
1106   // TODO: do we need the following? Seems irrelevant to moving the player
1107   if(is_big())
1108     set_size(31.8, 63.8);
1109   else
1110     set_size(31.8, 31.8);
1111   duck = false;
1112   last_ground_y = vector.y;
1113
1114   physic.reset();
1115 }
1116
1117 void
1118 Player::check_bounds(Camera* camera)
1119 {
1120   /* Keep tux in bounds: */
1121   if (get_pos().x < 0) {
1122     // Lock Tux to the size of the level, so that he doesn't fall of
1123     // on the left side
1124     set_pos(Vector(0, get_pos().y));
1125   }
1126
1127   /* fallen out of the level? */
1128   if (get_pos().y > Sector::current()->get_height()) {
1129     kill(true);
1130     return;
1131   }
1132
1133   // can happen if back scrolling is disabled
1134   if(get_pos().x < camera->get_translation().x) {
1135     set_pos(Vector(camera->get_translation().x, get_pos().y));
1136   }
1137   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1138   {
1139     set_pos(Vector(
1140           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1141           get_pos().y));
1142   }
1143 }
1144
1145 void
1146 Player::add_velocity(const Vector& velocity)
1147 {
1148   physic.set_velocity(physic.get_velocity() + velocity);
1149 }
1150
1151 void
1152 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1153 {
1154   if (end_speed.x > 0)
1155     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1156   if (end_speed.x < 0)
1157     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1158   if (end_speed.y > 0)
1159     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1160   if (end_speed.y < 0)
1161     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1162 }
1163
1164 void
1165 Player::bounce(BadGuy& )
1166 {
1167   if(controller->hold(Controller::JUMP))
1168     physic.set_velocity_y(-520);
1169   else
1170     physic.set_velocity_y(-300);
1171 }
1172
1173 //Scripting Functions Below
1174
1175 void
1176 Player::deactivate()
1177 {
1178   if (deactivated)
1179     return;
1180   deactivated = true;
1181   physic.set_velocity_x(0);
1182   physic.set_velocity_y(0);
1183   physic.set_acceleration_x(0);
1184   physic.set_acceleration_y(0);
1185 }
1186
1187 void
1188 Player::activate()
1189 {
1190   if (!deactivated)
1191     return;
1192   deactivated = false;
1193 }
1194
1195 void Player::walk(float speed)
1196 {
1197   physic.set_velocity_x(speed);
1198 }
1199
1200 void
1201 Player::set_ghost_mode(bool enable)
1202 {
1203   if (ghost_mode == enable)
1204     return;
1205
1206   if (enable) {
1207     ghost_mode = true;
1208     set_group(COLGROUP_DISABLED);
1209     physic.enable_gravity(false);
1210     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1211   } else {
1212     ghost_mode = false;
1213     set_group(COLGROUP_MOVING);
1214     physic.enable_gravity(true);
1215     log_debug << "You feel solid again." << std::endl;
1216   }
1217 }