Free cookie consent management tool by TermsFeed Policy Generator

source: branches/SimulationCore/HeuristicLab.SimulationCore.Samples/3.3/GameOfLifeSimulation.cs @ 12394

Last change on this file since 12394 was 10454, checked in by abeham, 11 years ago

#1610: updated core, implemented card game sample

File size: 6.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Threading;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Random;
33using HeuristicLab.SimulationCore.AgentBased;
34
35namespace HeuristicLab.SimulationCore.Samples {
36  [Item("GameOfLifeSimulation", "A game of life simulation.")]
37  [Creatable("Simulations")]
38  [StorableClass]
39  public sealed class GameOfLifeSimulation : AgentBasedSimulation {
40    public override Type ProblemType {
41      get { return typeof(GameOfLifeScenario); }
42    }
43
44    private GameOfLifeScenario Scenario {
45      get {
46        return Problem as GameOfLifeScenario;
47      }
48    }
49
50    public ValueParameter<IntValue> IterationsParameter {
51      get { return (ValueParameter<IntValue>)Parameters["Iterations"]; }
52    }
53
54    public GameOfLifeSimulation()
55      : base() {
56      Parameters.Add(new ValueParameter<IntValue>("Iterations", "The number of iterations.", new IntValue(100)));
57
58      Initialize();
59    }
60    [StorableConstructor]
61    private GameOfLifeSimulation(bool deserializing) : base(deserializing) { }
62    [StorableHook(HookType.AfterDeserialization)]
63    private void AfterDeserialization() {
64      Initialize();
65    }
66    private GameOfLifeSimulation(GameOfLifeSimulation original, Cloner cloner)
67      : base(original, cloner) {
68      Initialize();
69    }
70    public override IDeepCloneable Clone(Cloner cloner) {
71      return new GameOfLifeSimulation(this, cloner);
72    }
73
74    private GameOfLifeAgent GetAgent(int x, int y) {
75      int width = Scenario.WidthParameter.Value.Value;
76      int height = Scenario.HeightParameter.Value.Value;
77
78      if (x >= width || y >= height)
79        throw new Exception("invalid index");
80
81      int index = x + y * width;
82
83      return Agents[index] as GameOfLifeAgent;
84    }
85
86    private void Initialize() {
87      if (Scenario != null) {
88        Scenario.WidthParameter.Value.ValueChanged += new EventHandler(Width_ValueChanged);
89        Scenario.HeightParameter.Value.ValueChanged += new EventHandler(Height_ValueChanged);
90      }
91    }
92
93    void Width_ValueChanged(object sender, EventArgs e) {
94      CreateAgents();
95    }
96
97    void Height_ValueChanged(object sender, EventArgs e) {
98      CreateAgents();
99    }
100
101    public IEnumerable<GameOfLifeAgent> GetNeighbors(GameOfLifeAgent agent) {
102      int width = Scenario.WidthParameter.Value.Value;
103      int height = Scenario.HeightParameter.Value.Value;
104      int index = Agents.IndexOf(agent);
105
106      List<GameOfLifeAgent> result = new List<GameOfLifeAgent>();
107
108      int y = index / width;
109      int x = index - (y * width);
110
111      for (int x1 = x - 1; x1 <= x + 1; x1++) {
112        for (int y1 = y - 1; y1 <= y + 1; y1++) {
113          if (x1 >= 0 && y1 >= 0 && x1 < width && y1 < height &&
114            (x1 != x || y1 != y)) {
115            GameOfLifeAgent neighbor = GetAgent(x1, y1);
116            result.Add(neighbor);
117          }
118        }
119      }
120
121      return result;
122    }
123
124    private void CreateAgents() {
125      Agents.Clear();
126      int width = Scenario.WidthParameter.Value.Value;
127      int height = Scenario.HeightParameter.Value.Value;
128
129      for (int i = 0; i < width * height; i++) {
130        Agents.Add(new GameOfLifeAgent(this));
131      }
132
133      InitAgents();
134    }
135
136    protected override void OnProblemChanged() {
137      base.OnProblemChanged();
138
139      Initialize();
140
141      CreateAgents();
142    }
143
144    private void InitAgents() {
145      double rate = Scenario.AliveRateParameter.Value.Value;
146      int width = Scenario.WidthParameter.Value.Value;
147      int height = Scenario.HeightParameter.Value.Value;
148
149      var rand = new FastRandom();
150
151      for (int i = 0; i < width * height; i++) {
152        GameOfLifeAgent agent = Agents[i] as GameOfLifeAgent;
153        agent.Alive = rand.NextDouble() < rate;
154      }
155    }
156
157    protected override void OnPrepared() {
158      base.OnPrepared();
159
160      InitAgents();
161    }
162
163    private void UpdateResults() {
164      int width = Scenario.WidthParameter.Value.Value;
165      int height = Scenario.HeightParameter.Value.Value;
166
167      HeatMap cells = new HeatMap(width, height);
168
169      for (int i = 0; i < width * height; i++) {
170        int y = i / width;
171        int x = i - (y * width);
172
173        if (GetAgent(x, y).Alive)
174          cells[x, y] = 1;
175        else
176          cells[x, y] = 0;
177      }
178
179      Results["Cells"].Value = cells;
180
181      IntValue currentIterations = (Results["CurrentIterations"].Value as IntValue);
182      currentIterations.Value++;
183    }
184
185    protected override void Run(CancellationToken cancellationToken) {
186      int iterations = IterationsParameter.Value.Value;
187      int width = Scenario.WidthParameter.Value.Value;
188      int height = Scenario.HeightParameter.Value.Value;
189
190      int start = 0;
191      if (Results.ContainsKey("CurrentIterations")) {
192        start = (Results["CurrentIterations"].Value as IntValue).Value;
193      } else {
194        Results.Add(new Result("CurrentIterations", new IntValue(0)));
195        Results.Add(new Result("Cells", new HeatMap(width, height)));
196      }
197
198      for (int i = start; i < iterations; i++) {
199        cancellationToken.ThrowIfCancellationRequested();
200
201        base.Step();
202        UpdateResults();
203      }
204    }
205  }
206}
Note: See TracBrowser for help on using the repository browser.