0, "O"=>0, "T"=>0); } $state = $_POST["state"]; if (!$state || $_POST["new"] || $_POST["reset"]) $state="........."; $pair = "OX"; for ($i = 0; $i < 9; $i++) { if ($_POST["c" . $i]) $state[$i] = $pair[unplayed($state)%2]; } for ($i = 0; $i < 9; $i++) { if ($state[$i] == ".") echo "
"; else echo "
{$state[$i]}
"; } echo "
"; echo "
"; if ($result = check_win($state)) { $scores[$result] += 1; generate_cookie($scores); if ($result == "T") new_game("Tie!", $scores); else new_game("$result Wins!", $scores); } else { show_stats($scores); } echo ""; echo "
"; function generate_cookie($scores) { $r = array(); foreach ($scores as $which => $score) $r[] = "$which:$score"; setcookie("ttt_cookie", join($r, "/"), time() + 24*60*60); } /* * Given a nine-character string representing the state of the game... * Return "X" or "O" if either has won * Return "T" if all cells filled but tie * Return false otherwise * * The string "X...O...X" represents an "X" in the upper left, an "O" in the * middle, and an "X" in the lower right. */ function check_win($state) { foreach (explode(".", "036.147.258.012.345.678.048.246") as $win) { $first = $state[(int)$win[0]]; $second = $state[(int)$win[1]]; $third = $state[(int)$win[2]]; if ($first !== "." && $first == $second && $second == $third) { return $first; } } if (unplayed($state) == 0) return "T"; return false; } /* * Return the number of unplayed cells. count_chars is overkill for this but fun to use! */ function unplayed($state) { $counts = count_chars($state,0); $rval = $counts[ord(".")]; return $rval; } function show_stats($scores) { ?> wins for X, wins for O, ties