您的位置:首页 > 编程语言 > PHP开发

PHP版消灭星星实现算法

2015-09-09 13:04 513 查看
author: ericniu<niujiaming0819@163.com>
<?php
/* 打印星盘
*
* stars: 1:赤 2:橙 3:红 4:绿 5:青 6:蓝 7:紫
*/
function show_stars($stars, $star_h, $star_w) {

for ($i = 0; $i < $star_h; $i++) {
for ($j = 0; $j < $star_w; $j++) {
echo $stars[$i][$j] . " ";
}
echo "\r\n";
}
echo "\n\n";
}

/* 星星生成
*
* stars: 1:赤 2:橙 3:红 4:绿 5:青 6:蓝 7:紫
*/
function star_init($stars = array(1, 2, 3, 4, 5), $star_h = 20, $star_w = 20) {
$ret = array();

for ($i = 0; $i < $star_h; $i++) {
for ($j = 0; $j < $star_w; $j++) {
$ret[$i][$j] = rand(1, count($stars));
}
}

return $ret;
}
/**
* 获取可以消除的星星
*/
function star_destroy(&$stars_des, $stars, $star_h, $star_w, $x, $y) {
if($x - 1 >= 0 && $stars[$x - 1][$y] == $stars[$x][$y]) { //(x,y)左方是否有同色的

$t = $x - 1;
$k = "{$t}_{$y}";
if (!isset($stars_des[$k])) {
$stars_des[$k] = 1;
star_destroy($stars_des, $stars, $star_h, $star_w, $t, $y);
}

}
if ($y + 1 < $star_w && $stars[$x][$y + 1] == $stars[$x][$y]) { //(x,y)下方是否有同色的

$t = $y + 1;
$k = "{$x}_{$t}";
if (!isset($stars_des[$k])) {
$stars_des[$k] = 1;
star_destroy($stars_des, $stars, $star_h, $star_w, $x, $t);
}

}
if ($x + 1 < $star_h && $stars[$x + 1][$y] == $stars[$x][$y]) { //(x,y)右方是否有同色的

$t = $x + 1;
$k = "{$t}_{$y}";
if (!isset($stars_des[$k])) {
$stars_des[$k] = 1;
star_destroy($stars_des, $stars, $star_h, $star_w, $t, $y);
}

}
if ($y - 1 >= 0 && $stars[$x][$y - 1] == $stars[$x][$y]) { //(x,y)右方是否有同色的

$t = $y - 1;
$k = "{$x}_{$t}";
if (!isset($stars_des[$k])) {
$stars_des[$k] = 1;
star_destroy($stars_des, $stars, $star_h, $star_w, $x, $t);
}

}
}

/**
* 消除星星
*/
function star_result(&$stars, $star_h, $star_w, $stars_des) {
if(count($stars_des) <= 1) {
return false;
}
foreach ($stars_des as $k => $v) {
$t = explode('_', $k);
$x = $t[0];
$y = $t[1];
$stars[$x][$y] = 0;
}

for ($y = 0; $y < $star_h; $y++) {
while(true) {
for($xx = $star_w - 1; $xx >= 0 && $stars[$xx][$y] > 0; $xx--);
if($xx < 0) { break; }

for($i = $xx - 1; $i >= 0 && $stars[$i][$y] == 0; $i--);
if($i < 0) { break; }

$stars[$xx][$y] = $stars[$i][$y];
$stars[$i][$y] = 0;
}

}
return true;
}

$star_h = 10;
$star_w = 10;
$stars = star_init(array(1, 2, 3,), $star_h, $star_w);
show_stars($stars, $star_h, $star_w);
$score = 0;
while(true) {
echo "score: " . $score . "\n";
echo "row[0-9]:";
$x = intval(fgets(STDIN));

echo "col[0-9]:";
$y = intval(fgets(STDIN));

$stars_des = array();
$k = "{$x}_{$y}";
$stars_des[$k] = 1;

star_destroy($stars_des, $stars, $star_h, $star_w, $x, $y);

star_result($stars, $star_h, $star_w, $stars_des);
show_stars($stars, $star_h, $star_w);
count($stars_des) > 1 && $score += count($stars_des) * count($stars_des) * 5;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: