C语言实现生命游戏

使用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);
}
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值