原标题:Keener_Tic_Tac_Toe(井字棋游戏)代码(c语言)
遇到的问题:
1.中间有需要清楚键盘缓冲区,具体(?)
2.number char型,强制int型转换是利用ASCII码,相差48.
3.string型c++支持,c并没有,利用char型字符数组解决,char player1[20];scanf("%s",player1);printf("%s",player1);
代码如下:
#include
#include
#include
#include
#include
int main{
//初始化
char another_game = 'Y';
char game[3][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'}};
bool win = true;
int choose_player = 0;
char number = '0';
int row = 0 , col = 0;
bool take_turns = false;
char player1[20],player2[20];
int c;
//循环_1
do{
//初始化游戏
printf("井字棋游戏初始化...\n");
char game[3][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'}};
win = false;
//输入玩家1,2姓名
printf("(不要使用空格,回车键结束)\n");
printf("请输入玩家1姓名:\n");
scanf("%s",player1);
printf("请输入玩家2姓名:\n");
scanf("%s",player2);
//随机选择先落子玩家
srand((unsigned)time(NULL));
choose_player = rand%2 + 1;
if(choose_player == 1){
take_turns = true;
printf("%s(玩家1)首先落子(1~9).\n",player1);
}else{
take_turns = false;
printf("%s(玩家2)首先落子(1~9).\n",player2);
}
//循环_2
while(!win){
//输出3x3游戏格
printf("\n");
printf(" %c | %c | %c \n",game[0][0],game[0][1],game[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n",game[1][0],game[1][1],game[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n",game[2][0],game[2][1],game[2][2]);
printf("\n");
//玩家1,玩家2分别下棋
//落子是否有效
do{
printf("%s落子:",take_turns?player1:player2);
//这里需要清楚缓冲区(why?)
if(feof(stdin) || ferror(stdin)){
break;
}
while((c = getchar) != '\n' && c != EOF);
scanf("%c",&number);
//why:ASCII码表对应的数字差48~
row = ((int)number-48-1)/3;
col = ((int)number-48-1)%3;
//printf("%d.%d.%c.\n",row,col,game[row][col]);
//printf("%c\n",number);
}while( game[row][col] != number);
//更新棋盘
if(take_turns){
game[row][col] = 'X';
}else{
game[row][col] = 'O';
}
//循环_2,判定:是否有人胜利
if((game[0][0] == game[0][1] && game[0][1] == game[0][2])||
(game[1][0] == game[1][1] && game[1][1] == game[1][2])||
(game[2][0] == game[2][1] && game[2][1] == game[2][2])||
(game[0][0] == game[1][0] && game[1][0] == game[2][0])||
(game[0][1] == game[1][1] && game[1][1] == game[2][1])||
(game[0][2] == game[1][2] && game[1][2] == game[2][2])||
(game[0][0] == game[1][1] && game[1][1] == game[2][2])||
(game[0][2] == game[1][1] && game[1][1] == game[2][0])
){
win = true;
printf("%s胜利!游戏结束.",take_turns?player1:player2);
printf("\n");
printf(" %c | %c | %c \n",game[0][0],game[0][1],game[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n",game[1][0],game[1][1],game[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n",game[2][0],game[2][1],game[2][2]);
printf("\n");
}else{
if(take_turns){
take_turns = false;
}else{
take_turns = true;
};
}
}
//循环_1,是否开始新游戏
if(feof(stdin) || ferror(stdin)){
break;
}
while((c = getchar) != '\n' && c != EOF);
printf("是否开始新游戏?(y/n)");
scanf("%c",&another_game);
}while(toupper(another_game)=='Y');
//结束
return 0;
}
作者:LNZ001
原文:https://blog.csdn.net/LNZ001/article/details/54780728
责任编辑: