<?php
class seaBot
{
private $map = [];
private $true_cell = [];
private $game_id = '';
public function __construct($game_id)
{
$this->game_id = $game_id;
if (!$this->load()) {
$this->init();
$this->save();
}
}
public function getCell()
{
$cell_index = rand(0, count($this->map) - 1);
$cell = $this->map[$cell_index];
unset($this->map[$cell_index]);
$this->map = array_values($this->map);
return $cell;
}
public function init()
{
for ($x = 0; $x < 10; $x++) {
for ($y = 0; $y < 10; $y++) {
$this->map[] = [$x, $y];
}
}
}
public function save()
{
$data = [
'map' => $this->map,
'true_cell' => $this->true_cell
];
$c = new Memcached();
$c->addServer('localhost', 11211);
$c->set($this->game_id, $data, 60);
}
public function load()
{
$c = new Memcached();
$c->addServer('localhost', 11211);
$data = $c->get($this->game_id);
if ($data) {
$this->map = $data['map'];
$this->true_cell = $data['true_cell'];
return true;
}
return false;
}
public function __destruct()
{
$this->save();
}
}
$json = file_get_contents("php://input");
if (empty($json)) {
exit;
}
$data = json_decode($json);
$game_id = $data->game_id;
$command = $data->game_command;
$game_id .= $_GET['bot_name'];
if ($game_id) {
$sea_bot = new seaBot($game_id);
}
else {
exit;
}
if ($command == 'start_new_game') {
echo json_encode(['response' => 'ok']);
}
if ($command == 'get_ship_location') {
$ship_location = [
[[0, 0]],
[[3, 1]],
[[5, 1]],
[[7, 1]],
[[2, 3], [1, 3]],
[[4, 3], [5, 3]],
[[7, 3], [8, 3]],
[[1, 5], [2, 5], [3, 5]],
[[5, 5], [6, 5], [7, 5]],
[[1, 7], [2, 7], [3, 7], [4, 7]]
];
echo json_encode(['ship_array' => $ship_location]);
}
if ($command == 'make_move') {
echo json_encode(['response' => $sea_bot->getCell()]);
}