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

Игра жизнь (бесконечное пространство)

18.06.2016, 14:15. Показов 6356. Ответов 5
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Надо сделать бесконечное пространство для игры "жизнь", примерно понимаю как это сделать, но что то не получается,надо в подпрограмму rules добавить правила для клеток, которые находятся по сторонам.Н
Кликните здесь для просмотра всего текста
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
#include <iostream>
#include <time.h>
#include <conio.h>
#include <windows.h>
 
using namespace std;
 
void world(int array[25][100]) {
    for(int j = 1; j < 25; j++) {
        for(int i = 1; i < 100; i++) {
            if(array[j][i] == 1)
                cout << '*';
            else
                cout << ' ';
        }
        cout << endl;
    }
}
 
void copy(int array1[25][100], int array2[100][100]) {
    for(int j = 0; j < 25; j++) {
        for(int i = 0; i < 100; i++)
            array2[j][i] = array1[j][i];
    }
}
 
void rules(int array[25][100], char choice) {
    int temp[25][100];
    copy(array, temp);
    for(int j = 1; j < 25; j++) {
        for(int i = 1; i < 100; i++) {
            int count = 0;
            count = array[j-1][i] +
                    array[j-1][i-1] +
                    array[j][i-1] +
                    array[j+1][i-1] +
                    array[j+1][i] +
                    array[j+1][i+1] +
                    array[j][i+1] +
                    array[j-1][i+1];
            if(count < 2 || count > 3)
                temp[j][i] = 0;
            if(count == 2)
                temp[j][i] = array[j][i];
            if(count == 3)
                temp[j][i] = 1;
        }
    }
    copy(temp, array);
}
 
int main() {
    setlocale(LC_ALL, "Russian");
    int fgen[25][100];
    int gen[25][100];
    char ncells;
    char count;
    bool paused;
    int g;
    int c = 100;
 
    system("CLS");
    system("color 5");
    int i = 0;
    srand(time(NULL));
    for(int j = 1; j < 25; j++) {
        for (int i = 1; i < 100; i++)
            fgen[j][i] = rand() % 2;
    }
 
    do {
        if (!paused) {
            system("CLS");
            if(i == 0)
                copy(fgen, gen);
            world(gen);
            rules(gen, ncells);
            i++;
        }
        if (kbhit())
            g = getch();
        if(GetAsyncKeyState(VK_SPACE)) {
            paused = !paused;
        }
        if(GetAsyncKeyState(VK_UP)) {
            c = c+50;
        }
        if(GetAsyncKeyState(VK_DOWN)) {
            c = c-50;
            if (c<0) {
                c = c+50;
            }
        }
        Sleep(c);
    } while(g != 27);
 
    return 0;
}


Добавлено через 23 часа 43 минуты
спасибо/
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
18.06.2016, 14:15
Ответы с готовыми решениями:

Игра жизнь
Нужно написать игру &quot;Жизнь&quot; простым кодом. Только начал изучать c++

игра жизнь
содержимое life.cpp// Life.cpp: определяет точку входа для консольного приложения. // #include...

Игра Жизнь
Ну, правила игры таковы: - если клетка пустая но имеет ровно 3 соседа (вообще их 8), там...

Игра Жизнь
Написал вот такую реализацию: #include &quot;stdafx.h&quot; #include &quot;iostream&quot; #include &quot;clocale&quot; ...

5
Эксперт С++
3224 / 1751 / 436
Регистрация: 03.05.2010
Сообщений: 3,867
18.06.2016, 21:36 2
Лучший ответ Сообщение было отмечено AlphaOmega как решение

Решение

Цитата Сообщение от AlphaOmega Посмотреть сообщение
спасибо/
Да завсегда!
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//сделать бесконечное пространство для игры "жизнь"
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <set>
#include <utility>
#include <windows.h>
///////////////////////////////////////////////////////////////////////////////
struct  T_cell
{
    //-------------------------------------------------------------------------
    using   T_cells     =   std::set< T_cell >;
    //-------------------------------------------------------------------------
    int     x_;
    int     y_;
    //-------------------------------------------------------------------------
    T_cell
        (
            int     x,
            int     y
        )
        :
        x_(x),
        y_(y)
    {}
    //-------------------------------------------------------------------------
    T_cell  operator-   ( T_cell    cell )                                  const
    {
        return  T_cell  (
                            x_  -   cell.x_,
                            y_  -   cell.y_
                        );
    }
    //-------------------------------------------------------------------------
    bool    operator<   ( T_cell    cell )                                  const
    {
        return      std::make_pair( x_,         y_      )
                <   std::make_pair( cell.x_,    cell.y_ );
    }
    //-------------------------------------------------------------------------
    T_cells     get_cell_and_its_adjacent()                                 const
    {
        T_cells     res;
 
        for (
                int
                i   =   x_  -   1;
                i   <=  x_  +   1;
                ++i
            )
        {
            for (
                    int
                    j   =   y_  -   1;
                    j   <=  y_  +   1;
                    ++j
                )
            {
                res.insert  (
                                T_cell(i, j)
                            );
            }//for
        }//for
 
        return  res;
    }
    //-------------------------------------------------------------------------
    int     adjacent_count_in( T_cells  const   &   cells )                 const
    {
        int     res{};
 
        for (
                int
                i   =   x_  -   1;
                i   <=  x_  +   1;
                ++i
            )
        {
            for (
                    int
                    j   =   y_  -   1;
                    j   <=  y_  +   1;
                    ++j
                )
            {
                auto    cell_cur    =   T_cell(i, j);
 
                if  (
                                cell_cur
                            !=  *this
 
                        &&  cells.count( cell_cur )
                    )
                {
                    ++res;
                }
            }//for
        }//for
 
        return  res;
    }
    //-------------------------------------------------------------------------
    bool    operator!=  ( T_cell    cell )                                  const
    {
        return      *this   <   cell
                ||  cell    <   *this;
    }
    //-------------------------------------------------------------------------
    bool    operator==  ( T_cell    cell )                                  const
    {
        return  !( *this != cell );
    }
    //-------------------------------------------------------------------------
};
///////////////////////////////////////////////////////////////////////////////
typedef T_cell::T_cells     T_cells;
///////////////////////////////////////////////////////////////////////////////
class   T_life
{
    //-------------------------------------------------------------------------
    T_cell      center_pos_;
    T_cells     cells_;
    //-------------------------------------------------------------------------
public:
    //-------------------------------------------------------------------------
    T_life()
        :
        center_pos_( 0, 0 )
    {}
    //-------------------------------------------------------------------------
    void    play()
    {
        generate_cells();
 
        while   (
                    !cells_.empty()
                )
        {
            auto    cells_old   =   cells_;
 
            print_and_shift     ();
            make_life_step      ();
 
            if  (
                        cells_
                    ==  cells_old
                )
            {
                std::cout   <<  "Game fixated. Press Enter."
                            <<  std::endl;
 
                return;
            }//if
        }//while
 
        std::cout   <<  "All cells died.  Press Enter."
                    <<  std::endl;
    }
    //-------------------------------------------------------------------------
private:
    //-------------------------------------------------------------------------
    void    generate_cells()
    {
        for( int  i{}; i < 4; ++i )
        {
            for( int  j{}; j < 4; ++j )
            {
                if  (
                        rand()  %   3
                    )
                {
                    cells_.insert
                        (
                            T_cell(i, j)
                        );
                }
            }//for
        }//for
    }
    //-------------------------------------------------------------------------
    void    print_and_shift()
    {
        const   int     SHORT_MIN   =   -0x7fff;
 
        for(;;)
        {
            system          ("CLS");
            print_cells     ();
 
            std::cout   <<  "Press arrow keys or SPACEBAR."
                        <<  std::endl;
 
            for(;;)
            {
                if  (
                        GetAsyncKeyState( VK_UP )   ==  SHORT_MIN
                    )
                {
                    --center_pos_.x_;
                    break;
                }
 
                if  (
                        GetAsyncKeyState( VK_DOWN )     ==  SHORT_MIN
                    )
                {
                    ++center_pos_.x_;
                    break;
                }
 
                if  (
                        GetAsyncKeyState( VK_LEFT )     ==  SHORT_MIN
                    )
                {
                    --center_pos_.y_;
                    break;
                }
 
                if  (
                        GetAsyncKeyState( VK_RIGHT )    ==  SHORT_MIN
                    )
                {
                    ++center_pos_.y_;
                    break;
                }
 
                if  (
                        GetAsyncKeyState( VK_SPACE )    ==  SHORT_MIN
                    )
                {
                    return;
                }
            }//for
        }//for
    }
    //-------------------------------------------------------------------------
    void    print_cells()                                                   const
    {
        for( int  i{-11}; i < 13; ++i )
        {
            for( int  j{-18}; j < 21; ++j )
            {
                bool    to_show     =   cells_.count
                                            (
                                                T_cell(i, j)    -   center_pos_
                                            );
 
                std::cout   <<  (
                                    to_show
                                        ?   '*'
                                        :   ' '
                                )
 
                            <<  ' ';
            }//for
 
            std::cout   <<  std::endl;
        }//for
    }
    //-------------------------------------------------------------------------
    void    make_life_step()
    {
        T_cells     cells_and_their_adjacent    =   get_cells_and_their_adjacent();
        T_cells     new_cells;
 
        copy_with_rules
            (
                cells_and_their_adjacent,
                new_cells
            );
 
        std::swap
            (
                new_cells,
                cells_
            );
    }
    //-------------------------------------------------------------------------
    T_cells     get_cells_and_their_adjacent()                              const
    {
        T_cells     res;
 
        for( auto   cell    :   cells_ )
        {
            auto    cell_and_its_adjacent  =   cell.get_cell_and_its_adjacent();
 
            res.insert
                (
                    cell_and_its_adjacent.begin    (),
                    cell_and_its_adjacent.end      ()
                );
        }//for
 
        return  res;
    }
    //-------------------------------------------------------------------------
    void    copy_with_rules
        (
            T_cells     const   &   cells,
            T_cells             &   new_cells
        )                                                                   const
    {
        for( auto   cell    :   cells )
        {
            switch  (
                        cell.adjacent_count_in( cells_ )
                    )
            {
            case    2   :
                if  (
                        cells_.count( cell )
                    )
                {
                    new_cells.insert( cell );
                }
                break;
 
            case    3   :
                new_cells.insert( cell );
                break;
 
            default     :
                break;
            }//switch
        }//for
    }
    //-------------------------------------------------------------------------
};
///////////////////////////////////////////////////////////////////////////////
int     main()
{
    std::ios::sync_with_stdio( false );
    srand(unsigned(time(0)));
    T_life  life;
    life.play();
}

