5 / 5 / 0
Регистрация: 22.05.2012
Сообщений: 122
1

Построить сетку для игры Жизнь

05.09.2016, 19:32. Показов 3635. Ответов 5
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Задача построить сетку(поле для игры Жизнь). В текстбоксах ввожу ширину/высоту (количество клеток соответственно).
Как реализовать само поле для игры, тоесть сетку в которой можно будет нажимать на клетку не имею никакого представления.
В WPF тоже очень плохо разбираюсь. Но так как того требует природа технологий, стараюсь учить. До этого все делал только в WinForms.
В общем пока у меня есть только вот такое "чудо":
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<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="900" Width="900" WindowStartupLocation="CenterScreen" ResizeMode="NoResize">
    <StackPanel Orientation="Horizontal">
        <Grid Width="770" Name="GameField">
 
        </Grid>
        <StackPanel Orientation="Vertical" Name="LeftMenu" Width="110" Background="Beige" HorizontalAlignment="Right">
            <TextBlock Margin="5,5,5,0">Ширина:</TextBlock>
            <TextBox Name="tbWidth" Margin="5,5"></TextBox>
            <TextBlock Margin="5,0,5,0">Высота:</TextBlock>
            <TextBox Name="tbHight" Margin="5,5"></TextBox>
            <Button Name="btnBuildField"  Height="25" Width="100"  HorizontalAlignment="Center">Построить поле</Button>
            
            <Button Name="btnStart"  Height="25" Width="100"  HorizontalAlignment="Center">Старт</Button>
        </StackPanel>
    </StackPanel>
</Window>
Подскажите как сделать эту сетку(даже от готового кода не откажусь)
Также можете порекомендовать как мне улучшить тот говнокод который выше.

Либу с реализацией самой игры уже сделал. Осталось только визуализировать это как-то))
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
05.09.2016, 19:32
Ответы с готовыми решениями:

Визуализация игры Жизнь. Какой компонент использовать для прорисовки поля (MVVM)
http://ru.wikipedia.org/wiki/Жизнь_(игра) (Адрес копирните в адресную строку) делаю её. пытаюсь...

Интерфейс для игры «жизнь»
Всем привет! Нужно написать интерфейс программы, в нем должно быть поле (сетка) клеток, которое...

Разработать программу для игры «Жизнь»
3. Разработать программу для игры «Жизнь». Игра моделирует жизнь поколений гипотетической колонии...

Построить турнирную сетку для n пар участников некоего соревнования
Добрый день! Задача такая. Нужно построить турнирную сетку для n пар участников некоего...

5
184 / 183 / 96
Регистрация: 30.04.2016
Сообщений: 478
06.09.2016, 15:40 2
влад0, наверняка, раз Вы уже разработали логику игры, у Вас есть модель поля (сетка).
По кнопке построить сетку Вам нужно создать модель игры.

Отображать созданную модель можно с использованием DrawingContext. Со стороны API подход к рисованию похож на работу с GDI+ в WinForms.

Есть несколько вариантов работы с DrawingContext. Опишу один из них (в примере на MSDN другой вариант показан) - с использованием класса наследника FrameworkElement.

Вот простейший пример использования DrawingContext:
C#
1
2
3
4
5
6
7
8
9
public class RenderingSurface : FrameworkElement
    {
        protected override void OnRender(DrawingContext drawingContext)
        {
            drawingContext.DrawEllipse(Brushes.Red, new Pen(Brushes.Blue, 2), new Point(100,100), 50,50);
 
            base.OnRender(drawingContext);
        }
    }
В этом примере при запуске функция OnRender будет вызвана единственный раз. Последующие вызовы будут происходить по событиям изменения Layout'a элемента или его родителей. Такой вариант для игры будет не достаточен, наверняка, понадобится добавить анимацию изменения состояния, тогда для реализации цикла отрисовки можно воспользоваться возможностями класса CompositionTarget.

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
public class RenderingSurface : FrameworkElement
    {
        public RenderingSurface()
        {
            Loaded += RenderingSurface_Loaded;
            Unloaded += RenderingSurface_Unloaded;
        }
 
        private void RenderingSurface_Unloaded(object sender, RoutedEventArgs e)
        {
            CompositionTarget.Rendering -= OnCompositionTargetRendering;
        }
 
        private void RenderingSurface_Loaded(object sender, RoutedEventArgs e)
        {
            CompositionTarget.Rendering += OnCompositionTargetRendering;
        }
 
        private void OnCompositionTargetRendering(object s, EventArgs a)
        {
            InvalidateVisual();
        }
 
        protected override void OnRender(DrawingContext drawingContext)
        {
            drawingContext.DrawEllipse(Brushes.Red, new Pen(Brushes.Blue, 2), new Point(100,100), 50,50);
 
            base.OnRender(drawingContext);
        }
    }
Сейчас OnRender будет вызываться каждый кадр перерисовки (примерно 60 fps).
1
5 / 5 / 0
Регистрация: 22.05.2012
Сообщений: 122
21.09.2016, 16:09  [ТС] 3
Пытался разобраться с графикой в WPF. Читал про работу с примитивными элипсами и ректанглами. В общем ничего я не понял. И то что вы написал я не понимаю куда вставлять и как использовать
0
Заблокирован
21.09.2016, 16:44 4
Цитата Сообщение от влад0 Посмотреть сообщение
Либу с реализацией самой игры уже сделал.
влад0, покажите как сделали, тогда что-то посоветовать будет проще.
0
5 / 5 / 0
Регистрация: 22.05.2012
Сообщений: 122
21.09.2016, 17:38  [ТС] 5
Вот так вот:
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
using System.Collections.Generic;
 
