C语言实现三子棋游戏

题目要求:设计一个3*3的棋盘,由电脑和玩家两个进行游戏,谁先连成一行(横,竖,对角线),谁就获得胜利。


GAME.h
#ifndef __GAME_H__
#define __GAME_H__

#include
#include
#include
#include
#include

#define ROW 3
#define COL 3

void InitBoard(char board[ROW][COL], int row, int col);
void DisplayBoard(char board[ROW][COL], int row, int col);
void ComputerMove(char board[ROW][COL], int row, int col);
void PlayerMove(char board[ROW][COL], int row, int col);
char IsWin(char board[ROW][COL], int row, int col);

#endif __GAME_H__
GAME.c
#include "game.h"

void InitBoard(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	memset(board, ' ', row*col*sizeof(board[0][0]));
}

void DisplayBoard(char board[ROW][COL], int row, int col)
{
	int i = 0;
	for(i=0; i=1 && x<=3 && y>=1 && y<=3)
		{
			if(board[x-1][y-1] == ' ')
			{
				board[x-1][y-1] = 'X';
				break;
			}
			else
			{
				printf("该坐标已被占用\n");
			}
		}
		else
		{
			printf("该坐标非法\n");
		}
	}
}

static int IsFull(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for(i=0; i
TEST.c
#include "game.h"

void menu()
{
	printf("**********************\n");
	printf("****1.play   0.exit***\n");
	printf("**********************\n");
}

void game()
{
	char ret = 0;
	char board[ROW][COL] = {0};
    InitBoard(board, ROW, COL);
	DisplayBoard(board, ROW, COL);
	while(1)
	{
		ComputerMove(board, ROW, COL);
		ret = IsWin(board, ROW, COL);
		if(ret != ' ')
		{
			break;
		}
		DisplayBoard(board, ROW, COL);
		PlayerMove(board, ROW, COL);
		ret = IsWin(board, ROW, COL);
		if(ret != ' ')
		{
			break;
		}
		DisplayBoard(board, ROW, COL);
	}
	if(ret == 'P')
	{
		printf("平局\n");
	}
	else if(ret == 'X')
	{
		printf("玩家赢\n");
	}
	else if(ret == '0')
	{
		printf("电脑赢\n");
	}
	DisplayBoard(board, ROW, COL);
}

void test()
{
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
		menu();
		printf("请选择:");
			scanf("%d",&input);
		switch(input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误\n");
			break;
		}

	}while(input);
}

int main()
{
	test();
	return 0;
} 






你可能感兴趣的:(C语言实现三子棋游戏)