Добавлено через 20 минут
Занятные-таки картинки сочиняет! Вот одна из них:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
           *           *
           *           *
           * *       * *
 
   * * *     * *   * *     * * *
       *   *   *   *   *   *
           * *       * *
 
           * *       * *
       *   *   *   *   *   *
   * * *     * *   * *     * * *
 
           * *       * *
           *           *
           *           *
Добавлено через 1 час 0 минут
2
rikimaru2013
18.06.2016, 21:51
  #3

Не по теме:

даже шутить не буду, что вы кодом такие же занятные сочиняете :wizard:

0
Эксперт С++
3224 / 1751 / 436
Регистрация: 03.05.2010
Сообщений: 3,867
18.06.2016, 22:48 4
Цитата Сообщение от rikimaru2013 Посмотреть сообщение
даже шутить не буду, что вы кодом такие же занятные сочиняете
Так это жэ Жызнь!
0
4817 / 2278 / 287
Регистрация: 01.03.2013
Сообщений: 5,947
Записей в блоге: 28
19.06.2016, 00:48 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
#include <iostream>
 
const int n=19, m=20, N=n*m; bool a[N], b[N];
 
bool get(bool *a, int i, int j) { return a[(i+n)%n*n + (j+m)%m]; }
 
int neibs(bool *a, int i, int j) {
    int r = 0;
    for(int p=-1; p<=1; p++) for(int q=-1; q<=1; q++) r += get(a, i+p, j+q);
    return r - get(a, i, j);
}
void show(bool *a) {    
    for(int k=0; k<N; k++) std::cout<<(a[k] ? '@' : '-')<<((k+1)%n ? ' ' : '\n');}
 
