game.h
#ifndef __GAME__H__
#define __GAME_H__
#include"time.h"
#include"stdlib.h"
#include"string.h"
#include"stdio.h"
#define ROWS 3
#define COLS 3
void init_board( char arr[ROWS][COLS], int row, int col);
void display( char arr[ROWS][COLS], int row, int col);
void Computer(char arr[ROWS][COLS], int row, int col);
void player(char arr[ROWS][COLS], int row, int col);
int cheekfull(char arr[ROWS][COLS], int row, int col);
#endif
game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void init_board(char arr[ROWS][COLS], int row, int col)
{
memset(arr, ' ', ROWS*COLS*sizeof(char));
}
void display(char arr[ROWS][COLS], int row, int col)
{
int i;
for (i = 0; i < row; i++)
{
printf("------------\n");
printf(" %c | %c | %c |\n", arr[i][0],arr[i][1],arr[i][2]);
}
printf("-----------\n");
}
void Computer(char arr[ROWS][COLS], int row, int col)
{
while (1)
{
int x = rand () % 4;
int y = rand () % 4;
if (arr[x-1][y-1] == ' ')
{
arr[x-1][y-1] = 'o';
break;
}
}
cheekfull(arr, ROWS, COLS);
}
void player(char arr[ROWS][COLS], int row, int col)
{
int x, y;
printf("输入你要放棋子的坐标");
scanf("%d%d", &x, &y);
while (1)
{
if ((x<4 && x>0) && (y<4 && y>0))
{
if (arr[x-1][y-1] == ' ')
{
arr[x-1][y-1] = 'X';
break;
}
else
{
printf("此坐标有棋子,请重新你输入》");
scanf("%d%d", &x, &y);
}
}
else
{
printf("输入的坐标有误,请重新输入》");
scanf("%d%d", &x, &y);
}
}
cheekfull(arr, ROWS, COLS);
}
int cheekfull(char arr[ROWS][COLS], int row, int col)
{
int i,j;
for (i = 0; i < row;i++)
if ((arr[i][0] == arr[i][1]) && (arr[i][1] == arr[i][2]) && (arr[i][0] != ' '))
return 0;
for (i = 0; i < col; i++)
if ((arr[0][i] == arr[1][i]) && (arr[1][i] == arr[2][i]) && (arr[0][i] != ' '))
return 0;
if ((((arr[0][0] == arr[1][1]) && (arr[1][1] == arr[2][2]) )||
((arr[0][2] == arr[1][1]) && (arr[1][1] == arr[2][0])))&&arr[1][1]!=' ')
return 0;
for (i = 0; i < row;i++)
for (j = 0; j < col; j++)
{
if (arr[i][j] == ' ')
return 1;
}
return 'p';
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void menu()
{
printf("*************************\n");
printf("*****1.play 0.exist*****\n");
printf("*************************\n");
}
void Playgame()
{
char arr[ROWS][COLS] = { 0 };
init_board(arr, ROWS, COLS);
display(arr, ROWS, COLS);
srand((unsigned int)time(NULL));
while (1)
{
Computer(arr, ROWS, COLS);
display(arr, ROWS, COLS);
if (cheekfull(arr, ROWS, COLS) == 0)
{
printf("电脑赢\n");
break;
}
else if (cheekfull(arr, ROWS, COLS) == 'p')
{
printf("平局\n");
break;
}
player(arr, ROWS, COLS);
display(arr, ROWS, COLS);
if (cheekfull(arr, ROWS, COLS) == 0)
{
printf("玩家赢\n");
break;
}
else if (cheekfull(arr, ROWS, COLS) == 'p')
{
printf("平局\n");
break;
}
}
}
void test()
{
int input;
do
{
menu();
printf("请选择》\n");
scanf("%d", &input);
switch (input)
{
case 1:
Playgame();
break;
case 0:
printf("游戏结束\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
}
int main()
{
test();
system("pause");
return 0;
}
三子棋,
最新推荐文章于 2024-04-19 15:41:06 发布