进行了几个函数的拆分,分为初始化,显示,是否选择继续,相邻格子存活个数和更新代数几个部分,但运行时主函数每次运行到初始化startup()处便停止了,也无法进行输入,这是为什么?
行和列用作全局变量。codeblocks编程
#include <stdio.h>
#include <stdlib.h>
#define Height 20
#define Width 60
int grid[Height+2][Width+2];
int newgrid[Height+2][Width+2];
int Count[Height+2][Width+2];
int row,col;
void startup(){
for(row=0;row<=Width+1;row++){
for(col=0;col<=Height+1;col++){
grid[row][col]=0;}}
printf("List the coordinates for living cells.\nTerminate the list with the special pair -1 -1\n");
scanf("%d %d",&row,&col);
while(row!=-1||col!=-1){
if(row>=1&&row<=Width){
if(col>=1&&col<=Height)
grid[row][col]=1;
else printf("column %d is out of range.\n",col);}
else printf("row %d is out of range.\n",row);
scanf("%d %d",&row,&col);
}
}
void show(){
printf("The current life generation is:\n");
for(row=1;row<=Width;row++){
for(col=1;col<=Height;col++){
if(grid[row][col]=1)printf("*");
else printf("-");}
printf("\n");
}
printf("\n");
}
int yes_or_no(){
char ans;
printf("Continue viewing new generations?\n(y,n)?");
scanf("%c",&ans);
while(ans!='y'||'Y'||'n'||'N'){
printf("respond with either y or n:\n");
scanf("%c",&ans);}
if(ans=='y'||'Y')return 1;
else return 0;
}
void neighbor_count(){
int i,j;
int count=0;
for(row=1;row<=Width+1;row++){
for(col=1;col<=Height+1;col++){
for(i=row-1;i<=row+1;i++)
for(j=col-1;col+1;j++)
count+=grid[i][j];
count-=grid[i][j];
Count[row][col]=count;}}
}
void update(){
for(row=1;row<=Width;row++)
for(col=1;col<=Height;col++)
switch(Count[row][col]){
case 2:
newgrid[row][col]=grid[row][col];break;
case 3:
newgrid[row][col]=1;break;
default:
newgrid[row][col]=0;break;
}
for(row=1;row<=Width+1;row++)
for(col=1;col<=Height+1;col++)
grid[row][col]=newgrid[row][col];
}
int main(){
printf("Welcome to Conway's game of Life.\nThis game uses a grid of size 20 by 60 in which\neach cell can either be occupied by an organism or not.\n");
printf("The occupied cells change from generation to generation\naccording to the number of neighboring cells which are alive.\nList the coordinates for living cells.\nTerminate the list with the special pair -1 -1\n");
startup();
show();
while(yes_or_no()){
neighbor_count();
update();
show();
yes_or_no();}
return 0;
}