void go(bool *a, bool *b, int c) {    
    for(int i=0; i<=c; i++) {
        std::cout << "generation " << i << ":\n"; show(a); std::cout<<'\n';
        for(int k=0; k<N; k++) {
            int s = neibs(a, k/n, k%n);
            b[k] = !a[k] && s==3 ? 1 : a[k] && (s<2 || s>3) ? 0 : a[k];
        }
        bool *t=a; a=b; b=t;
    }
}
int main() { for(int i=6; i<=13; i++) a[i*n+n/2]=1; go(a, b, 50); }
http://rextester.com/BVIONU61927
0
0 / 0 / 0
Регистрация: 17.06.2016
Сообщений: 2
19.06.2016, 12:28  [ТС] 6
спасибо еще раз кто хоть как то отписался, но уже сам дошел до решения
вот код подпрограммы кому интересно
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
void rules(int array[25][100], char choice) {
    int temp[25][100];
    copy(array, temp);
    for(int j = 0; j < 25; j++) {
        for(int i = 0; i < 100; i++) {
            int count = 0;
            if (j>0 && j<24 && i>0 && i<99) {
                count = array[j-1][i] +
                        array[j-1][i-1] +
                        array[j][i-1] +
                        array[j+1][i-1] +
                        array[j+1][i] +
                        array[j+1][i+1] +
                        array[j][i+1] +
                        array[j-1][i+1];
                if(count < 2 || count > 3)
                    temp[j][i] = 0;
                if(count == 2)
                    temp[j][i] = array[j][i];
                if(count == 3)
                    temp[j][i] = 1;
            } else {
                if (j>0 && j<24 && i == 0) {
                    count = array[j][99] +
                            array[j+1][99] +
                            array[j-1][99] +
                            array[j][i+1] +
                            array[j+1][i+1] +
                            array[j-1][i+1] +
                            array[j-1][i] +
                            array[j+1][i];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j == 0 && i>0 && i<99) {
                    count = array[24][i+1] +
                            array[24][i] +
                            array[24][i-1] +
                            array[j][i+1] +
                            array[j+1][i+1] +
                            array[j+1][i-1] +
                            array[j][i-1] +
                            array[j+1][i];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j == 24 && i>0 && i<99) {
                    count = array[0][i+1] +
                            array[0][i] +
                            array[0][i-1] +
                            array[j][i+1] +
                            array[j-1][i+1] +
                            array[j-1][i-1] +
                            array[j][i-1] +
                            array[j-1][i];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j>0 && j<24 && i == 99) {
                    count = array[j][0] +
                            array[j+1][0] +
                            array[j-1][0] +
                            array[j][i-1] +
                            array[j+1][i-1] +
                            array[j-1][i-1] +
                            array[j+1][i] +
                            array[j-1][i];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j == 0 && i == 0) {
                    count = array[j][i+1] +
                            array[j-1][i+1] +
                            array[j-1][i] +
                            array[j][99] +
                            array[j+1][99] +
                            array[24][i+1] +
                            array[24][i] +
                            array[24][99];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j == 0 && i == 99) {
                    count = array[j][i-1] +
                            array[j-1][i-1] +
                            array[j+1][i] +
                            array[j][99] +
                            array[j-1][99] +
                            array[0][i-1] +
                            array[0][i] +
                            array[24][0];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j == 24 && i == 99) {
                    count = array[j][i-1] +
                            array[j-1][i-1] +
                            array[j-1][i] +
                            array[j][0] +
                            array[j-1][0] +
                            array[99][i-1] +
                            array[99][i] +
                            array[0][0];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
                if (j == 24 && i == 0) {
                    count = array[j][i+1] +
                            array[j-1][i+1] +
                            array[j-1][i] +
                            array[j][99] +
                            array[j-1][99] +
                            array[0][i+1] +
                            array[0][i] +
                            array[0][99];
                    if(count < 2 || count > 3)
                        temp[j][i] = 0;
                    if(count == 2)
                        temp[j][i] = array[j][i];
                    if(count == 3)
                        temp[j][i] = 1;
                }
            }
        }
    }
    copy(temp, array);
}
0
19.06.2016, 12:28
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
19.06.2016, 12:28
Помогаю со студенческими работами здесь

Игра в жизнь Конвей
Чего то я намудрил помогите разобраться пожалуйста #include&lt;math.h&gt; #include &lt;time.h&gt; #include...

Игра ( Жизнь Конвея)
Написал код - но во время запуска игра вылетает! Вот исходники, подскажите, что не так?

Игра "жизнь" - глайдер ведет себя не так, как надо
Добрый вечер. Нужно написать игру &quot;жизнь&quot;. Реализовал,однако глайдер ведет себя не так,как надо....

Игра "Жизнь"; Нужно, чтобы первое поколение задавалось оператором (с клавиатуры)
Нужна помощь с решением задачи &quot;Жизнь&quot; на с++ Есть код программы, которая задает первое поколение...


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

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

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