gpt4 book ai didi

php - 如何检测 "5 in a row"游戏中的对角线获胜 (PHP)

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:03 27 4
gpt4 key购买 nike

我必须编写一个不错的“5 连胜”小游戏。我已经成功检测到这样的行和列胜利:

对于行:

$same=0;
for($i=1;$i<=$size;$i++) for($j=1;$j<=$size;$j++){ /wins in a row
if((@$_SESSION["pos"][$i][$j] == @$_SESSION["pos"][$i][$j+1]) && @$_SESSION["pos"][$i][$j]!=0 ) ++$same; else $same=0;
if($same==4){
if($_SESSION["pos"][$i][$j]==1) $winner="First"; //will be read from DB
if($_SESSION["pos"][$i][$j]==2) $winner="Second"; //will be read from DB
print $winner.' player WON!<br />';
}
}

对于列,它是相同的,但相反,所以这很容易。现在我的问题是,您如何检测对角线获胜?我试图搜索它,但找不到任何我可以使用(或理解)的东西。我只被允许使用 PHP。

What is what:
$same = same symbol counter
$_SESSION["pos"][$i][$j] = the 2D array of coordinates of the board (starting from 1,1 not 0,0)
indexes are the coordinates, values can be 0 (empty space) or 1 (symbol1) or 2 (symbol2)
$size = size of the board (always N x N)

您不必向我灌输完整的代码,我只需要了解如何操作即可。

最佳答案

让我们的游戏区域宽度为 5。这有点棘手或 hack,但我们可以使用长字符串这样的数组并找到像 XXXXX 这样的子字符串。 , 或 00000 (用于行检查),或 X....{5 times} (用于列检查)或 X.....{5 times} (用于\对角线检查)和 X...{5 times}对于/对角线。

所以我们只需要替换.使用任何符号并找到这样的模式。这个任务是我们可以使用正则表达式的时候。我们只需要将该模式与 preg_match() 匹配即可.

我不知道更快的方式,但它似乎是原始的(示例仅用于 X 检查):

<?php
$area = array(
array('x','x','x','x','x'),
array('0','0','x','x','0'),
array('x','x','x','x','0'),
array('0','0','x','x','x'),
array('x','0','x','0','x'),
);

//get the long string of that array
$fullstring = '';
foreach($area as $string) {
$fullstring .= implode('', $string)."|";
}

//check long string for such patterns
$win_by_column = preg_match('/x.{5}x.{5}x.{5}x.{5}x/i', $fullstring); //5 game area width
$win_by_row = preg_match('/x{5}/i', $fullstring); //5 same in rows
$win_by_bs_diagonal = preg_match('/x.{6}x.{6}x.{6}x.{6}x/i', $fullstring); // \ diagonal, 5 is $area width + 1
$win_by_s_diagonal = preg_match('/x.{4}x.{4}x.{4}x.{4}x/i', $fullstring); // / diagonal, 4 is $area width - 1.

//output the results
var_dump($win_by_column);
var_dump($win_by_row);
var_dump($win_by_bs_diagonal);
var_dump($win_by_s_diagonal);
?>

如果您不熟悉正则表达式,这也是一个好的开始 ;)

UPD. 我已经更新了代码。我在数组字符串中插入字符串分隔符。所以现在我们需要在列检查中检查 5 个点(任何符号),在对角线检查中检查 6 个点。此硬编码值相应地计算为 width 和 width+1 。为了阅读和理解的简单性,我没有插入 $area图案宽度。

关于php - 如何检测 "5 in a row"游戏中的对角线获胜 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20316090/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com