/*
 * A very simple tic-tac-toe game.
 *
 * Copyright (c) 2011 Cyber Switching, Inc.
 * Chris Verges <chrisv@cyberswitching.com>
 *
 * Copyright (c) 2003 Bill Kendrick
 * Bill Kendrick <bill@newbreedsoftware.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

/*
 * The game board is setup in the following manner:
 *
 *    A1 (0,0)  |  A2 (1,0)  |  A3 (2,0)
 *  ------------+------------+------------
 *    B1 (0,1)  |  B2 (1,1)  |  B3 (2,1)
 *  ------------+------------+------------
 *    C1 (0,2)  |  C2 (1,1)  |  C3 (2,2)
 */

#include "ttt.h"

typedef enum {
	UNCLAIMED,
	PLAYER_X,
	PLAYER_O,
	DRAW
} player_t;

typedef struct {
	ttt_element_id_t	img_id;
	player_t		owner;
	int			is_winning_tile;
} grid_element_t;

static grid_element_t grid[3][3];

static int is_game_over = 1;

static player_t player = UNCLAIMED;

void reset_game(void)
{
	int x, y;

	for (x = 0; x < 3; x++) {
		for (y = 0; y < 3; y++) {
			grid_element_t *e = &grid[x][y];
			e->img_id = 0;
			e->owner = UNCLAIMED;
			e->is_winning_tile = 0;
		}
	}

	is_game_over = 0;

	player = PLAYER_X;

	draw_board();
	draw_element(TURN_X);

	srand(SDL_GetTicks());
}

void game_over(void)
{
	int x, y;

	is_game_over = 1;

	for (x = 0; x < 3; x++) {
		for (y = 0; y < 3; y++) {
			grid_element_t *e = &grid[x][y];
			if (e->owner != UNCLAIMED && !e->is_winning_tile)
				strikeout_element(e->img_id);
		}
	}

	switch (player) {
	case PLAYER_X:
		draw_element(STATUS_WIN_X);
		break;
	case PLAYER_O:
		draw_element(STATUS_WIN_O);
		break;
	case DRAW:
		draw_element(STATUS_DRAW);
		break;
	case UNCLAIMED:
		break;
	}

	strikeout_element(HUMAN_VS_COMPUTER);
	strikeout_element(HUMAN_VS_HUMAN);
}

static int is_winner(void)
{
	player_t a, b, c;
	int x, y;

	/* Check for a vertical match */
	for (x = 0; x < 3; x++) {
		a = grid[x][0].owner;
		b = grid[x][1].owner;
		c = grid[x][2].owner;

		if (a != UNCLAIMED && a == b && b == c) {
			grid[x][0].is_winning_tile = 1;
			grid[x][1].is_winning_tile = 1;
			grid[x][2].is_winning_tile = 1;
			return 1;
		}
	}

	/* Check for a horizontal match */
	for (y = 0; y < 3; y++) {
		a = grid[0][y].owner;
		b = grid[1][y].owner;
		c = grid[2][y].owner;

		if (a != UNCLAIMED && a == b && b == c) {
			grid[0][y].is_winning_tile = 1;
			grid[1][y].is_winning_tile = 1;
			grid[2][y].is_winning_tile = 1;
			return 1;
		}
	}

	/* Check for a top-left to bottom-right diagonal match */
	a = grid[0][0].owner;
	b = grid[1][1].owner;
	c = grid[2][2].owner;

	if (a != UNCLAIMED && a == b && b == c) {
		grid[0][0].is_winning_tile = 1;
		grid[1][1].is_winning_tile = 1;
		grid[2][2].is_winning_tile = 1;
		return 1;
	}

	/* Check for a top-right to bottom-left diagonal match */
	a = grid[2][0].owner;
	b = grid[1][1].owner;
	c = grid[0][2].owner;

	if (a != UNCLAIMED && a == b && b == c) {
		grid[2][0].is_winning_tile = 1;
		grid[1][1].is_winning_tile = 1;
		grid[0][2].is_winning_tile = 1;
		return 1;
	}

	/* No winners yet */
	return 0;
}

static int ai_select_move(int x, int y)
{
	SDL_Delay(350);
	register_move(x, y);
	return 1;
}

/*
 * Searches the combination of cells form by 'a', 'b' and 'c' against the
 * 'expected' owner, and returns 0 if no action should be taken against
 * this combination or 1 thru 3 to indicate which cell ('a' thru 'c',
 * respectively) should be your next move.
 */
static int ai_find_next_move(player_t expected, player_t a, player_t b,
				 player_t c)
{
	int match = 0;
	int count = 0;
	int cell = 0;
	int tmp;

	if (a == expected)
		return 0;
	else if (a != UNCLAIMED)
		match |= 0x1;

	if (b == expected)
		return 0;
	else if (b != UNCLAIMED)
		match |= 0x2;

	if (c == expected)
		return 0;
	else if (c != UNCLAIMED)
		match |= 0x4;

	match ^= 0x0007;

	for (tmp = 1; tmp <= 3; tmp++) {
		if (match & 0x0001) {
			count++;
			cell = tmp;
		}
		match >>= 1;
	}

	if (count == 1)
		return cell;

	return 0;
}

/*
 * This function assumes that the calling player is looking for
 * a win against player 'expected'.  The winning grid coordinate
 * will be placed in the variables 'x_buf' and 'y_buf' if
 * such a coordinate is found.
 */
static int ai_search(player_t expected, int *x_buf, int *y_buf)
{
	player_t a, b, c;
	int x, y;

	/* Check for a vertical win */
	for (x = 0; x < 3; x++) {
		a = grid[x][0].owner;
		b = grid[x][1].owner;
		c = grid[x][2].owner;

		y = ai_find_next_move(expected, a, b, c);
		if (!y)
			continue;
		else
			y--;

		debug("AI selected grid %dx%d (vertical algorithm)\n", x, y);
		*x_buf = x;
		*y_buf = y;
		return 1;
	}

	/* Check for a horizontal win */
	for (y = 0; y < 3; y++) {
		a = grid[0][y].owner;
		b = grid[1][y].owner;
		c = grid[2][y].owner;

		x = ai_find_next_move(expected, a, b, c);
		if (!x)
			continue;
		else
			x--;

		debug("AI selected grid %dx%d (horizontal algorithm)\n", x, y);
		*x_buf = x;
		*y_buf = y;
		return 1;
	}

	/* Check for a top-left to bottom-right diagonal win */
	do {
		a = grid[0][0].owner;
		b = grid[1][1].owner;
		c = grid[2][2].owner;

		x = ai_find_next_move(expected, a, b, c);
		if (!x)
			continue;
		else
			x--;

		debug("AI selected grid %dx%d (TL-BR diagonal algorithm)\n", x, x);
		*x_buf = x;
		*y_buf = x;
		return 1;
	} while (0);

	/* Check for a bottom-left to top-right diagonal win */
	do {
		a = grid[0][2].owner;
		b = grid[1][1].owner;
		c = grid[2][0].owner;

		x = ai_find_next_move(expected, a, b, c);
		if (!x) {
			continue;
		} else {
			x--;
			y = 2 - x;
		}

		debug("AI selected grid %dx%d (BL-TR diagonal algorithm)\n", x, y);
		*x_buf = x;
		*y_buf = y;
		return 1;
	} while (0);

	return 0;
}

int run_artificial_intelligence(void)
{
	int x, y, err;

	debug("AI analyzing board\n");

	/* Run the scenario for us winning */
	debug("Running search for winning scenario\n");
	err = ai_search(PLAYER_X, &x, &y);
	if (err) {
		register_move(x, y);
		return 1;
	}

	/* Run the scenario for us blocking */
	debug("Running search for blocking scenario\n");
	err = ai_search(PLAYER_O, &x, &y);
	if (err) {
		register_move(x, y);
		return 1;
	}

	/* Pick something at random */
	for (err = 0; err < 3; err++) {
		x = rand() % 3;
		y = rand() % 3;
		if (grid[x][y].owner == UNCLAIMED) {
			debug("AI selected grid %dx%d via random search\n", x, y);
			return ai_select_move(x, y);
		}
	}

	for (x = 0; x < 3; x++)
		for (y = 0; y < 3; y++)
			if (grid[x][y].owner == UNCLAIMED) {
				debug("AI selected grid %dx%d via sequential search\n", x, y);
				return ai_select_move(x, y);
			}

	return 0;
}

void switch_players(void)
{
	if (player == PLAYER_O) {
		player = PLAYER_X;
		draw_element(TURN_X);
		debug("Player %d's turn\n", player);
		return;
	}

	player = PLAYER_O;
	draw_element(TURN_O);
	debug("Player %d's turn\n", player);

	if (game_type == HUMAN_VS_HUMAN)
		return;

	run_artificial_intelligence();
}

void register_move(int x, int y)
{
	grid_element_t *e;
	int tiles_remaining = 0;

	if (is_game_over)
		return;

	e = &grid[x][y];
	if (e->owner != UNCLAIMED)
		return;

	e->owner = player;
	e->img_id = (player == PLAYER_X) ? MARK_X_A1 : MARK_O_A1;
	e->img_id += x + (y * 3);
	draw_element(e->img_id);

	debug("Player %d: Grid %dx%d -> Element %d\n", player, x, y, e->img_id);

	if (is_winner()) {
		game_over();
		return;
	}

	/* Are there any unclaimed tiles left? */
	for (x = 0; x < 3; x++)
		for (y = 0; y < 3; y++)
			if (grid[x][y].owner == UNCLAIMED) {
				tiles_remaining = 1;
				break;
			}

	if (!tiles_remaining) {
		player = DRAW;
		game_over();
		return;
	}

	switch_players();
}
