首先创建一个头文件,在头文件中放函数的声明等。
#ifndef _GAME_H_
#define _GAME_H_
#include<stdio.h>
#include<windows.h>
void game();
#pragma warning(disable :4996)
#endif
然后创建一个main函数,用以驱动游戏。
#include"game.h"
void head(){
while (1){
printf("**********************\n");
printf("*** 1.play 0.exit ***\n");
printf("**********************\n");
printf(" please select \n");
printf("**********************\n");
int a;
scanf("%d", &a);
if (a == 1){
game();
}
else{
printf("game over!\n");
break;
}
}
}
int main(){
head();
system("pause");
return 0;
}
然后是游戏运行所需的函数
#include"game.h"
void inint(char g[][3]){
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
g[i][j] = ' ';
}
}
}
void printfChessBoard(char g[][3]){
for (int i = 0; i < 3; i++){
printf(" %c | %c | %c \n", g[i][0], g[i][1], g[i][2]);
if (i < 2){
printf("-----------\n");
}
}
}
void peopleRemove(char g[][3]){
int x, y;
do{
scanf("%d%d", &x, &y);
if (g[x][y] == ' '&&x < 3&&y<3){
g[x][y] = 'o';
break;
}
else{
printf("error,please import again");
}
} while (1);
}
void computerRemove(char g[][3]){
int x, y;
do{
x = rand() % 3;
y = rand() % 3;
if (g[x][y] == ' '){
g[x][y] = 'x';
break;
}
} while (1);
}
int isFull(char g[][3]){
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (g[i][j] == ' '){
return 0;
}
}
}
return 1;
}
char judg(char g[][3]){
for (int i = 0; i < 3; i++){
if (g[i][0] == g[i][1] && g[i][1] == g[i][2] && g[i][1] == 'o'){
return 'p';
}
else if (g[i][0] == g[i][1] && g[i][1] == g[i][2] && g[i][1] == 'x'){
return 'c';
}
}
for (int i = 0; i < 3; i++){
if (g[0][i] == g[1][i] && g[1][i] == g[2][i] && g[0][i] == 'o'){
return 'p';
}
else if (g[0][i] == g[1][i] && g[1][i] == g[2][i] && g[0][i] == 'x'){
return 'c';
}
}
if (g[0][0] == g[1][1] && g[1][1] == g[2][2] && g[0][0] == 'o'){
return 'p';
}
else if (g[0][0] == g[1][1] && g[1][1] == g[2][2] && g[0][0] == 'x'){
return 'c';
}
else if (g[0][2] == g[1][1] && g[1][1] == g[2][0] && g[0][2] == 'o'){
return 'p';
}
else if (g[0][2] == g[1][1] && g[1][1] == g[2][0] && g[0][2] == 'x'){
return 'c';
}
if (isFull(g)){
return 'q';
}
return ' ';
}
void judg2(j){
if (j == 'c'){
printf("YOU FAIL\n");
}
else if(j == 'p'){
printf("YOU WIN\n");
}
else if (j == 'q'){
printf("DOGFALL\n");
}
}
void game(){
char g[3][3];
inint(g);
char j=' ';//p c q
do{
system("CLS");
printf("\nplease remove:\n\n");
printfChessBoard(g);
peopleRemove(g);
j=judg(g);
if (j != ' '){
break;
}
system("CLS");
printf("\ncomputer remove:\n\n");
printfChessBoard(g);
Sleep(1500);
computerRemove(g);
j=judg(g);
} while (j==' ');
judg2(j);
}