namespace GameLife
{
    public class GameField
    {
        int height;
        int width;
        List<Cell> liveCells;
        List<Cell> analyzedCells;
        List<Cell> nextLiveCells;
 
        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;
            int[,] tempArr;
            foreach (Cell cell in liveCells)
            {
                x = cell.X;
                y = cell.Y;
                tempArr = GetCoordinatesSurroundedCells(x, y);                
 
                Cell tempCell;
                for (int i = 0; i<3; i++)
                    for(int j = 0; j<3; j++)
                    {
                        tempCell = null;
                        if((tempCell = liveCells.Find(c=> c.X== tempArr[0, i] && c.Y== tempArr[1, j])) != null)
                        {
                            analyzedCells.Add(tempCell);
                        }
                        else
                        {
                            analyzedCells.Add(new Cell(tempArr[0,i], tempArr[1,j]));
                        }
                    }
            }
        }
 
        private int[,] GetCoordinatesSurroundedCells(int x, int y)
        {
            int[,] resArr = new int[2, 3];
 
            // Получение 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;
            }
            return resArr;
        }
 
        public void Analyze()
        {
            nextLiveCells = new List<Cell>(); // "опустошаем список следующих живых клеток"
 
            int [,] coordCell;
            List<Cell> surCell = new List<Cell>();
            foreach(Cell cell in analyzedCells)
            {
                coordCell = GetCoordinatesSurroundedCells(cell.X, cell.Y);
                for (int i = 0; i < 3; i++)
                    for (int j = 0; j < 3; j++)
                    {
                        Cell cell1;
                        if ((cell1 = analyzedCells.Find(c => c.X == coordCell[0, i] && c.Y == coordCell[1, j])) != null)
                            surCell.Add(cell1);
                        else
                            surCell.Add(new Cell(coordCell[0, i], coordCell[1, j]));
                    }
                surCell.RemoveAt(4); // Удаляем сам искомый элемент из списка окружения
 
                int liveNeighb = surCell.FindAll(c => c.LifeState == true).Count;
                if (cell.LifeState) // Если клетка живая
                {
                    // если у живой клетки есть две или три живые соседки, то эта клетка продолжает жить; 
                    // в противном случае (если соседей меньше двух или больше трёх) клетка умирает («от одиночества» или «от перенаселённости»)
                    if (liveNeighb >= 2 && liveNeighb <= 3)
                        nextLiveCells.Add(cell);        
                }
                else // Если клетка мертвая
                {
                    // в пустой (мёртвой) клетке, рядом с которой ровно три живые клетки, зарождается жизнь;
                    if (surCell.FindAll(c => c.LifeState == true).Count == 3)
                    {
                        Cell tempCell = cell;
                        tempCell.Revive();
                        nextLiveCells.Add(tempCell);
                    }
                }    
            }
 
            // на поле не останется ни одной «живой» клетки
            if (nextLiveCells.FindAll(c => c.LifeState == true).Count == 0)
                GameState = false;
 
            // при очередном шаге ни одна из клеток не меняет своего состояния
            if (liveCells == nextLiveCells)
                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 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;
        }
    }
}
Возможно где то неверно. По коду: я храню список живых клеток на каждой итерации их обновляю. Как то так.
Так же пока не проверял данный код, так как без графики, даже не знаю как это сделать))

Добавлено через 48 минут
Был у меня конечно вариант просто сделать кнопками. Но оно на этапе инициализации уже подтормаживало, я преедставляю если это перерисовывать каждый раз

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
<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" ResizeMode="NoResize" HorizontalAlignment="Center" VerticalAlignment="Center">
    <Grid>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="700"></ColumnDefinition>
            <ColumnDefinition ></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>
            <Button Grid.Row="5" Name="btnStart"  Height="25" Width="100"  HorizontalAlignment="Center" Margin=" 0, 5">Старт</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
        private void btnBuildField_Click(object sender, RoutedEventArgs e)
        {
            GameGridField.RowDefinitions.Clear();
            GameGridField.ColumnDefinitions.Clear();
            int WidthSize = int.Parse(tbWidth.Text);
            int 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());
            for (int i = 0; i < HeigthSize; i++)
            {
                for (int j = 0; j < WidthSize; j++)
                {
                    Button el = new Button();
                    Grid.SetColumn(el, j);
                    Grid.SetRow(el, i);
                    el.Background = Brushes.White;
                    GameGridField.Children.Add(el);
                }
            }
 
        }
0
5 / 5 / 0
Регистрация: 22.05.2012
Сообщений: 122
30.09.2016, 23:22  [ТС] 6
Поднимаю вопрос вновь.
Код скинутый мною раньше не работоспособен. Сейчас вроде бы отладил, переделал, код работает как надо. С визуализацией остались проблемы.

Думал все сделать через кнопки. Но при изменении цвета нужных кнопок из списка, не пойму почему не перерисовываются кнопки в окне.

Вот архив с проектом: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
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
30.09.2016, 23:22
Помогаю со студенческими работами здесь

Написание кода игры "Жизнь" для трех точек
Здесь поставлены три точки на местах 5,12 7,14 9,14 dosseg .model tiny .stack 100h .code ...

Как создать клеточное поле для игры "Жизнь"?
Как создать клеточное поле 10 на 10, чтоб оно запускалось при нажатии кнопки старт?

Исходники игры жизнь
у кого есть сие чудо, поделитесь пожалуйста.

Построить криволинейную сетку
Добрый день! Есть 2д фигура, ограниченная уравнениями y=0.5x^2 + 2; y=0.5x^2 - 2; x=2; x=-2 Нужно...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru