简易井字棋c语言数组代码
时间: 2023-11-24 14:49:48 浏览: 135
井字棋代码
以下是简易井字棋的C语言数组代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ROW 3
#define MAX_COL 3
//初始化棋盘
void Init(char board[MAX_ROW][MAX_COL]) {
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
board[row][col] = ' ';
}
}
}
//打印棋盘
void printboard(char board[MAX_ROW][MAX_COL]) {
printf(" 1 2 3\n");
for (int row = 0; row < MAX_ROW; row++) {
printf("%d ", row + 1);
for (int col = 0; col < MAX_COL; col++) {
printf("%c", board[row][col]);
if (col != MAX_COL - 1) {
printf("|");
}
}
printf("\n");
if (row != MAX_ROW - 1) {
printf(" -----\n");
}
}
}
//玩家落子
void player(char board[MAX_ROW][MAX_COL]) {
int row, col;
printf("请落子(行 列):");
scanf("%d %d", &row, &col);
while (board[row - 1][col - 1] != ' ') {
printf("该位置已有棋子,请重新落子(行 列):");
scanf("%d %d", &row, &col);
}
board[row - 1][col - 1] = 'x';
}
//电脑落子
void computer(char board[MAX_ROW][MAX_COL]) {
int row, col;
do {
row = rand() % MAX_ROW;
col = rand() % MAX_COL;
} while (board[row][col] != ' ');
board[row][col] = 'o';
}
//判断胜负
char cheak(char board[MAX_ROW][MAX_COL]) {
//判断行
for (int row = 0; row < MAX_ROW; row++) {
if (board[row] == board[row] && board[row] == board[row] && board[row] != ' ') {
return board[row];
}
}
//判断列
for (int col = 0; col < MAX_COL; col++) {
if (board[col] == board[col] && board[col] == board[col] && board[col] != ' ') {
return board[col];
}
}
//判断对角线
if (board == board && board[1] == board && board != ' ') {
return board;
}
if (board == board && board[1] == board && board != ' ') {
return board;
}
//判断平局
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
if (board[row][col] == ' ') {
return ' ';
}
}
}
return 't';
}
int main() {
//创建棋盘,初始化为全0
char board[MAX_ROW][MAX_COL] = { 0 };
//使用Init函数将棋盘初始位置改为' '
Init(board);
//生成随机种子,程序开始前设置即可
srand((unsigned int)time(0));
char winner = ' ';
while (1) {
//打印棋盘
printboard(board);
//玩家落子
player(board);
//电脑落子
computer(board);
//判断胜负
winner = cheak(board);
if (winner != ' ') {
//胜负已分,循环结束
break;
}
}
if (winner == 'x') {
printf("恭喜你赢了!!\n");
}
else if (winner == 'o') {
printf("你真菜!!\n");
}
else {
printf("你和人工智障五五开\n");
}
system("pause");
return 0;
}
阅读全文