Skip to content

Instantly share code, notes, and snippets.

@Tyrael
Last active December 16, 2015 10:28
Show Gist options
  • Save Tyrael/5419963 to your computer and use it in GitHub Desktop.
Save Tyrael/5419963 to your computer and use it in GitHub Desktop.
Tic-Tac-Toe-Tomek
$ cat test.txt |php -f index.php
Case #1: X won
Case #2: Draw
Case #3: Game has not completed
Case #4: O won
Case #5: O won
Case #6: O won
<?php
$raw = trim(file_get_contents('php://stdin'));
$temp = explode("\n", $raw, 2);
$numberOfBlocks = $temp[0];
if ($numberOfBlocks == 0) {
exit;
}
$rawBlocks = explode("\n\n", $temp[1]);
foreach ($rawBlocks as $i => $rawBlock) {
switch (selectWinner($rawBlock)) {
case -1:
echo "Case #".($i+1).": Game has not completed\n";
break;
case 0:
echo "Case #".($i+1).": Draw\n";
break;
case 1:
echo "Case #".($i+1).": X won\n";
break;
case 2:
echo "Case #".($i+1).": O won\n";
break;
}
}
function parseBlock($rawBlock) {
$block = array();
$rawRows = explode("\n", $rawBlock);
foreach ($rawRows as $i => $rawRow) {
foreach (str_split($rawRow) as $j => $field) {
$block[$i.$j] = $field;
}
}
return $block;
}
function selectWinner($rawBlock) {
$hasDot = strpos($rawBlock, '.');
$block = parseBlock($rawBlock);
static $winningLines = array(
array('00', '01', '02', '03'),
array('10', '11', '12', '13'),
array('20', '21', '22', '23'),
array('30', '31', '32', '33'),
array('00', '10', '20', '30'),
array('01', '11', '21', '31'),
array('02', '12', '22', '32'),
array('03', '13', '23', '33'),
array('00', '11', '22', '33'),
array('03', '12', '21', '30'),
);
foreach($winningLines as $winningLine){
$countX = 0;
$countO = 0;
foreach($winningLine as $field) {
switch ($block[$field]) {
case 'T':
$countX++;
$countO++;
break;
case 'X':
$countX++;
break;
case 'O':
$countO++;
break;
}
}
if ($countX == 4) {
return 1;
}
elseif ($countO == 4) {
return 2;
}
}
if ($hasDot) {
return -1;
}
return 0;
}
6
XXXT
....
OO..
....
XOXT
XXOO
OXOX
XXOO
XOX.
OX..
....
....
OOXX
OXXX
OX.T
O..O
XXXO
..O.
.O..
T...
OXXX
XO..
..O.
...O
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment