Messaging subsystem rewrite, step I
[supertux.git] / src / object / level_time.cpp
1 #include <config.h>
2
3 #include "level_time.hpp"
4
5 #include <stdexcept>
6 #include <iostream>
7 #include "main.hpp"
8 #include "resources.hpp"
9 #include "sector.hpp"
10 #include "gettext.hpp"
11 #include "object_factory.hpp"
12 #include "object/player.hpp"
13 #include "video/drawing_context.hpp"
14 #include "lisp/list_iterator.hpp"
15 #include "msg.hpp"
16
17 /** When to alert player they're low on time! */
18 static const float TIME_WARNING = 20;
19
20 LevelTime::LevelTime(const lisp::Lisp& reader)
21 : final_level_time(0.f), final_remaining_time(0.f)
22 {
23     float time = -1;
24     lisp::ListIterator iter(&reader);
25     while(iter.next()) {
26         if(iter.item() == "time") {
27             iter.value()->get(time);
28             break;
29         } else {
30             msg_warning << "Unknown token '" << iter.item() << "' in LevelTime object" << std::endl;
31         }
32     }
33     if(time < 0)
34       throw std::runtime_error("Invalid leveltime specified");
35     time_left.start(time);
36 }
37
38 LevelTime::~LevelTime()
39 {}
40
41 void
42 LevelTime::update(float )
43 {
44   if(time_left.check()) {
45     Sector::current()->player->kill(Player::KILL);
46   }
47 }
48
49 void
50 LevelTime::draw(DrawingContext& context)
51 {
52   context.push_transform();
53   context.set_translation(Vector(0, 0));
54
55   char str[60];
56     
57   if(get_remaining_time() < 0) {
58     context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, BORDER_Y),
59         CENTER_ALLIGN, LAYER_FOREGROUND1);
60   } else if (get_remaining_time() > TIME_WARNING
61       || int(game_time * 2.5) % 2) {
62     snprintf(str, sizeof(str), " %d", int(get_remaining_time()));
63     context.draw_text(white_text, _("TIME"),
64         Vector(SCREEN_WIDTH/2, BORDER_Y), CENTER_ALLIGN, LAYER_FOREGROUND1);
65     context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2 + 4*16, BORDER_Y),
66                       CENTER_ALLIGN, LAYER_FOREGROUND1);
67   }
68
69   context.pop_transform();
70 }
71
72 float
73 LevelTime::get_level_time()
74 {
75   if (!time_left.started())
76     return final_level_time;
77   return time_left.get_period();
78 }
79
80 float
81 LevelTime::get_remaining_time()
82 {
83   if (!time_left.started())
84     return final_remaining_time;
85   return time_left.get_timeleft();
86 }
87
88 void
89 LevelTime::stop()
90 {
91   final_level_time = time_left.get_period();
92   final_remaining_time = time_left.get_timeleft();
93   time_left.stop();
94 }
95
96 IMPLEMENT_FACTORY(LevelTime, "leveltime");