我正在用 ANSI C 构建生命游戏的一个版本,并且我已经为它编写了几乎所有的代码。
我的 C 源文件:
#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 32
#define WIDTH 32
#define COMPASS 8
#define SPACE '.'
unsigned long mask = 0x80000000;
unsigned long neighbours[COMPASS] = { 0 };
unsigned long row[WIDTH] = { 0 };
unsigned long copy[WIDTH] = { 0 };
int northWest(unsigned long row, int rowNum) {
copy[rowNum - 1] = row >>= 1;
return copy[rowNum - 1];
}
int north(unsigned long row, int rowNum) {
copy[rowNum - 1] = row;
return copy[rowNum - 1];
}
int northEast(unsigned long row, int rowNum) {
copy[rowNum - 1] = row <<= 1;
return copy[rowNum - 1];
}
int west(unsigned long row, int rowNum) {
copy[rowNum] = row >>= 1;
return copy[rowNum];
}
int east(unsigned long row, int rowNum) {
copy[rowNum] = row <<= 1;
return copy[rowNum];
}
int southWest(unsigned long row, int rowNum) {
copy[rowNum + 1] = row >>= 1;
return copy[rowNum + 1];
}
int south(unsigned long row, int rowNum) {
copy[rowNum + 1] = row;
return copy[rowNum + 1];
}
int southEast(unsigned long row, int rowNum) {
copy[rowNum + 1] = row <<= 1;
return copy[rowNum + 1];
}
/*void clearRows(unsigned long row[]) {
int i;
system("clear");
for (i = 0; i < HEIGHT; ++i) {
row[i] = 0;
}
}*/
void displayBinary(unsigned long x) {
int bit;
int mask;
for (bit = 0; bit < HEIGHT; ++bit) {
mask = 1 << bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}
int main(void) {
int i, alive;
char ch;
unsigned long init32;
srand(time(NULL));
for (i = 0; i < HEIGHT; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
do {
system("clear");
for (i = 0; i < HEIGHT; ++i) {
neighbours[0] = north(row[i], i);
neighbours[1] = south(row[i], i);
neighbours[2] = west(row[i], i);
neighbours[3] = east(row[i], i);
neighbours[4] = northWest(row[i], i);
neighbours[5] = northEast(row[i], i);
neighbours[6] = southEast(row[i], i);
neighbours[7] = southWest(row[i], i);
}
for (i = 0; i < HEIGHT; ++i) {
alive += ((mask & neighbours[i]) ? 1 : 0);
displayBinary(row[i]);
}
} while ((ch = getchar()) != 'n');
return EXIT_SUCCESS;
}
我的目标是在 32x32 板上打印随机的“X”字符,只要用户不输入“n”,程序就会循环。对于每个循环迭代,我希望每个坐标检查它的邻居,如果它的邻居少于两个或多于三个,则“死亡”。否则,它会“存活”并在该坐标处打印一个“X”。
我知道使用按位与可能不是完成此操作的最佳方法,但我的教授要求我们使用按位与,因此我无法更改该逻辑。
我无法清除循环之间的行。有人可以帮我弄清楚如何为 do 循环的每次迭代打印更新的行吗?
任何帮助深表感谢。谢谢你。