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
|
// Life.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <ctime>
using namespace std;
void generation(char[][20], int);
void neighbors(char[][20], int);
void display(char[][20], char[][20], int, int);
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
char board[70][20];
char s[2][2];
srand(time(NULL));
generation(board, 70);
system("pause");
return 0;
}
void generation (char board[][20], int size)
{
int number;
for (int x = 0; x < 20; x++) //initial configuration
{
for (int y = 0; y < 70; y++)
{
board[y][x] = ' ';
board[34][10] = 'X';
board[35][10] = 'X';
board[36][10] = 'X';
board[19][6] = 'X';
board[20][6] = 'X';
board[21][6] = 'X';
board[49][6] = 'X';
board[50][6] = 'X';
board[51][6] = 'X';
}
}
neighbors(board, 70);
}
void neighbors(char board[][20], int size)
{
char newBoard[70][20];
int nCount = 0;
int z = 0;
/*
Rules:
1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overcrowding.
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
*/
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 70; y++)
{
newBoard[y][x] = board[y][x];
//count neighbors
if (newBoard[y-1][x-1] == 'X') nCount += 1;
if (newBoard[y-1][x] == 'X') nCount += 1;
if (newBoard[y-1][x+1] == 'X') nCount += 1;
if (newBoard[y][x-1] == 'X') nCount += 1;
if (newBoard[y][x+1] == 'X') nCount += 1;
if (newBoard[y+1][x-1] == 'X') nCount += 1;
if (newBoard[y+1][x] == 'X') nCount += 1;
if (newBoard[y+1][x+1] == 'X') nCount += 1;
if (newBoard[y][x] == 'X' && nCount < 2) //rule 1
newBoard[y][x] = ' ';
else if (newBoard[y][x] == 'X' && nCount > 3) //rule 3
newBoard[y][x] = ' ';
else if (newBoard[y][x] == 'X' && (nCount == 2 || nCount == 3)) //rule 2
newBoard[y][x] = 'X';
else if (newBoard[y][x] == ' ' && nCount == 3) //rule 4
newBoard[y][x] = 'X';
}
}
cout << nCount << endl;
do
{
display(board, newBoard, 70, z);
z++;
system("pause");
system("cls");
} while(z < 50);
}
void display(char board[][20], char newBoard[][20], int size, int z)
{
if (z == 0)
{
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 70; y++)
{
cout << board[y][x];
}
cout << endl;
}
}
else
{
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 70; y++)
{
cout << newBoard[y][x];
}
cout << endl;
}
}
cout << endl;
}
|