三子棋双人版
包含一个头文件threeChess.h和两个源文件(main.c和threeChess.c)
//threeChess.h
#ifndef _THREECHESS_H_
#define _THREECHESS_H_
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#pragma warning(disable:4996)
#define ROW 3
#define COL 3
void game();
#endif
//main.c
#include"threeChess.h"
int main()
{
int num;
do{
printf("******************************************\n");
printf("**********欢迎访问三子棋双人版!**********\n");
printf("**** input 1:play! input 0:exit! *****\n");
printf("******************************************\n");
printf("please select:");
scanf("%d", &num);
switch (num)
{
case 0:
exit(0);
case 1:
game();
continue;
default:
printf("input error! try again.\n");
break;
}
} while (1);
system("pause");
return 0;
}
//threeChess.c
#include"threeChess.h"
char triChe[ROW][COL];
//输出棋盘
void outputCheckerBoard()
{
int i = 0;
printf("\t");
for (i = 0; i < COL; i++){
printf("%d\t", i);
}
printf("\n");
for (i = 0; i < ROW; i++){
printf("%d\t", i);
for (int j = 0; j < COL; j++){
printf("%c\t", triChe[i][j]);
}
printf("\n\n");
}
}
int isFull()
{
char *p = &triChe[0][0];
for (int i = 0; i < ROW*COL; i++){
if (*(p + i) == '_'){
return 0;
}
}
return 1;//平局
}
int judge()
{
//判断行
int i = 0;
for (; i < ROW; i++){
if ((triChe[i][0] != '_') && (triChe[i][0] == triChe[i][1]) && \
(triChe[i][1] == triChe[i][2])){
return triChe[i][0];
}
}
//判断列
for (i = 0; i < COL; i++){
if ((triChe[0][i] != '_') && (triChe[0][i] == triChe[1][i]) && \
(triChe[1][i] == triChe[2][i])){
return triChe[0][i];
}
}
//判断斜线
if ((triChe[1][1] != '_') && \
(((triChe[0][0] == triChe[1][1]) && (triChe[1][1] == triChe[2][2])) || \
((triChe[0][2] == triChe[1][1]) && (triChe[1][1] == triChe[2][0])))){
return triChe[1][1];
}
if (isFull()){
return 1;//平局
}
return 0;
}
void play(int i)
{
int line, column;
system("cls");
outputCheckerBoard();
loop:
printf("player %c:please input the position of your chess pieces!\n", i % 2 + 65);
scanf("%d%d", &line, &column);
if (line > 2 || column > 2){
printf("the position out of bounds!\n");
goto loop;
}else if (triChe[line][column] != '_'){
printf("There are already pieces in this position!\n");
goto loop;
}else{
triChe[line][column] = i % 2 + 65;
}
}
void game()
{
memset(triChe, '_', ROW*COL);
int i = 0;
int result;
do{
play(i++);
result = judge();
if (result != 0){
break;
}
play(i++);
} while (result == 0);
system("cls");
outputCheckerBoard();
switch (result){
case 1:
printf("平局!\n");
return;
case 65:
printf("A胜!\n");
return;
case 66:
printf("B胜!\n");
return;
}
}