<?php
error_reporting(0);
$random_number = rand(1, 500);
setcookie('playing', '0', time() + (86400 * 30), "/");
if(empty($_POST['submit']) && $_COOKIE['playing'] != 1){
setcookie('number', $random_number, time() + (86400 * 30), "/");
setcookie('attempts', '1', time() + (86400 * 30), "/");
}
?>
<form method="POST">
<font color="red">Número generado...</font><br><hr style="width: 250px; float: left;"><br>
Adivinar número: <input type="number" name="numero" style="width: 40px">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$number = $_POST['numero'];
$cookie_number = $_COOKIE['number'];
$attempts = $_COOKIE['attempts'];
setcookie('playing', '1', time() + (86400 * 30), "/");
function attempts_left($valor){
if($valor == 1){ $valor = 9;
}elseif($valor == 2){ $valor = 8;
}elseif($valor == 3){ $valor = 7;
}elseif($valor == 4){ $valor = 6;
}elseif($valor == 5){ $valor = 5;
}elseif($valor == 6){ $valor = 4;
}elseif($valor == 7){ $valor = 3;
}elseif($valor == 8){ $valor = 2;
}else{ $valor = 1; }
return $valor;
}
$attempts_left = attempts_left($_COOKIE['attempts']);
if($number != $cookie_number && $attempts < 10){
$another_try = $attempts+1;
echo '<hr style="width: 250px; float: left; margin-top: -2px;"><br>Error, te queda'; if($attempts_left > 1){ echo 'n';} echo ' <b>'.$attempts_left.'</b> intento'; if($attempts_left > 1){ echo 's';}
setcookie('attempts', $another_try, time() + (86400 * 30), "/");
}elseif($number != $cookie_number && $attempts == 10){
echo '<hr style="width: 250px; float: left; margin-top: -2px;"><br>Error, perdiste todos tus intentos. <meta http-equiv="Refresh" content="1;url=/">';
}else{
echo 'Has adivinado con éxito el número: <b>'.$cookie_number.'</b>. <meta http-equiv="Refresh" content="3;url=/">';
setcookie('playing', '0', time() + (86400 * 30), "/");
}
}
?>