Skip to content

Instantly share code, notes, and snippets.

@nw
Created September 10, 2015 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nw/1fbd5016787edf60eb4b to your computer and use it in GitHub Desktop.
Save nw/1fbd5016787edf60eb4b to your computer and use it in GitHub Desktop.
<?php
$players = ["X", "O"];
$current_player_idx = getPlayerIdx();
$player = $players[$current_player_idx];
$next_player_idx = getNextPlayerIdx($current_player_idx);
$board = [
[null, null, null],
[null, null, null],
[null, null, null]
];
if(isset($_POST['select'])){
$parts = explode(',', $_POST['select']);
$board[$parts[0]][$parts[1]] = $player; // sets piece
if(isset($_POST['board'])) {
forEach ($_POST['board'] as $rowidx => $row) {
forEach ($row as $colidx => $col) {
$board[$rowidx][$colidx] = $col;
}
}
}
}
function debug($val){
$output = print_r($val, true);
echo "<pre>". $output ."</pre>";
}
function getCell($row, $col){
global $board;
$val = $board[$row][$col];
if(is_null($val)){
return "<input type='submit' value='$row,$col' name='select' />";
} else {
return "<h1>$val</h1><input type='hidden' name='board[$row][$col]' value='$val' />";
}
}
function getPlayerIdx(){
$val = 1;
if(isset($_POST['player'])){
$val = intval($_POST['player']);
}
return $val;
}
function getNextPlayerIdx($idx){
global $players;
$val = $idx;
$val++;
if($val >= count($players)) $val = 0;
return $val;
}
?>
<html>
<head>
<title>Tic Tac Toe</title>
</head>
<body>
<form method="POST">
<input type="hidden" value="<?= $next_player_idx; ?>" name="player" />
<table border="1", cellspacing="0" cellpadding="25">
<tr>
<td><?= getCell(0,0); ?></td>
<td><?= getCell(0,1); ?></td>
<td><?= getCell(0,2); ?></td>
</tr>
<tr>
<td><?= getCell(1,0); ?></td>
<td><?= getCell(1,1); ?></td>
<td><?= getCell(1,2); ?></td>
</tr>
<tr>
<td><?= getCell(2,0); ?></td>
<td><?= getCell(2,1); ?></td>
<td><?= getCell(2,2); ?></td>
</tr>
</table>
</form>
<?= debug($board); ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment