1. 程式人生 > >五子棋的隨機C語言版本,以及網上找的完整版

五子棋的隨機C語言版本,以及網上找的完整版

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <time.h>
//#include "AL.h"
#define ROW 15
#define COL 15
char str[ROW][COL];
void Str(){
	for (int row = 0; row < ROW; ++row)
	{
		for (int col = 0; col < COL; ++col)
		{
			str[row][col] = ' ';
		}
	}

}
void Print(){
	for (int i = 0; i < ROW; i++)
	{
		printf("|");
		for (int j = 0; j < COL; j++)
		{
			printf(" %c |", str[i][j]);

		}
		printf("\n");
		printf("|");

		for (int i = 0; i <=ROW-1;i++)
		{
			printf("---|");
		}
		printf("\n");
	}
}
int Isfull(){
	int row;
	int col;
	for (row = 0; row < ROW; ++row)
	{
		for (col = 0; col < COL; ++col){
			if (str[row][col] == ' ')
			{
				return 0;
			}
		}
	}
	return 1;
}
int Win(){
	int win = 0;
	for (int i = 0; i < ROW; ++i)
	{
		for (int j = 0; j < COL; j++)
		{
			if (((str[i][j] == str[i][j + 1] && str[i][j + 1] == str[i][j + 2] && str[i][j + 2] == str[i][j + 3] 
				&& str[i][j + 3] == str[i][j + 4]) ||
				(str[i][j] == str[i + 1][j] && str[i + 1][j] == str[i + 2][j] && str[i + 2][j] == str[i + 3][j]
				&& str[i + 3][j] == str[i + 4][j]) ||
				(str[i][j] == str[i + 1][j + 1] && str[i + 1][j + 1] == str[i + 2][j + 2]
				&& str[i + 2][j + 2] == str[i + 3][j + 3] && str[i + 3][i + 3] == str[i + 4][j + 4]) ||
				(str[i][j] == str[i + 1][j - 1] && str[i + 1][j - 1] == str[i + 2][j - 2]
				&& str[i + 2][j - 2] == str[i + 3][j - 3] && str[i + 3][j - 3] == str[i + 4][j - 4]))
				&& str[i][j] != ' ')
			{
				return str[i][j];
				break;
			}
		}
	}
	if (Isfull() == 1)
	{
		return 'q';
	}
	return ' ';

}
void Player(){
	int  row;
	int col;
	printf("玩家執x,請玩家落子:(row,col)\n");
	while (1){
		scanf("%d,%d", &row, &col);
		if (row > ROW || col > COL || str[row][col] != ' ')//檢驗落子是否正確
		{
			printf("請重新輸入:");
		}
		else
		{
			break;
		}
	}
	str[row][col] = 'x';
	Print();
}
void Computer(){
	int row, col;
	printf("電腦執o,電腦落子\n");
	while (1)
	{
		srand(time(NULL));
		row = rand() % ROW;
		col = rand() % COL;
		if (row > 10 || col > 10 || str[row][col] != ' '){
			continue;
		}
		else
		{
			str[row][col] = 'o';
			break;
		}
	}
	Print();
}

int main(){
	//1.初始化陣列
	Str();

	//2.列印棋盤

	//3.玩家落子(檢驗落子位置是否正確)
	//判斷勝負
	char winner = ' ';
	Print();
	while (1)
	{


		Player();
		winner = Win();
		if (winner != ' ')//遊戲結束 
		{
			break;
		}

		//4.電腦落子(檢驗落子位置是否正確)
		//判斷勝負

		Computer();
		winner = Win();
		if (winner != ' ')//遊戲結束 
		{
			break;
		}
	}
	if (winner == 'x')
	{
		printf("玩家獲勝\n");
	}
	else if (winner == 'o')
	{
		printf("電腦獲勝\n");
	}
	else if (winner == ' ')
	{
		printf("和棋\n");
	}

	system("pause");
	return 0;
}

用最簡單的C語言中的知識,寫出這個電腦隨機落子的五子棋,感到可以寫出這種有點自得的感覺,但是看到電腦的隨機落子,有感覺還差的太遠太遠.

在網上找了別人的版本,瞬間又讓我覺得還完全沒有學習這方面的知識.

https://pan.baidu.com/s/1X2XiY1prFBrRgxQVCcodfQ