examples: annotate examples
[nit.git] / lib / actors / examples / agent_simulation / simple_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 # Using `agent_simulation` by refining the Agent class to make
16 # a multi-agent simulation where every agent know each other
17 # The steps consist of each agent greeting each other, and
18 # waiting for every other agent to respond before notifying
19 # to the `ClockAgent` that they finished their step.
20 module simple_simulation is example
21
22 import agent_simulation
23
24 redef class Agent
25 var others = new Array[Agent]
26 var count = 0
27
28 fun greet(message: String, other: Agent) do other.async.greet_back("Hello back !")
29
30 fun greet_back(message: String) do
31 count -= 1
32 if count == 0 then end_step
33 end
34
35 redef fun do_step do
36 for o in others do
37 o.async.greet("Hello !", self)
38 count += 1
39 end
40 end
41 end
42
43 var nb_steps = 0
44 var nb_agents = 0
45 if args.is_empty or args.length != 2 then
46 nb_steps = 10
47 nb_agents = 10
48 else
49 nb_steps = args[0].to_i
50 nb_agents = args[1].to_i
51 end
52
53 var agents = new Array[Agent]
54 for i in [0..nb_agents[ do agents.add(new Agent)
55 for a in agents do for b in agents do if a != b then a.others.add(b)
56 clock_agent = new ClockAgent(nb_steps, agents)
57 clock_agent.async.do_step