简易三子棋
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define row 3
#define col 3
int Menu() {
printf("=================================\n");
printf("欢迎来到三子棋!\n");
printf("1.输入1开始游戏!\n");
printf("2.输入2退出游戏!\n");
printf("=================================\n");
int choice = 0;
scanf("%d", &choice);
return choice;
}
void Init(char chessBoard[row][col]) {
memset(chessBoard, ' ', row * col*sizeof(char));
srand((unsigned int)time(0));
}
void Print(char chessBoard[row][col]) {
for (int i = 0; i < row; i++) {
printf("-------------------\n");
for (int j = 0; j < col; j++) {
printf("| %c ", chessBoard[i][j]);
}
printf("|\n");
}
printf("-------------------\n");
}
void playerMove(char chessBoard[row][col]) {
printf("轮到玩家落子!\n");
while (1) {
printf("请输入你要落得子(r c):\n");
int r = 0, c = 0;
scanf("%d %d", &r, &c);
if (r < 0 || r >= row || c < 0 || c >= col) {
printf("你的输入有误!\n");
continue;
}
if (chessBoard[r][c] != ' ') {
printf("该位置已经有子了!\n");
continue;
}
chessBoard[r][c] = 'x';
break;
}
}
char Check(char chessBoard[row][col]) {
int i = 0, j = 0;
for (; i < row; i++) {
if (chessBoard[i][0]!=' ' && chessBoard[i][i] == chessBoard[i][i+1]
&& chessBoard[i][i+2] == chessBoard[i][i + 1]) {
return chessBoard[i][0];
}
}
for (i = 0; i < row; i++) {
if (chessBoard[i][i] != ' ' && chessBoard[i][i] == chessBoard[i + 1][i]
&& chessBoard[i + 2][i] == chessBoard[i][i + 1]) {
return chessBoard[0][i];
}
}
if (chessBoard[1][1] != ' ' && chessBoard[0][0] == chessBoard[1][1] &&
chessBoard[2][2] == chessBoard[1][1]) {
return chessBoard[1][1];
}
if (chessBoard[1][1] != ' ' && chessBoard[0][2] == chessBoard[1][1] &&
chessBoard[1][1] == chessBoard[2][0]) {
return chessBoard[1][1];
}
if (isFull(chessBoard)) {
return 'p';
}
return ' ';
}
int isFull(char chessBoard[row][col]) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (chessBoard[i][j] == ' ') {
return 0;
}
}
}
return 1;
}
void computerMove(char chessBoard[row][col]) {
printf("轮到电脑落子!\n");
while (1) {
int r = rand() % row;
int c = rand() % col;
if (chessBoard[r][c] != ' ') {
continue;
}
chessBoard[r][c] = 'o';
break;
}
}
void Game() {
char chessBoard[row][col] = { 0 };
Init(chessBoard);
char winner;
while (1) {
Print(chessBoard);
playerMove(chessBoard);
if (Check(chessBoard)){
int i=0;
}
computerMove(chessBoard);
winner=Check(chessBoard);
if (winner != ' ') {
break;
}
}
if (winner == 'x') {
printf("玩家获胜!\n");
}
else if (winner == 'o') {
printf("电脑获胜!\n");
}
else if (winner == 'p') {
printf("平局!\n");
}
}
int main() {
while (1) {
int choice = Menu();
if (choice == 1) {
Game();
}
else if (choice==2) {
printf("byebye!\n");
}
else {
printf("输入有误!\n");
}
}
return 0;
}