#include <cstdio>
#include <memory.h>
#include <vector>
#include <string>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <set>
#include <ctime>
#include <unordered_set>
#include "chesspi.h"
extern int max_depth;
int main()
{
	//初始棋局
	int coordx[32]{5,4,6,3,7,2,8,1,9,2,8,1,3,5,7,9,5,4,6,3,7,2,8,1,9,2,8,1,3,5,7,9};
	int coordy[32]{1,1,1,1,1,1,1,1,1,3,3,4,4,4,4,4,10,10,10,10,10,10,10,10,10,8,8,7,7,7,7,7};
	int alive[32]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
	printf ("Node Size=%lu Bytes\n",sizeof(chess_node));
	srand(time(0));
	chess_node root;

	if (!build_node(coordx,coordy,alive,0,&root))
	{
		printf ("创建棋局失败！\n");
		return 0;
	}
	int side = 0;
	int nodesInM = 0;
	printf ("Side(0=RED,1=BLACK):");
	scanf("%d",&side);
	printf ("Max Depth(default 5):");
	scanf("%d",&nodesInM);
	if (nodesInM>=4 && nodesInM<10)
		max_depth = nodesInM;
	//回合
	side %=2;
	if (side <0)
		side = 1;
	size_t round = 0;
	bool finished = false;
	root.side = side % 2;
	std::vector<chess_node> history;
	while (!finished)
	{
		printf ("\nround %d:\n==========\n", round);
		if (history.size())
			print_node(root,*history.rbegin());
		else
			print_node(root,root);
		history.push_back(root);
		if ((round+side) % 2==0)
		{
			//找到棋子
			bool ok = false;
			chess_node new_node;
			while (!ok)
			{
				printf ("请输入四个整数，分别是棋子X,Y，目的X,Y,逗号分割:\n");
				int x1,y1,x2,y2;
				scanf("%d,%d,%d,%d",&x1,&y1,&x2,&y2);
				ok = move_node(root,&new_node,x1+1,y1+1,x2+1,y2+1,round % 2);
				if (!ok)
				{
					printf ("没有选中棋子.\n");
					getchar();
				}
				else {
					root = new_node;

				}
			}
		}
		else
		{
			std::vector<chess_node> tree =
					build_tree(root,round%2,history);
			size_t best = judge_tree(tree);
			if (best <1 || best + 1 > tree.size())
				break;
			root = tree[best];
			printf ("Best % ld Cost: %f, %f, Weight %f\n",best
					,root.jump_cost[0],root.jump_cost[1],root.weight
					);
		}
		root.side = side % 2;
		++round;
		if (!((root.alive & 0x00010001)==0x00010001))
		{
			printf ("\nround %lu:\n==========\n", round);
			print_node(root,*history.rbegin());
			finished = true;
		}
	}
	printf ("FINISHED!\n");

	return 0;
}


