I'm learning PHP and I'm programming a sinking fleet game with a single ship and a hundred squares. The problem I am having is that when I request the server the value of the session that stores the value of the box in which the ship is, it does not find it and I do not finish finding the solution to the problem no matter how hard I try to search for it . I have three files:
- index.php: It is from where the missile is "launched" to try to guess the square of the ship.
- trigger.php: This is where the grid is generated from and a box value is assigned to the ship, storing it within a session.
- control.php: It is from where the user's response is processed, the value of the ship's session is read and compared, returning the result.
Here are the codes for each:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hundir La Flota</title>
</head>
<body>
<form action="./control.php" method="post">
¿Dónde vas a golpear? <br/><input type='text' name='misil'>
<input type='submit' value='Comprobar'>
</form>
</body>
</html>
trigger.php
<?php
$cuadriculas = 100;
$letras = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
function generarCuadricula($cuadriculas, $letras) {
global $posiciones;
$posiciones = array();
$numActual = 1;
$siguiente = 0;
while(count($posiciones) < $cuadriculas){
if($numActual == 11) {
$numActual = 1;
$siguiente += 1;
};
array_push($posiciones, $letras[$siguiente] . $numActual);
$numActual++;
};
};
function asignarCuadricula($posiciones) {
session_start();
$posBarco = $posiciones[rand(0, 99)];
$_SESSION['barco'] = $posBarco;
};
generarCuadricula($cuadriculas, $letras);
asignarCuadricula($posiciones);
?>
control.php
<?php
session_start();
$posBarco = $_SESSION["barco"];
$uHit = $_POST["misil"];
function comprobarSiGolpe($uHit){
echo "Has golpeado en: " . $uHit . "<br/>";
echo "Posición barco: " . $posBarco . "<br/>";
if($uHit == $_SESSION["barco"]){
echo "¡Enhorabuena! Has hundido el barco." . "<br/>";
} else {
echo "Has fallado, vuelve a intentarlo." . "<br/>";
echo '<a href="./index.php">Volver</a>';
};
};
comprobarSiGolpe($uHit);
?>