Last active
August 29, 2015 14:10
-
-
Save vrana/a8c39f6ed01cc17005c2 to your computer and use it in GitHub Desktop.
Piškvorky naslepo, http://knesl.com/articles/view/okomentovany-zdrojak-piskvorek
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ahoj v piškvorkách naslepo. | |
Povolené příkazy jsou: | |
new - nová hra | |
quit - konec | |
[a-i][0-9] - tah na pole, kde řada je pozice a, b, c, d, e, f, g, h, i. Sloupec je 1 až 9. | |
Formát zápisu je např. e5. | |
<?php | |
function isWinningInDirection(array $field, $x, $y, $a, $b) { | |
// průzkum jedním směrem | |
for ($i = 1; $i < 5; $i++) { | |
$yb = $y - $i * $b; | |
$xa = $x - $i * $a; | |
if (!isset($field[$yb][$xa]) || $field[$yb][$xa] != $field[$y][$x]) { | |
break; | |
} | |
} | |
// průzkum druhým směrem | |
for ($j = 1; $j < 5; $j++) { | |
$yb = $y + $j * $b; | |
$xa = $x + $j * $a; | |
if (!isset($field[$yb][$xa]) || $field[$yb][$xa] != $field[$y][$x]) { | |
return ($i + $j - 1 >= 5); | |
} | |
} | |
return true; | |
} | |
function isWinning(array $field, $x, $y) { | |
return isWinningInDirection($field, $x, $y, 1, 0) | |
|| isWinningInDirection($field, $x, $y, 0, 1) | |
|| isWinningInDirection($field, $x, $y, 1, 1) | |
|| isWinningInDirection($field, $x, $y, 1, -1) | |
; | |
} | |
function isFull(array $field) { | |
foreach ($field as $row) { | |
foreach ($row as $val) { | |
if ($val == '_') { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
$playing = 'o'; | |
while (true) { | |
$field = array_fill(1, 9, array_fill(1, 9, '_')); | |
while (true) { | |
$playing = ($playing == 'x' ? 'o' : 'x'); | |
// získání vstupu od uživatele | |
while (true) { | |
echo "Hráč $playing: "; | |
$input = rtrim(fgets(STDIN)); | |
if ($input == "new") { | |
break 2; | |
} elseif ($input == "quit") { | |
echo "Naviděnou.\n"; | |
exit; | |
} | |
$y = ord(substr($input, 0, 1)) - ord('a') + 1; | |
$x = substr($input, 1, 1); | |
if (strlen($input) != 2 || !isset($field[$y][$x])) { | |
echo "Tah ve špatném formátu.\n"; | |
} elseif ($field[$y][$x] != '_') { | |
echo "Pole je zabráno, hraj znovu.\n"; | |
} else { | |
break; | |
} | |
} | |
$field[$y][$x] = $playing; | |
if (isWinning($field, $x, $y)) { | |
echo "VÝHRA! Gratulace hráči $playing.\n"; | |
break; | |
} elseif (isFull($field)) { | |
echo "Remíza, hrací pole zaplněno.\n"; | |
break; | |
} | |
} | |
// zobrazení hracího pole | |
foreach ($field as $row) { | |
foreach ($row as $val) { | |
echo "$val "; | |
} | |
echo "\n"; | |
} | |
echo "Nová hra.\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment