1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014-2015 Alexandre Terrasa <alexandre@moz-code.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # `nitrpg` game events.
19 # In this module we introduce the concept of `GameEvent`.
20 # They can be attached to every GameEntities.
25 redef class GameEntity
27 # Saves `event` in `self`.
28 fun add_event
(event
: GameEvent) do event
.save_in
(self)
30 # List all events registered in this entity.
32 # This list is reloaded from game data each time its called.
34 # To add events see `add_event`.
35 fun load_events
: Array[GameEvent] do
36 var key
= key
/ "events"
37 var res
= new Array[GameEvent]
38 if not game
.store
.has_collection
(key
) then return res
39 var coll
= game
.store
.list_collection
(key
)
42 res
.add load_event
(name
).as(not null)
44 (new EventTimeComparator).sort
(res
)
48 # Load the event from its `id`.
50 # Looks for the event save file in game data.
51 # Returns `null` if the event cannot be found.
52 fun load_event
(id
: String): nullable GameEvent do
53 var key
= key
/ "events" / id
54 if not game
.store
.has_key
(key
) then return null
55 var json
= game
.store
.load_object
(key
)
56 return new GameEvent.from_json
(game
, json
)
60 # An event that occurs in the `Game`.
64 redef var key
is lazy
do return "events" / internal_id
68 # String used to dissociate events in the display.
71 # GameEvents have raw data associated to them.
73 # These data are stored in a JsonObject.
74 var data
: JsonObject is writable
76 # GameEvent uniq id used for storage.
77 var internal_id
: String is noinit
79 # Date and time of the event.
80 var time
: ISODate is noinit
, writable
82 # An event initialized at now `time`.
84 internal_id
= "{get_time}{object_id}{100.rand}"
88 # Init `self` from a `json` object.
90 # Used to load events from json storage.
91 init from_json
(game
: Game, json
: JsonObject) do
93 internal_id
= json
["internal_id"].to_s
94 kind
= json
["kind"].to_s
95 time
= new ISODate.from_string
(json
["time"].to_s
)
96 data
= json
["data"].as(JsonObject)
100 var json
= new JsonObject
101 json
["internal_id"] = internal_id
.to_s
103 json
["time"] = time
.to_s
109 # Compare `GameEvent` to sort them from the most recent to the older.
110 class EventTimeComparator
113 redef type COMPARED: GameEvent
115 redef fun compare
(a
, b
) do return b
.time
<=> a
.time