<?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);

function isGameOver($board, $pin) {
	$pat = 
		'/X{3}|' . 
		'X..X..X..|' . 
		'.X..X..X.|' . 
		'..X..X..X|' . 
		'..X.X.X..|' . 
		'X...X...X|' . 
		'[^\.]{9}/i'; 
	if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
	return preg_match($pat, $board);
}


$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);


echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border=>';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
	echo '<tr>';
	for ($c = 0; $c < ROW_NUM; $c++) {
		$pin = $boardStr[$p];

		echo '<td>';		
		if ($gameOver || $pin != '.') echo '<span class=>', $pin, '</span>'; 
		else { 
			$boardDelta = $boardStr;
			$boardDelta[$p] = $turn;		
			echo '<a class= href=>';
			echo $boardStr[$p];
			echo '</a>';
		}

		echo '</td>';	
		$p++;
	}
	echo '</tr>';
	echo '<input type= name= value=/>';
}
echo '</table>';
echo '<a href=>Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';