35fe57cb4e776b8a809b420a75dad0e1041f636a
[nit.git] / lib / actors / examples / agent_simulation / agent_simulation.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # a "Framework" to make Multi-Agent Simulations in Nit
16 module agent_simulation is no_warning("missing-doc")
17
18 import actors
19
20 # Master of the simulation, it initiates the steps and waits for them to terminate
21 class ClockAgent
22 actor
23
24 # Number of steps to do in the simulation
25 var nb_steps: Int
26
27 # List of Agents in the simulation
28 var agents: Array[Agent]
29
30 # Number of agents that finished their step
31 var nb_finished = 0
32
33 fun do_step do
34 for a in agents do a.async.do_step
35 nb_steps -= 1
36 end
37
38 fun finished_step do
39 nb_finished += 1
40 if nb_finished == agents.length then
41 nb_finished = 0
42 if nb_steps != 0 then async.do_step
43 end
44 end
45 end
46
47 class Agent
48 actor
49
50 # Doing a step in the simulation
51 fun do_step do
52 end
53
54 fun end_step do clock_agent.async.finished_step
55
56 end
57
58 redef class Sys
59 var clock_agent: ClockAgent is noautoinit,writable
60 end