Поднимаю вопрос вновь.
Код скинутый мною раньше не работоспособен. Сейчас вроде бы отладил, переделал, код работает как надо. С визуализацией остались проблемы.
Думал все сделать через кнопки. Но при изменении цвета нужных кнопок из списка, не пойму почему не перерисовываются кнопки в окне.
Вот архив с проектом: GameLife.rar
Вот библиотека с игрой:
C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace GameLife
{
public class GameField
{
int height;
int width;
List<Cell> liveCells;
List<Cell> analyzedCells;
List<Cell> nextLiveCells;
public List<Cell> LiveCells
{
get
{
return liveCells;
}
}
public bool GameState { get; private set; }
public GameField(List<Cell> startCellList, int h, int w)
{
liveCells = startCellList;
height = h;
width = w;
GameState = true;
RefreshAnalyzedCells();
}
private void RefreshAnalyzedCells()
{
int x, y;
List<int[]> tempList;
analyzedCells = new List<Cell>();
foreach (Cell cell in liveCells)
{
x = cell.X;
y = cell.Y;
tempList = GetListCoordinatesSurroundedCells(x, y);
Cell tempCell;
CellComparer compCell = new CellComparer();
foreach (int[] c in tempList)
{
tempCell = new Cell(c[0], c[1]);
if (analyzedCells.Find(cellx=> compCell.Equals(cellx, tempCell)) == null)
{
if (liveCells.Find(lCell => compCell.Equals(tempCell, lCell)) != null)
tempCell.Revive();
analyzedCells.Add(tempCell);
}
}
}
}
private List<int[]> GetListCoordinatesSurroundedCells(int x, int y)
{
int[,] resArr = new int[2, 3];
List<int[]> resList = new List<int[]>();
// Получение X координат окружающих клетку
if (x == 0)
{
resArr[0, 0] = height - 1;
resArr[0, 1] = x;
resArr[0, 2] = x + 1;
}
else if (x == height - 1)
{
resArr[0, 0] = x - 1;
resArr[0, 1] = x;
resArr[0, 2] = 0;
}
else
{
resArr[0, 0] = x - 1;
resArr[0, 1] = x;
resArr[0, 2] = x + 1;
}
// Получение Y координат окружающих клетку
if (y == 0)
{
resArr[1, 0] = width - 1;
resArr[1, 1] = y;
resArr[1, 2] = y + 1;
}
else if (y == width - 1)
{
resArr[1, 0] = y - 1;
resArr[1, 1] = y;
resArr[1, 2] = 0;
}
else
{
resArr[1, 0] = y - 1;
resArr[1, 1] = y;
resArr[1, 2] = y + 1;
}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
resList.Add(new int[] { resArr[0, i], resArr[1, j] });
}
resList.RemoveAt(4);
return resList;
}
public void Analyze()
{
CellComparer cellComp = new CellComparer();
nextLiveCells = new List<Cell>(); // "опустошаем список следующих живых клеток"
List<int[]> coordCell = new List<int[]>();
List<Cell> surCell;
foreach(Cell cell in analyzedCells)
{
surCell = new List<Cell>();
coordCell = GetListCoordinatesSurroundedCells(cell.X, cell.Y);
foreach (int[] coordC in coordCell)
{
Cell cell1;
if ((cell1 = analyzedCells.Find(c => c.X == coordC[0] && c.Y == coordC[1])) != null)
surCell.Add(cell1);
else
surCell.Add(new Cell(coordC[0], coordC[1]));
}
int liveNeighb = surCell.FindAll(c => c.LifeState == true).Count;
// если у живой клетки есть две или три живые соседки, то эта клетка продолжает жить;
// в противном случае (если соседей меньше двух или больше трёх) клетка умирает («от одиночества» или «от перенаселённости»)
// в пустой (мёртвой) клетке, рядом с которой ровно три живые клетки, зарождается жизнь;
if (liveNeighb >= 2 && liveNeighb <= 3)
{
Cell tempCell = new Cell(cell);
if(liveNeighb == 3)
tempCell.Revive();
if(tempCell.LifeState)
nextLiveCells.Add(tempCell);
}
}
// на поле не останется ни одной «живой» клетки
if (nextLiveCells.FindAll(c => c.LifeState == true).Count == 0)
GameState = false;
// при очередном шаге ни одна из клеток не меняет своего состояния
var list3 = liveCells.Except(nextLiveCells, cellComp).ToList();
if (list3.Count == 0)
GameState = false;
liveCells = nextLiveCells;
RefreshAnalyzedCells();
}
}
public class Cell
{
private bool _lifeState;
private int _x;
private int _y;
public int X
{
get
{
return _x;
}
}
public int Y
{
get
{
return _y;
}
}
public bool LifeState
{
get
{
return _lifeState;
}
}
public Cell(int x, int y)
{
this._lifeState = false;
this._x = x;
this._y = y;
}
public Cell(Cell c)
{
this._lifeState = c.LifeState;
this._x = c.X;
this._y = c.Y;
}
public void Revive()
{
this._lifeState = true;
}
public void Die()
{
this._lifeState = false;
}
bool Compare(Cell cell)
{
if (this._x == cell._x && this._y == cell._y)
return true;
return false;
}
}
class CellComparer : IEqualityComparer<Cell>
{
public bool Equals(Cell x, Cell y)
{
if (Object.ReferenceEquals(x, y))
return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.X == y.X && x.Y == y.Y;
}
public int GetHashCode(Cell obj)
{
if (object.ReferenceEquals(obj, null))
return 0;
int hashCellCoordX = obj.X.GetHashCode();
int hashCellCoordY = obj.Y.GetHashCode();
return hashCellCoordX ^ hashCellCoordY;
}
}
} |
|
Вот фронтенд окна:
XML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| <Window x:Class="GameOfLife.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:GameOfLife"
mc:Ignorable="d"
Title="MainWindow" Height="740" Width="900" WindowStartupLocation="CenterScreen" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition ></ColumnDefinition>
<ColumnDefinition Width="150"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Name="GameGridField">
</Grid>
<Grid Grid.Column="1" Background="Beige">
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Margin="5,5,5,0">Ширина:</TextBlock>
<TextBox Grid.Row="1" Name="tbWidth" Margin="5,5,5,5"></TextBox>
<TextBlock Grid.Row="2" Margin="5,0,5,0">Высота:</TextBlock>
<TextBox Grid.Row="3" Name="tbHeight" Margin="5,5,5,5"></TextBox>
<Button Grid.Row="4" Name="btnBuildField" Height="25" Width="100" HorizontalAlignment="Center" Margin=" 0, 5" Click="btnBuildField_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF3F3F3" Offset="0"/>
<GradientStop Color="#FFEBEBEB" Offset="0.5"/>
<GradientStop Color="#FFDDDDDD" Offset="0.5"/>
<GradientStop Color="#FFCDCDCD" Offset="1"/>
</LinearGradientBrush>
</Button.Background> Построить поле
</Button>
<Button Grid.Row="5" Name="btnStart" Height="25" Width="100" HorizontalAlignment="Center" Margin=" 0, 5" Click="btnStart_Click">Старт</Button>
</Grid>
</Grid>
</Window> |
|
Вот бэкенд окна:
C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GameLife;
namespace GameOfLife
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
GameField game;
List<Cell> cellList;
private Button[,] field;
int WidthSize;
int HeigthSize;
public MainWindow()
{
InitializeComponent();
cellList = new List<Cell>();
}
private void btnBuildField_Click(object sender, RoutedEventArgs e)
{
GameGridField.RowDefinitions.Clear();
GameGridField.ColumnDefinitions.Clear();
WidthSize = int.Parse(tbWidth.Text);
HeigthSize = int.Parse(tbHeight.Text);
for (int i = 0; i < WidthSize; i++)
GameGridField.ColumnDefinitions.Add(new ColumnDefinition());
for (int i = 0; i < HeigthSize; i++)
GameGridField.RowDefinitions.Add(new RowDefinition());
field = new Button[HeigthSize, WidthSize];
for (int i = 0; i < HeigthSize; i++)
{
for (int j = 0; j < WidthSize; j++)
{
field[i, j] = new Button();
Grid.SetColumn(field[i, j], j);
Grid.SetRow(field[i, j], i);
field[i, j].Click += this.btnFieldGamers_Click;
field[i, j].Background = Brushes.White;
GameGridField.Children.Add(field[i, j]);
}
}
}
private void btnFieldGamers_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
if (game != null)
{
if (!game.GameState)
{
if (btn.Background == Brushes.White)
btn.Background = Brushes.Black;
else
btn.Background = Brushes.White;
}
}
else
{
if (btn.Background == Brushes.White)
btn.Background = Brushes.Black;
else
btn.Background = Brushes.White;
}
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < HeigthSize; i++)
{
for (int j = 0; j < WidthSize; j++)
{
if (field[i, j].Background == Brushes.Black)
cellList.Add(new Cell(i, j));
}
}
game = new GameField(cellList, HeigthSize, WidthSize);
while (game.GameState)
{
System.Threading.Thread.Sleep(1000);
game.Analyze();
if (game.LiveCells.Count != 0)
{
foreach (Cell c in game.LiveCells)
{
field[c.X, c.Y].Background = Brushes.Black;
}
}
else
{
for (int i = 0; i < HeigthSize; i++)
{
for (int j = 0; j < WidthSize; j++)
{
field[i, j].Background = Brushes.White;
}
}
}
}
}
}
} |
|
0
|