井字棋:
井字棋,英文名叫TicTacToe,是一种在3✖3格子上进行的连珠游戏。
我所写的这个井字棋不是很智能(相当于简单难度),因为电脑的落子是随机的,基本上玩家都会获得最后的胜利。
Utili.h:
#ifndef _UTILI_H_
#define _UTILI_H_
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<time.h>
#include<stdbool.h>
#endif /* _UTILI_H_ */
Game.h
#ifndef _GAME_H_
#define _GAME_H_
#include"Utili.h"
#define START 1
#define QUIT 0
void StartGame();
void InitGame();
void PrintChess();
void PlayerMove();
void ComputerMove();
char CheckGameOver();
#endif /* _GAME_H_ */
Game.c
#include"Game.h"
#define ROW 3
#define COL 3
static char chess_board[ROW][COL];
void InitGame()
{
for (int i = 0; i < ROW; ++i)
{
for (int j = 0; j < COL; ++j)
{
chess_board[i][j] = ' ';
}
}
}
void PrintChess()
{
for (int i = 0; i < ROW; ++i)
{
printf("| %c | %c | %c |\n", chess_board[i][0], chess_board[i][1], chess_board[i][2]);
if (i < ROW - 1)
printf("|---|---|---|\n");
}
}
void PlayerMove()
{
printf("玩家落子.\n");
int row, col;
while (1)
{
printf("请选择你要下的位置(row col):");
scanf("%d %d", &row, &col);
if (row < 0 || row >= ROW || col<0 || col>COL)
{
printf("坐标输入错误,请重新输入\n");
continue;
}
if (chess_board[row][col] != ' ')
{
printf("此坐标已落子,请重新选择\n");
continue;
}
chess_board[row][col] = 'x';
break;
}
}
void ComputerMove()
{
srand(time(0));
while (1)
{
int row = rand() % ROW;
int col = rand() % COL;
if (chess_board[row][col] != ' ')
{
continue;
}
chess_board[row][col] = 'o';
break;
}
}
bool ChessFull()
{
for (int i = 0; i < ROW; ++i)
{
for (int j = 0; j < COL; ++j)
{
if (chess_board[i][j] == ' ')
return false;
}
}
return true;
}
char CheckGameOver()
{
for (int 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 (int i = 0; i < COL; ++i)
{
if (chess_board[0][i] != ' '
&& chess_board[0][i] == chess_board[1][i]
&& chess_board[0][i] == chess_board[2][i])
return chess_board[0][i];
}
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 (ChessFull())
return 'h';
return 'c'; //
}
void StartGame()
{
InitGame();
char winner;
while (1)
{
PrintChess();
PlayerMove();
winner = CheckGameOver();
if (winner != 'c')
break;
ComputerMove();
winner = CheckGameOver();
if (winner != 'c')
break;
}
if (winner == 'x')
printf("玩家胜利\n");
else if (winner == 'o')
printf("电脑胜利\n");
else if (winner == 'h')
printf("平局\n");
}
GameMain.c
#include"Game.h"
int main(int argc, char* argv[])
{
int select = 1;
while (select)
{
system("cls");
printf("*************************************\n");
printf("* [1] Game Start [0] Game Over *\n");
printf("*************************************\n");
printf("请输入:>");
scanf("%d", &select);
if (select == QUIT)
break;
if (select != START)
{
printf("输入错误\n");
continue;
}
//开始游戏
StartGame();
}
printf("再见\n");
return 0;
}