用C语言实现的井字棋游戏,仅作个人记录
headcpy.h
#include<stdio.h>
#include<stdbool.h>
#include<windows.h>
#define ROW 3
#define ROL 3
static chess_board[ROW][ROL];
void WelcomeInterface();
void InitGame();
void PrintChess();
void PlayerMove();
void ComputerMove();
bool InputLegality(int row,int rol);
char CheckChess();
bool CheckFull();
void JudgeWinner(char input);
maincpy.c
#include"headcpy.h"
int main()
{
char winner;
int select;
WelcomeInterface();
scanf("%d",&select);
if(select==1)
{
InitGame();
PrintChess();
while('c'==CheckChess())
{
if(CheckFull())
break;
PlayerMove() ;
system("cls");
PrintChess();
winner=CheckChess();
if(winner=='x')
break;
if(CheckFull())
break;
ComputerMove();
system("cls");
PrintChess();
winner=CheckChess();
if(winner=='o')
break;
}
JudgeWinner(CheckChess());
}
return 0;
}
function.c
#include"headcpy.h"
void WelcomeInterface()
{
printf("---------------\n");
printf("|[1] StartGame|\n");
printf("|[0] OverGame |\n");
printf("---------------\n");
}
void InitGame()
{
int i,j;
for(i=0;i<ROW;i++)
{
for(j=0;j<ROL;j++)
{
chess_board[i][j]=' ';
}
}
}
void PrintChess()
{
int i,j;
for(i=0;i<ROW;i++)
{
printf("|| %c || %c || %c ||\n",chess_board[i][0],chess_board[i][1],chess_board[i][2]);
if(i<2)
printf("||---||---||---||\n");
}
}
void PlayerMove()
{
srand(time(0));
int row,rol;
printf("Player'turn......\n");
do
{
scanf("%d %d",&row,&rol);
if(InputLegality(row,rol))
break;
}while(1);
chess_board[row][rol]='x';
}
void ComputerMove()
{
srand(time(0));
int row,rol;
printf("Computerx'turn......\n");
do
{
row=rand()%ROW;
rol=rand()%ROL;
if(InputLegality(row,rol))
break;
}while(1);
chess_board[row][rol]='o';
}
bool InputLegality(int row,int rol)
{
if(row>=0&&row<=3)
{
if(rol>=0&&rol<=3)
{
if(chess_board[row][rol]==' ')
return true;
}
}
return false;
}
char CheckChess()
{
int i,j;
char ret;
for(i=0;i<ROW;i++)
{
if(chess_board[i][0]!=' '&&
chess_board[i][0]==chess_board[i][1]&&
chess_board[i][0]==chess_board[i][2])
return chess_board[i][0];
}
for(j=0;j<ROL;j++)
{
if(chess_board[0][j]!=' '&&
chess_board[0][j]==chess_board[1][j]&&
chess_board[0][j]==chess_board[2][j])
return chess_board[0][j];
}
if(chess_board[0][0]!=' '&&
chess_board[0][0]==chess_board[1][1]&&
chess_board[0][0]==chess_board[2][2])
return chess_board[0][0];
if(chess_board[0][2]!=' '&&
chess_board[0][2]==chess_board[1][1]&&
chess_board[0][2]==chess_board[2][0])
return chess_board[0][2];
if(CheckFull())
return 'h';
return 'c';
}
bool CheckFull()
{
int row,rol;
for(row=0;row<ROW;row++)
{
for(rol=0;rol<ROL;rol++)
{
if(chess_board[row][rol]==' ')
return false;
}
}
return true;
}
void JudgeWinner(char input)
{
switch(input)
{
case 'x':printf("Congratulations!You win!\n");break;
case 'o':printf("Unfortunately.You loose.\n");break;
case 'h':printf("Fight to draw.\n");break;
}
}