C语言简单实现一个9宫格的井子格游戏,任意一方完成三连即获胜!
int winner = 0; int player = 0; int col = 0; int row = 0; int choice = 0; char board[3][3] = { {‘1‘,‘2‘,‘3‘}, {‘4‘,‘5‘,‘6‘}, {‘7‘,‘8‘,‘9‘} }; for (int i = 0; i < 9 && winner == 0; i++) { printf("\n\n"); printf(" %c | %c | %c \n",board[0][0],board[0][1],board[0][2]); printf("---+---+---\n"); printf(" %c | %c | %c \n",board[1][0],board[1][1],board[1][2]); printf("---+---+---\n"); printf(" %c | %c | %c \n",board[2][0],board[2][1],board[2][2]); player = i % 2 + 1; do { printf("玩家%d请输入你要选择的位置来放置%c:",player,(player == 1)?‘X‘:‘Z‘); scanf("%d",&choice); col = --choice % 3; row = choice / 3; } while (choice < 0 || choice > 8 || board[row][col] > 57); board[row][col] = player == 1 ? ‘X‘ : ‘Z‘; /****判断是否有人胜出*****/ if ((board[0][0]==board[1][1]&&board[0][0]==board[2][2]) ||(board[0][2]==board[1][1]&&board[0][2]==board[2][0])) { winner = player; }else{ for (int i = 0; i < 3; i++) { if ((board[i][0]==board[i][1]&&board[i][0]==board[i][2]) ||(board[0][i]==board[1][i]&&board[0][i]==board[2][i])) { winner = player; } } } } printf("\n\n"); printf(" %c | %c | %c \n",board[0][0],board[0][1],board[0][2]); printf("---+---+---\n"); printf(" %c | %c | %c \n",board[1][0],board[1][1],board[1][2]); printf("---+---+---\n"); printf(" %c | %c | %c \n",board[2][0],board[2][1],board[2][2]); printf("**********玩家%d赢了!!!**********\n\n",winner);
时间: 2024-11-06 20:15:45