Merge: nitrpg: periodize stats
[nit.git] / contrib / nitrpg / src / game.nit
index 9de4887..1ab143e 100644 (file)
@@ -38,9 +38,18 @@ interface GameEntity
        # Uniq key used for data storage.
        fun key: String is abstract
 
-       # Save `self` as a json object.
+       # Saves the `self` state in game data.
+       #
+       # Date are stored under `self.key`.
        fun save do game.store.store_object(key, to_json)
 
+       # Saves `self` state under `key` data.
+       #
+       # Data are stored under `key / self.key`.
+       fun save_in(key: String) do
+               game.store.store_object(key / self.key, to_json)
+       end
+
        # Json representation of `self`.
        fun to_json: JsonObject  do return new JsonObject
 
@@ -226,11 +235,16 @@ end
 
 redef class User
        # The player linked to `self`.
-       fun player(game: Game): Player is lazy do
-               var player = game.load_player(login)
+       fun player(game: Game): Player do
+               var player = player_cache.get_or_null(game)
+               if player != null then return player
+               player = game.load_player(login)
                if player == null then player = game.add_player(self)
+               player_cache[game] = player
                return player
        end
+
+       private var player_cache = new HashMap[Game, Player]
 end
 
 # A GameReactor reacts to event sent by a `Github::HookListener`.
@@ -273,15 +287,24 @@ interface GameReactor
        #
        # Concrete `GameReactor` implement this method to update game data
        # for each specific GithubEvent.
-       #
-       # By default, only logs received events.
-       fun react_event(game: Game, event: GithubEvent) do
-               game.message(1, "Received event {event} for {game.repo.full_name}")
-       end
+       fun react_event(game: Game, event: GithubEvent) is abstract
 end
 
 # utils
 
+# Sort games by descending number of players.
+#
+# The first in the list is the game with the more players.
+class GamePlayersComparator
+       super Comparator
+
+       redef type COMPARED: Game
+
+       redef fun compare(a, b) do
+               return b.load_players.length <=> a.load_players.length
+       end
+end
+
 # Sort players by descending number of nitcoins.
 #
 # The first in the list is the player with the more of nitcoins.