Problem when validating ships in play to sink the fleet

0

I am trying to create the game of sinking the fleet, keeping the ships in arrays. I want to make a table in which the quadrants with the boat differ (by class ). The problem is that when checking, only the first box recognizes me.

This is my code:

<?php

$lancha=array(71);
$destructor=array(18,28);
$submarino=array(33,43,53);
$portaaviones=array(75,76,77,78);
$barcos=array($lancha,$destructor,$submarino,$portaaviones);

session_start();
$_SESSION['barcos']=$barcos;

echo "<table>";
for($a=0;$a<10;$a++){
  echo "<tr>";
  for($b=0;$b<10;$b++){
    if(valida($a.$b))
      echo "<td class='verde'>".$a.$b."</td>";
    else if(valida($a.$b))
      echo "<td class='verde'>".$a.$b."</td>";
    else
      echo "<td>".$a.$b."</td>";
  }
  echo "</tr>";
}
echo "</table>";

function valida($p){
  foreach ($_SESSION['barcos'] as $key) {
    foreach ($key as $q => $value) {
      if($p==$value)
        return true;
      else
      return false;
    }
  }
}
    
asked by incarnati0n 05.03.2018 в 23:57
source

1 answer

0

The problem is in the valida function and how false is returned in concrete:

  foreach ($_SESSION['barcos'] as $key) {
    foreach ($key as $q => $value) {
      if($p==$value)
        return true;
      else
      return false;
    }
  }

As it is set right now, the first element of the array is checked, if it matches: true is returned; and if not ... it returns false stopping the checks of the rest of the elements of the array. The solution would then be to move the return false; to the end of the function instead of having it as else so that only false is returned after checking all the possible elements of the array:

  foreach ($_SESSION['barcos'] as $key) {
    foreach ($key as $q => $value) {
      if($p==$value)
        return true;
    }
  }
  return false;
}

With that change, the code would be like this and it works:

<?php

$lancha=array(71);
$destructor=array(18,28);
$submarino=array(33,43,53);
$portaaviones=array(75,76,77,78);
$barcos=array($lancha,$destructor,$submarino,$portaaviones);

session_start();
$_SESSION['barcos']=$barcos;

echo "<table>";
for($a=0;$a<10;$a++){
  echo "<tr>";
  for($b=0;$b<10;$b++){
    if(valida($a.$b))
      echo "<td class='verde'>".$a.$b."</td>";
    else if(valida($a.$b))
      echo "<td class='verde'>".$a.$b."</td>";
    else
      echo "<td>".$a.$b."</td>";
  }
  echo "</tr>";
}
echo "</table>";

function valida($p){
  foreach ($_SESSION['barcos'] as $key) {
    foreach ($key as $q => $value) {
      if($p==$value)
        return true;
    }
  }
  return false;
}
    
answered by 07.03.2018 в 13:54