找回密码
 注册
查看: 643|回复: 3

帮忙找找原因

[复制链接]
发表于 2003-8-5 17:00:23 | 显示全部楼层 |阅读模式
/*A simple Tic Tac Toe game.*/
#include<stdio.h>
#include<stdlib.h>

char matrix[3][3];/*the tic toe matric*/

char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);

int main(void)
{
  char done;

  printf("This is the game of Tic Tac Toe.");
  printf("You will be playing against the computer.\n");

  done=' ';
  init_matrix();

  do{
     disp_matrix();
     get_player_move();
     done=check();/*see if winner*/
     if(done!=' ')break;/*winner!*/
     get_computer_move();
     done=check();/*see if winner*/
   }while(done==' ');

   if(done=='X')printf("You won! \n");
   else printf("I won!!!! \n");
   disp_matrix();/*show final positions*/

   return 0;
}

/* Initialize the matrix.*/
void init_matrix(void)
{
  int i,j;
  for(i=0;i<3;i++)
  for(j=0;j<3;j++)matrix[j]=' ';
}

/*Get a player's move.*/
void get_player_move(void)
{
  int x,y;

  printf("Enter X,Y coordinates for your move:");
  scanf("%d% * c%d",&x,&y);

  x--;y--;

  if(matrix[x][y]!= ' '){
    printf("Invalid move,try again.\n");
    get_player_move();
  }
  else matrix[x][y]='X';
}

/* Get a move from the computer.*/
void get_computer_move(void)
{
  int i,j;
  for(i=0;i<3;i++){
    for(j=0;j<3;j++)
      if(matrix[j]==' ')break;
    if(matrix[j]==' ')break;
  }

  if(i*j==9){
    printf("draw\n");
    exit(0);
   }
  else
    matrix[j]='O';
}

/* Display the matrix on the screen.*/
void disp_matrix(void)
{
  int t;

  for(t=0;t<3;t++){
    printf("%c | %c | %c",matrix[t][0],
        matrix[t][1],matrix[t][2]);
    if(t!=2)printf("\n---|---|---\n");
  }
  printf("\n");
}

/*See if there is a winner.*/
char check(void)
{
  int i;

  for(i=0;i<3;i++)/*check rows */
    if(matrix[0]==matrix[1]&&
       matrix[0]==matrix[2])
         return matrix[0];

  for(i=0;i<3;i++)/*check columns*/
    if(matrix[0]==matrix[1]&&
       matrix[0]==matrix[2])
         return matrix[0];

   /*test diagonals*/
   if(matrix[0][0]==matrix[1][1]&&
      matrix[1][1]==matrix[2][2])
        return matrix[0][0];

   if(matrix[0][2]==matrix[1][1]&&
      matrix[1][1]==matrix[2][0])
        return matrix[0][2];

   return ' ';
}


get_player_move();此函数能通过编译,但会出现奇怪的循环,并终止程序运行,出现莫名其妙的结果。
大家能帮我找找原因吗?
发表于 2003-8-5 17:48:32 | 显示全部楼层
你的输入方法也太...烂了吧
可想的就是用户输入一个不规范的字符 然后计算位置那里就完全不对了
也没有判断的阿?
对了 提醒一下 这样的方式是得不到y的 只能得到x (由于行缓冲之类的问题)
回复

使用道具 举报

发表于 2003-8-5 17:50:33 | 显示全部楼层
if(matrix[x][y]= ' '){
=======>
if(matrix[x][y]== ' '){
少了一个=吧
回复

使用道具 举报

发表于 2003-8-6 08:17:23 | 显示全部楼层
if(matrix[x][y]= ' '){
printf("Invalid move,try again.\n");
get_player_move();
}
else matrix[x][y]='X';
}

应该是!=吧
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2025-8-11 12:04 , Processed in 0.021896 second(s), 16 queries .

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表