in_array搜索字符串时总是返回 false



我目前正在用PHP编写一个简单的战舰游戏。在游戏开始时,我在 5 x 5 的板上生成三个飞船位置,每艘船占据一个正方形:

function generate_three_battleships($ships){
for ($n=0; $n<3; $n++){
// Generate new position, returned from function as string
$ship_position = generate_new_position();
// Check to ensure that the position is not already occupied - if so, recast 
if (in_array($ship_position, $ships)){
$ship_position = generate_new_position();
}//if
// Assign position to array
array_push($ships, $ship_position);
}//for
}//generate_three_battleships

每个位置都表示为一个两位数的字符串,表示笛卡尔坐标(例如,"32"表示 y = 3,x = 2(。此任务由generate_new_position函数处理:

当游戏开始时,用户将输入他们对行和列的猜测:

function generate_new_position(){
// Generate x and y coordinates - cast to string for storage
$ship_row = (string)random_pos();
$ship_col = (string)random_pos();
$ship_position = $ship_row.$ship_col;
return $ship_position;
}//generate_new_position

然后用户输入他们对行和列的猜测,游戏将检查那里是否有船:

// Generate battleships
generate_three_battleships($ships);
for($turn=1; $turn <= GUESSES; $turn++){
// First check to see if all ships have been sunk. If not, proceed with the game
if ($ships_sunk < 3){
$guess_row = (string)readline("Guess a row: ");
$guess_col = (string)readline("Guess a column: ");
$guess = $guess_row.$guess_col; // format guesses as strings
if(($guess_row=="") || ($guess_col=="") || ($guess_row < 0) || ($guess_col < 0) || ($guess_row >= BOARDSIZE) || ($guess_col >= BOARDSIZE)){
print("Oops, that's not even in the ocean. n");
}
else if(array_search($guess, $ships) != false){
print("Congratulations! You sunk one of my battleships!n");
$board[$guess_row][$guess_col] = "X";
$ships_sunk++;
}
}

但是,in_array 函数始终为每个猜测返回 false,即使该猜测实际上在 $ships 数组中也是如此。我看不出我哪里出错了,因为我已经明确地将所有内容都转换为字符串。我错过了一些明显的东西吗?

正如一些人所问的,generate_three_battleships执行后$shipsvar_dump的输出如下:

array(3) {
[0]=>
string(2) "12"
[1]=>
string(2) "30"
[2]=>
string(2) "03"
}

不幸的是,我没有完整的答案,因为我缺少一些信息来了解问题所在。

您可以通过使用 var_dump 打印数组的内容来调试正在发生的事情,以查看$ships的实际内容,并可能强制generate_new_position始终返回相同的值。

如果你自己不能解决这个问题,你能在for循环之前和之后发布$ships的内容(使用var_dump(吗?

最新更新