Skip to content

Instantly share code, notes, and snippets.

@vrana
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrana/a9f2bdcea5d3d03c04c9 to your computer and use it in GitHub Desktop.
Save vrana/a9f2bdcea5d3d03c04c9 to your computer and use it in GitHub Desktop.
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
class BlindTicTacToe {
protected $field;
protected $x, $y;
protected $playing = 'o';
public function play($size) {
$this->field = array_fill(1, $size, array_fill(1, $size, '_'));
while (true) {
$this->playing = ($this->playing == 'x' ? 'o' : 'x');
if (!$this->getInput()) {
return;
}
$this->field[$this->y][$this->x] = $this->playing;
if ($this->isWinning()) {
echo "VÝHRA! Gratulace hráči $this->playing.\n";
break;
} elseif ($this->isFull()) {
echo "Remíza, hrací pole zaplněno.\n";
break;
}
}
// zobrazení hracího pole
foreach ($this->field as $row) {
foreach ($row as $val) {
echo "$val ";
}
echo "\n";
}
}
protected function getInput() {
while (true) {
echo "Hráč $this->playing: ";
$input = rtrim(fgets(STDIN));
if ($input == "new") {
return false;
} elseif ($input == "quit") {
echo "Naviděnou.\n";
exit;
}
$this->y = ord(substr($input, 0, 1)) - ord('a') + 1;
$this->x = substr($input, 1, 1);
if (strlen($input) != 2 || !isset($this->field[$this->y][$this->x])) {
echo "Tah ve špatném formátu.\n";
} elseif ($this->field[$this->y][$this->x] != '_') {
echo "Pole je zabráno, hraj znovu.\n";
} else {
return true;
}
}
}
protected function isWinning() {
return $this->isWinningInDirection(1, 0)
|| $this->isWinningInDirection(0, 1)
|| $this->isWinningInDirection(1, 1)
|| $this->isWinningInDirection(1, -1)
;
}
protected function isWinningInDirection($a, $b) {
// průzkum jedním směrem
for ($i = 1; $i < 5; $i++) {
$yb = $this->y - $i * $b;
$xa = $this->x - $i * $a;
if (!isset($this->field[$yb][$xa]) || $this->field[$yb][$xa] != $this->field[$this->y][$this->x]) {
break;
}
}
// průzkum druhým směrem
for ($j = 1; $j < 5; $j++) {
$yb = $this->y + $j * $b;
$xa = $this->x + $j * $a;
if (!isset($this->field[$yb][$xa]) || $this->field[$yb][$xa] != $this->field[$this->y][$this->x]) {
return ($i + $j - 1 >= 5);
}
}
return true;
}
protected function isFull() {
foreach ($this->field as $row) {
foreach ($row as $val) {
if ($val == '_') {
return false;
}
}
}
return true;
}
}
$ticTacToe = new BlindTicTacToe;
$size = 9;
while (true) {
$ticTacToe->play($size);
echo "Nová hra.\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment