使用C语言实现生命的游戏
屏幕上的*将模拟细胞,在周围有3个细胞的时候,将产生新的细胞,如果是两个,就保持不变,其他情况下,细胞将会死亡,系统将随机生成细胞的位置,看看最终的细胞历程吧
windows系统下实现
代码如下:
game.h:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#define HIGH 40
#define WIDTH 70
void DataInit();
void Show();
void UpdateWithoutInput();
void gotoxy(int x, int y);
test.cpp
#include "game.h"
int main()
{
DataInit(); //数据初始化
while (1)
{
Show(); //显示画面
UpdateWithoutInput(); //与用户无关的数据更新
}
return 0;
}
game.cpp:
#include "game.h"
int cells[HIGH][WIDTH];
void DataInit()
{
int i = 0, j = 0;
for (i = 0; i < HIGH; i++)
{
for (j = 0; j < WIDTH; j++)
{
cells[i][j] = rand() % 2;
}
}
}
void Show()
{
gotoxy(0, 0);
int i, j;
for (i = 1; i < HIGH - 1; i++)
{
for (j = 1; j < WIDTH - 1; j++)
{
if (cells[i][j] == 1)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
Sleep(300);
}
void UpdateWithoutInput()
{
int NewCells[HIGH][WIDTH];
int i = 0, j = 0;
int NeighbourNember = 0;
for (i = 1; i < HIGH - 1; i++)
{
for (j = 1; j < WIDTH - 1; j++)
{
NeighbourNember = cells[i - 1][j - 1] + cells[i - 1][j] + cells[i - 1][j + 1]
+ cells[i][j - 1] + cells[i][j] + cells[i][j + 1]
+ cells[i + 1][j - 1] + cells[i + 1][j] + cells[i + 1][j + 1];
if (NeighbourNember == 3)
{
NewCells[i][j] = 1;
}
else if (NewCells[i][j] == 2)
{
NewCells[i][j] = cells[i][j];
}
else
{
NewCells[i][j] = 0;
}
}
NeighbourNember = 0;
}
for (i = 1; i < HIGH - 1; i++)
{
for (j = 1; j < WIDTH - 1; j++)
{
cells[i][j] = NewCells[i][j];
}
}
}
fix.cpp:
该文件用于修复闪屏
#include "game.h"
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}