头文件game.h
#pragma once
#include<stdio.h>
#include<time.h>
#include<stdbool.h>
#include<windows.h>
void startgame();
void initchessboard();
void printfchessboard();
void playermove();
void computermove();
char checkresult();
static bool chessboardfull();
源文件game.c
#include"game.h"
#define row 3
#define col 3
static char chessboard[row][col];
void initchessboard(){
for (int i = 0; i < row; ++i){
for (int j = 0; j < col; ++j){
chessboard[i][j] = ' ';
}
}
}
void printfchessboard(){
printf("-------------\n");
for (int i = 0; i < row; ++i){
printf("| %c | %c | %c |\n",
chessboard[i][0],
chessboard[i][1],
chessboard[i][2]);
printf("-------------\n");
}
}
void playermove(){
int x, y;
while (1){
printf("输入你所下的位置(row col):\n");
scanf("%d %d", &x, &y);
if ((x < 0 || x >= row) || (y < 0 || y >= col)){
printf("你输入的位置已越界,请重新输入正确的位置!!!\n");
continue;
}
if (chessboard[x][y] != ' '){
printf("该位置已经被占用请重新输入\n");
continue;
}
chessboard[x][y] = 'x';
break;
}
}
void computermove(){
int x, y;
srand(time(0));
while (1){
x = rand() % row;
y = rand() % col;
if (chessboard[x][y] == ' '){
chessboard[x][y] = 'o';
break;
}
}
}
//x代表玩家赢,o代表电脑赢,h代表和棋,c代表继续下continue
char checkresult(){
for (int i = 0; i < row; ++i){
if (chessboard[i][0] != ' '&&chessboard[i][0]==chessboard[i][1]
&&chessboard[i][0]==chessboard[i][2]){
return chessboard[i][0];
}
}
for (int j = 0; j < col; ++j){
if (chessboard[0][j] != ' '&&chessboard[0][j] == chessboard[1][j]
&& chessboard[0][j] == chessboard[2][j]){
return chessboard[0][j];
}
}
if (chessboard [1][1]!= ' '&&chessboard[1][1] == chessboard[0][0]
&& chessboard[1][1] == chessboard[2][2]){
return chessboard[1][1];
}
if (chessboard[1][1] != ' '&&chessboard[1][1] == chessboard[2][0]
&& chessboard[1][1] == chessboard[0][2]){
return chessboard[1][1];
}
if (chessboardfull()){
return 'h';
}
return 'c';
}
static bool chessboardfull(){
for (int i = 0; i < row; ++i){
for (int j = 0; i < col; ++j){
if (chessboard[i][j] == ' ')
return false;
}
}
return true;
}
void startgame()
{
initchessboard();
char winner;
while (1){
printfchessboard();
playermove();
winner = checkresult();
if (winner != 'c')
break;
computermove();
if (winner != 'c')
break;
}
if (winner == 'x')
printf("玩家胜利\n");
else if (winner == 'o')
printf("电脑获胜\n");
else
printf("和棋\n");
}
主函数gametest.c
#include"game.h"
int main(){
system("color 0A");
system("title 三子棋");
int select = 1;
while (select){
printf("****************************************************************\n");
printf("* *\n");
printf("* 简易三子棋 *\n");
printf("* [1]PLAY [0]EXIT *\n");
printf("* *\n");
printf("****************************************************************\n");
printf("请选择》");
scanf("%d", &select);
if (select == 0){
break;
}
if (select != 1){
printf("输入有误请重新输入\n");
continue;
}
startgame();
}
printf("游戏结束\n");
return 0;
}