Building on webnut's theory about using sessions to store the data....
Heres something I put together for you.
(commented as much as possible!)
PHP Code:
<?php # tic-tac-toe
// start a session to store the variables and array
session_start();
// restart the game by destroying the session
if(isset($_GET['restart'])) {
session_destroy();
}
// define players
$player_1 = 'X';
$player_2 = 'O';
if($_GET['player'] == 'X') { $player = $player_2; } else { $player = $player_1; }
echo "Your Turn, Player " . $player . "<br /><br />\n";
// define the board. This could be done in a loop.....
// check that the session count is not 1 ie: the game hasn't been started
if($_SESSION['count'] != 1) {
// setup array
$_SESSION['board'] = array(
"0"=>"[ * ]", "1"=>"[ * ]","2"=>"[ * ]","3"=>"[ * ]","4"=>"[ * ]","5"=>"[ * ]","6"=>"[ * ]","7"=>"[ * ]",
"8"=>"[ * ]","9"=>"[ * ]","10"=>"[ * ]","11"=>"[ * ]","12"=>"[ * ]","13"=>"[ * ]","14"=>"[ * ]","15"=>"[ * ]");
}
// if a turn has been made
if(isset($_GET['id'])) {
// set the session key corresponding to the passed id is set as the players character
$_SESSION['board'][$_GET['id']] = '[ ' . $player . ' ]';
// set the session counter to 1 to signify the game has begun
$_SESSION['count']=1;
}
?>
<style type="text/css">
a:link {
color: #000000;
text-decoration: none;
}
a:hover {
color: #FF0000;
text-decoration: none;
}
a:active {
color: #000000;
text-decoration: none;
}
</style>
<h2>Tic-Tac-toe!</h2>
<?php
// display board
foreach($_SESSION['board'] as $key=>$data) {
// if the key is divisible by 4, echo a <br>
if(($key%4) == 0) { echo '<br>';}
// if the data is equal to either X or O, dont offer a link
if($data == '[ X ]') { echo '[ X ]';
} elseif($data == '[ O ]') { echo '[ O ]'; } else
{
// else offer a link to click
echo '<a href="?player='.$player . '&id='.$key.'">'. $data . '</a>';
}
}
?>
<p><a href="?restart">restart</a></p>
You can extend it further by setting up an function to check if the rows/ columns add up to 4 of the same characters.
Hope this helps, let me know!
Cheers
Mike
Bookmarks