Level time decreases only when game is not paused, i.e. when update() is called /
[supertux.git] / src / object / level_time.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
20 #include <config.h>
21
22 #include "level_time.hpp"
23
24 #include <stdexcept>
25 #include <iostream>
26 #include <sstream>
27 #include "main.hpp"
28 #include "resources.hpp"
29 #include "sector.hpp"
30 #include "gettext.hpp"
31 #include "object_factory.hpp"
32 #include "object/player.hpp"
33 #include "video/drawing_context.hpp"
34 #include "lisp/list_iterator.hpp"
35 #include "log.hpp"
36
37 /** When to alert player they're low on time! */
38 static const float TIME_WARNING = 20;
39
40 LevelTime::LevelTime(const lisp::Lisp& reader)
41 : running(true), time_left(0)
42 {
43   reader.get("time", time_left);
44   if(time_left <= 0) throw std::runtime_error("No or invalid leveltime specified");
45 }
46
47 void
48 LevelTime::update(float elapsed_time)
49 {
50   if (!running) return;
51
52   time_left = std::max(time_left - elapsed_time, 0.0f);
53   if(time_left <= 0) {
54     Sector::current()->player->kill(true);
55     stop();
56   }
57 }
58
59 void
60 LevelTime::draw(DrawingContext& context)
61 {
62   context.push_transform();
63   context.set_translation(Vector(0, 0));
64
65   if ((time_left > TIME_WARNING) || (int(game_time * 2.5) % 2)) {
66     std::stringstream ss;
67     ss << int(time_left);
68     std::string time = ss.str();
69
70     float caption_width = white_text->get_text_width(_("TIME")) + white_text->get_text_width(" ");
71     float all_width = caption_width + white_text->get_text_width(time);
72
73     context.draw_text(white_text, _("TIME"), Vector((SCREEN_WIDTH - all_width)/2, BORDER_Y), LEFT_ALLIGN, LAYER_FOREGROUND1);
74     context.draw_text(gold_text, time, Vector((SCREEN_WIDTH - all_width)/2 + caption_width, BORDER_Y), LEFT_ALLIGN, LAYER_FOREGROUND1);
75   }
76
77   context.pop_transform();
78 }
79
80 void
81 LevelTime::stop()
82 {
83   running = false;
84 }
85
86 IMPLEMENT_FACTORY(LevelTime, "leveltime");