我正在用 C 编写一个井字游戏。这是逻辑。用户先走,选择一个插槽。使用简单的公式计算槽的位置。然后填充选定的插槽。接下来,计算机随机选择一个插槽。为此,我在 stdlib.h 中使用了 rand() 函数。最初,3x3 矩阵的所有元素都设置为 0。我的问题是,即使所有其他元素都是 0,并且用户选择插槽 5 或插槽 9,用户也会获胜。comp 也一样。这是我的代码-
#include<stdio.h>
#include<stdlib.h>
int check(int[][3]);
void print(int[][3]);
main()
{
int i,j,match[3][3]={0},posx,posy,comp_posx,comp_posy,fill=0,slot,user_score=0,comp_score=0;
char ch;
srand(time(NULL));
do
{
while(fill<9)
{
printf("\nEnter the slot you want to fill.\n");
scanf("%d",&slot);
if (slot > 9)
{
printf("Error!\nSlot value cannot exceed 9.\n");
continue;
}
else if( slot >= 1&&slot <=3)
{
posx=0;
posy=slot-1;
}
else if (slot >= 4 && slot <= 6)
{
posx=1;
posy=slot-4;
}
else
{
posx=2;
posy=slot-7;
}
if (match[posx][posy] == 0)
{
match[posx][posy]=1;
fill++;
check(match);
if(check(match)==1)
{
printf("The user wins!\n");
user_score++;
print(match);
break;
}
else if(check(match)==-1)
{
printf("The computer wins!\n");
comp_score++;
print(match);
}
else
{
if(fill==9)
{
printf("It's a draw!\n");
print(match);
break;
}
else
{
printf(" ");
}
}
}
else
{
printf("Sorry! This slot is already filled.\nPlease pick another slot.\n");
continue;
}
label:
comp_posx=rand()%3;
comp_posy=rand()%3;
if(match[comp_posx][comp_posy]==0)
{
match[comp_posx][comp_posy]=-1;
fill++;
check(match);
if (check(match)==1)
{
printf("The user wins!\n");
user_score++;
print(match);
break;
}
else if(check(match)==-1)
{
printf("The computer wins!\n");
comp_score++;
print(match);
break;
}
else
{
if (fill==9)
{
printf("It's a draw!\n");
print(match);
break;
}
else
{
printf(" ");
}
}
}
else
goto label;
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
{
printf("%d\t",match[i][j]);
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
match[i][j]=0;
}
}
printf("Continue? Y/N\n");
scanf("%c %c",&ch,&ch);
}
while(ch=='y'||ch=='Y');
printf("FINAL SCORES>>\nUser=%d\nComputer=%d\n",user_score,comp_score);
}
int check(int match[][3])
{
int i,j;
if( match[2][0]==match[1][1] && match[1][1]==match[0][2] )
{
if (match[0][2]==1)
return 1;
else if (match[0][2]==-1)
return -1;
else
printf(" ");
}
for(i=0;i<3;i++)
{
if (match[i][0]==match[i][1]&&match[i][1]==match[i][2])
{
if(match[i][1]==1)
return 1;
else if(match[i][1]==-1)
return -1;
else
continue;
}
}
for(j=0;j<3;j++)
{
if(match[0][j]==match[1][j]&&match[0][j]==match[2][j])
{
if (match[0][j]==1)
return 1;
else if(match[0][j]==-1)
return -1;
else
continue;
}
}
for (i=0;i<1;i++)
{
if(match[i][i]==match[i+1][i+1]&&match[i][i]==match[i+2][i+2])
{
if (match[i][i]==1)
return 1;
else if (match[i][i]==-1) return -1;
else continue;
}
}
}
void print(int match[][3])
{
int i,j;
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
{
printf("%d\t",match[i][j]);
}
}
}
您能否建议更改代码,以便我不会遇到这些问题?