头文件
#ifndef _GAME_H_
#define _GAME_H_
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#endif
具体实现
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
char chess[3][3] = { 0 };
int size = 9;
void chess_board() //打印棋盘
{
int i = 0;
int j = 0;
printf(" | | \n");
for (i = 0; i < 3; i++)
{
printf("_%c_|_%c_|_%c_\n", chess[i][0], chess[i][1], chess[i][2]);
printf(" | | \n");
}
printf(" | | \n");
}
void player() //玩家下棋
{
int a = 0;
int b = 0;
scanf("%d,%d", &a, &b);
if (a > 0 || a <= 3 || b > 0 || b <= 3)
{
chess[a - 1][b - 1] = 'X';
}
else
{
printf("输入错误!\n");
player();
}
size--;
}
void computer() //电脑下棋
{
int m = 0;
int n = 0;
srand((unsigned)time(NULL));
m = rand() % 3;
n = rand() % 3;
while (chess[m][n] != 0)
{
m = rand() % 3;
n = rand() % 3;
}
chess[m][n] = 'O';
size--;
}
int winer() //输赢判断
{
int i = 0;
for (i = 0; i < 3; i++)
{
if (chess[i][0] == chess[i][1] && chess[i][1] == chess[i][2] && chess[i][2] == 'X'
|| chess[0][i] == chess[1][i] && chess[1][i] == chess[2][i] && chess[2][i] == 'X'
|| chess[0][0] == chess[1][1] && chess[1][1] == chess[2][2] && chess[2][2] == 'X'
|| chess[0][2] == chess[1][1] && chess[1][1] == chess[2][0] && chess[2][0] == 'X')
//printf("YOU WIN!\n"); //玩家胜
return 1;
else if (chess[i][0] == chess[i][1] && chess[i][1] == chess[i][2] && chess[i][2] == 'O'
|| chess[0][i] == chess[1][i] && chess[1][i] == chess[2][i] && chess[2][i] == 'O'
|| chess[0][0] == chess[1][1] && chess[1][1] == chess[2][2] && chess[2][2] == 'O'
|| chess[0][2] == chess[1][1] && chess[1][1] == chess[2][0] && chess[2][0] == '0')
//printf("YOU FAILED!\n");//电脑胜
return -1;
}
//printf("DRAW!\n");//平局
return 0;
}
int play() //三子棋游戏
{
int win = 0;
while (1)
{
printf("请玩家下棋:\n");
player();
//chess_board();
computer();
system("cls");
chess_board();
win = winer();
if (win == 1)
{
printf("玩家胜利\n");
return 1;
}
else if (win == -1)
{
printf("电脑胜利\n");
return 1;
}
else if (size < 1)
{
printf("游戏结束\n");
}
}
return 0;
}
void play1()
{
int n;
int i;
int j;
while (1)
{
menu();
printf("请选择PLAY或EXIT: ");
scanf("%d", &n);
switch (n)
{
case 1:
play();
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
chess[i][j] = 0;
}
size = 9;
break;
case 0:
return;
default:
printf("输入错误,请重新输入:\n");
break;
}
}
}
测试文件
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void menu()
{
printf("************** 1.PLAY *************\n");
printf("************** 0.EXIT *************\n");
}
int main()
{
//chess_board();
play1();
system("pause");
return 0;
}