C语言:实现三子棋
思路:三子棋顾名思义就是五子棋的延申,C语言实现三子棋需要先给用户展示使用界面,使用界面必须简单易懂,让他们能够去选择,其次是三子棋是人机大战,需要电脑和用户共同完成,所以写电脑的移动是可以以随机数生成坐标的形式来实现,无论是电脑移动和用户移动时,都要对坐标以判断,看是不是可以走,然后就是判断输赢了,以横竖对角线相等来判断输赢和平局,最后给用户一个显示界面供用户查看判断。
以下是源代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <windows.h>
#include <time.h>
#define ROW 3
#define COL 3
void ShowUI()
{
printf("##################################\n");
printf("## 1. Play 2. Exit ##\n");
printf("##################################\n");
printf("Please Select:> ");
}
void ComputerMove(char board[][COL], int row, int col)
{
while (1){
int x = rand() % row;
int y = rand() % col;
if (board[x][y] == ' '){
board[x][y] = 'O';
break;
}
}
}
void PlayerMove(char board[][COL], int row, int col)
{
int x, y;
while (1){
printf("Please Enter Your Pos(x,y):> ");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col){
if (board[x - 1][y - 1] == ' '){
board[x - 1][y - 1] = 'X';
break;
}
else{
printf("Enter Pos Is Not OK, Try Again!\n");
}
}
else{
printf("Enter Error, Try Again!\n");
}
}
}
char Judge(char board[][COL], int row, int col)
{
int i = 0;
int j = 0;
for (; i < row; i++){
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && \
board[i][0] != ' '){
return board[i][0];
}
}
for (i = 0; i < col; i++){
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && \
board[0][i] != ' '){
return board[0][i];
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && \
board[1][1] != ' '){
return board[1][1];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && \
board[1][1] != ' '){
return board[1][1];
}
for (i = 0; i < row; i++){
for (j = 0; j < col; j++){
if (board[i][j] == ' '){
return 'N';
}
}
}
return 'E';
}
void ShowBoard(char board[][COL], int row, int col)
{
printf(" 1 2 3\n");
printf("-----------------\n");
int i = 0;
int j = 0;
for (; i < row; i++){
printf("%d |", i + 1);
for (j = 0; j < col; j++){
printf(" %c |", board[i][j]);
}
printf("\n-----------------\n");
}
printf("\n");
}
void Game()
{
char board[ROW][COL];
memset(board, ' ', sizeof(board));
char result = 'N';
srand((unsigned long)time(NULL));
while (1){
system("cls");
ComputerMove(board, ROW, COL);
ShowBoard(board, ROW, COL);
result = Judge(board, ROW, COL);
if (result != 'N'){//'X' 'O' 'E' 'N'
break;
}
PlayerMove(board, ROW, COL);
ShowBoard(board, ROW, COL);
result = Judge(board, ROW, COL);
if (result != 'N'){//'X' 'O' 'E' 'N'
break;
}
}
switch (result){
case 'X':
printf("You Win! :)\n");
break;
case 'O':
printf("You Lose, Computer Win! :(\n");
break;
case 'E':
printf("平局,恭喜!\n");
break;
default:
break;
}
}
int main()
{
int select = 0;
int quit = 0;
while (!quit){
ShowUI();
scanf("%d", &select);
switch (select){
case 1:
Game();
break;
case 2:
printf("I Am Quit!\n");
quit = 1;
break;
default:
printf("Select Error! Try Again!\n");
break;
}
}
return 0;
}