<?php
class MineSweeper{
private $data = NULL;
private $map;
function debug(){
header('Content-Type:text/plain');
}
function createMap($data){
$this->data = $data;
if(!preg_match('/^[\*\.\r\n]+$/', $this->data)){
throw new Exception('Invalid input provided. Only asterik (*) and/or dot (.) is allowed.');
}
// breaking input to lines
$lines = preg_split('/\r\n/', $this->data);
$tmp_line = NULL; // holding previous line for comparsion
// lines index
foreach ($lines as $lnum=>$line){
// lines should be equal in length
if ($tmp_line != NULL && strlen($tmp_line) != strlen($line) ){
throw new Exception('Invalid input provided, please correct the format. Not all rows are equal.');
}else {
$tmp_line = $line;
// removing back spac and line break and spliting into charatcers (means multi dimension array)
$lines[$lnum] = str_split(str_replace('\r\n','', $line));
}
}
// N= lines
// M = Characters
$M = count($lines[0]);
$this->map = new MineMap($lines);
}
function display(){
$this->map->display();
}
}
class MineMap{
private $lines = array();
private $N;
private $M;
function __construct($lines){
$this->lines = $lines;
$this->N = count($lines);
$this->M = count($lines[0]);
foreach($this->lines as $lnum => $line){
$this->lines[$lnum] = array_map(function($str){
return (trim($str) == "*") ? trim($str) : 0;
}, $line);
}
foreach($this->lines as $lnum => $line){
foreach($line as $index => $str){
if ($str === "*"){
$this->mineFound($lnum, $index);
}
}
}
}
function incValue($n, $m){
if ($m < $this->M && $n < $this->N && $n >= 0 && $m >= 0){
$this->lines[$n][$m]++;
}
}
function mineFound($n, $m){
$this->incValue($n, $m+1);
$this->incValue($n, $m-1);
$this->incValue($n+1, $m-1);
$this->incValue($n+1, $m);
$this->incValue($n+1, $m+1);
$this->incValue($n-1, $m-1);
$this->incValue($n-1, $m);
$this->incValue($n-1, $m+1);
}
function display(){
echo "<table cellspacin='5px'>";
foreach ($this->lines as $line){
echo "<tr>";
foreach($line as $str){
echo "<td style=''><button data='$str' class='btn btn-primary'> </td>";
}
echo "</tr>";
}
echo "</table>";
}
}
preferences:
30.32 ms | 402 KiB | 5 Q