Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Запускать с ключами командной строки:
- * 1 - размер поля (поле квадратное)
- * 2 - количество фигур в линии, которых достаточно для выигрыша
- *
- * В рантайме принимает команды:
- * X,Y (два числа через запятую) - координаты, считая с нуля
- * see - посмотреть поле
- */
- $dimension = $argv[1];
- $to_win = $argv[2];
- define('MY', 'o');
- define('HIS', 'x');
- define('LINE', $to_win);
- define('DIM', $dimension);
- $field = array();
- for ($i = 0; $i < $dimension; $i++) {
- $field[$i] = array();
- $field[$i] = array_fill(0, $dimension, '-');
- }
- $f = fopen('php://stdin', 'r');
- while ($line = fgets($f)) {
- list($x, $y) = explode(',', trim($line));
- if (isset($x) && isset($y)) {
- $field[$x][$y] = HIS;
- ai($field);
- }elseif(trim($line) == 'see'){
- echoField($field);
- }
- }
- function echoField(&$field) {
- foreach ($field as $row) {
- foreach ($row as $value) {
- echo $value . "\t";
- }
- echo "\n";
- }
- }
- /**
- * ai =)
- */
- function ai(&$field) {
- for ($i = 0; $i < DIM; $i++) {
- for ($j = 0; $j < DIM; $j++) {
- if ($field[$i][$j] == '-') {
- $empty[] = array($i, $j);
- }
- $threat = checkLine($i, $j, LINE - 2, 0, $field);
- if ($threat && $threat[0] + 1 < DIM) {
- makeTurn($threat[0] + 1, $threat[1], $field);
- return;
- }
- $threat = checkLine($i, $j, 0, LINE - 2, $field);
- if ($threat && $threat[1] + 1 < DIM) {
- makeTurn($threat[0], $threat[1] + 1, $field);
- return;
- }
- $threat = checkLine($x, $y, LINE - 2, LINE - 2, $field);
- if ($threat && $threat[0] + 1 < DIM && $threat[1] + 1 < DIM) {
- makeTurn($threat[0] + 1, $threat[1] + 1, $field);
- return;
- }
- }
- }
- $xy = array_rand($empty);
- makeTurn($empty[$xy][0], $empty[$xy][1], $field);
- }
- function makeTurn($x, $y, &$field) {
- $field[$x][$y] = MY;
- echo "my turn: " . ($x) . ',' . ($y) . "\n";
- }
- function checkLine($x, $y, $r, $d, &$field) {
- $what_to_check = false;
- if ($field[$x][$y] == '-' || $field[$x][$y] == NULL) {
- return false;
- } else {
- $what_to_check = $field[$x][$y];
- }
- for ($i = $x; $i <= $x + $r; $i++) {
- for ($j = $y; $j <= $y + $d; $j++) {
- //echo "$i, $j \n";
- if ($field[$i][$j] !== $what_to_check) {
- return false;
- }
- }
- }
- return array($i - 1, $j - 1);
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement