package edu.compsci;

import cs1.android.*;

// Implementation of the popular Tic-Tac-Toe game. Tap a cell to make a move.

public class TicTacToeApp extends AndroidApp
{
	// board's upper-left corner and cell size
	final int BOARD_ULX = 80;
	final int BOARD_ULY = 160;
	final int CELL_SIZE = 80;

	// Draw the game game board as a grid of images.
	// The names of the images match the board entries
	// 'e' -> "e.png", 'x' -> "x.png", 'o' -> "o.png"
	public void drawBoard(char[][] board)
	{
		canvas.clear();
		for (int r = 0; r < board.length; ++r) {
			for (int c = 0; c < board[r].length; ++c) {
				int x = BOARD_ULX + c*CELL_SIZE;
				int y = BOARD_ULY + r*CELL_SIZE;
				canvas.drawImage(x, y, board[r][c]+".png");
			}
		}
	}

	// Check if the move in cell (r, c) is a win. Assumes
	// cell (r, c) contains either 'x' or 'o'.
	public boolean isWinningMove(char[][] board, int r, int c)
	{
		if (board[r][0] == board[r][1] && board[r][1] == board[r][2]) {
			return true;
		}
		else if (board[0][c] == board[1][c] && board[1][c] == board[2][c]) {
			return true;
		}
		else {
			boolean leftDiag = (board[0][0] == board[r][c] && board[1][1] == board[r][c] && board[2][2] == board[r][c]);
			boolean rightDiag = (board[2][0] == board[r][c] && board[1][1] == board[r][c] && board[0][2] == board[r][c]);
			return leftDiag || rightDiag;
		}
	}

	// Switches the given player.
	char switchPlayer(char player)
	{
		if (player == 'x') { return 'o'; }
		else               { return 'x'; }
	}

	public void run() 
	{	
		// the empty board representations
		char[][] board = { 
				{ 'e', 'e', 'e'},
				{ 'e', 'e', 'e'},
				{ 'e', 'e', 'e'} 
		};

		canvas.setBackground("DarkKhaki");

		char player = 'x';
		int moves = 0;
		boolean playerWon = false;

		// as long as no one has won and there are moves left
		while ( playerWon == false && moves < 9 ) {
			drawBoard(board);
			String name = (""+player).toUpperCase();
			canvas.drawText(canvas.getWidth()/2, canvas.getHeight()/8, 
					name + "'s turn!", 24, "white");

			// wait for the player to touch a cell and convert the touch
			// coordinates to (row, col) position in the board.
			Touch touch = canvas.waitForTouch();
			int row = (touch.getY() - BOARD_ULY + CELL_SIZE/2) / CELL_SIZE;
			int col = (touch.getX() - BOARD_ULX + CELL_SIZE/2) / CELL_SIZE;

			// handle the touch only if the cell is empty
			// update the board, number of moves and check or a win
			if (board[row][col] == 'e') {
				board[row][col] = player;
				moves = moves + 1;
				playerWon = isWinningMove(board, row, col);
				if (playerWon == false) {
					player = switchPlayer(player);
				}
			}
		}

		// redraw the board and show a final message for a win or a tie
		drawBoard(board);

		if (playerWon == true) {
			canvas.drawText(canvas.getWidth()/2, canvas.getHeight()/8, 
					"Player " + player + " WON!", 24, "white");
		}
		else {
			canvas.drawText(canvas.getWidth()/2, canvas.getHeight()/8, 
					"The game is a tie!", 24, "white");			
		}
	}
}
