Ver código fonte

Added comments

add-comments
Pepijn 3 anos atrás
pai
commit
6292655d0d
9 arquivos alterados com 134 adições e 132 exclusões
  1. BIN
      db_zeeslag.db
  2. 1
    1
      includes/dbase.inc
  3. 54
    77
      includes/functions.inc
  4. 0
    11
      includes/head.inc
  5. 27
    20
      includes/ships.inc
  6. 4
    4
      index.php
  7. 47
    17
      naval_battle.php
  8. 1
    0
      scores.php
  9. 0
    2
      signup.php

BIN
db_zeeslag.db Ver arquivo


+ 1
- 1
includes/dbase.inc Ver arquivo

@@ -7,6 +7,7 @@ class db
$this->database = new SQLite3('db_zeeslag.db');
}


public function checkLogin($usrName, $password)
{
$stmt = $this->database->prepare("SELECT * FROM users WHERE usr_name=:usrName AND password=:pass");
@@ -42,7 +43,6 @@ class db
{

$date = new DateTime(date('d-m-Y H:i:s'), new DateTimeZone('UTC'));
$formattedDate = $date;
$stmt = $this->database->prepare("INSERT INTO games (usr_id, date, difficulty, won, shots_left) VALUES(:usrId, :date, :difficulty, :won, :shotsLeft)");
$stmt->bindValue('usrId', $usr_id, SQLITE3_TEXT);
$stmt->bindValue('date', $date->format('d-m-Y H:i:s'), SQLITE3_TEXT);

+ 54
- 77
includes/functions.inc Ver arquivo

@@ -49,6 +49,8 @@ function writeScore($usr_id, $diff, $won, $shotsLeft)

$db->writeScore($usr_id, $diff, $won, $shotsLeft);
}

// Deze funtie is zichtbaar in de scores tab
function printScores($usr_id)
{
global $db;
@@ -63,6 +65,7 @@ function printScores($usr_id)
return $html;
}

// Message printen met $type = css stijl
function printMessage($message, $type)
{
unset($_SESSION['mess']);
@@ -78,11 +81,10 @@ function printMessage($message, $type)
$_SESSION['mess'] = $message;
}

// Session timeout control
function checkSession()
{

//TODO: Als sessie verloopt, maar is er is nog een spel bezig, moet deze functie de huidige spelgegevens gaan opslaan in de database

$now = time();
$delta = $now - $_SESSION['cur_session_time'];
$timeSpan = 30 * 60;
@@ -102,99 +104,45 @@ function checkSession()
}
}

// Check of we raken of niet
function hitOrMis($usrShot, $ships)
{

// Voor elk schip controleren
for ($i = 0; $i < count($ships); $i++) {
// hitOrMis if hit the shot will be deleted from original arr



// elk shhip heeft als methodefunctie hitOrMis, waar we dan kunnen checken of deze true is
if ($ships[$i]->hitOrMis($usrShot)) {

// Game message wordt geprint in de linkse container onder de boten
$_SESSION['gameMessage'][$i] = "Hit!";

// We vragen hier de volledige array op en slaan ze op in een variabele
$fullArr = $ships[$i]->getLocArrUntouched();

// We willen weten waar precies de usrshot ligt in onze array van locatie
$key = array_search($usrShot, $fullArr);

if ($usrShot == $fullArr[0]) {
$_SESSION['hits'][$i][$key] = "<";
} elseif ($usrShot == $fullArr[count($fullArr) - 1]) {
$_SESSION['hits'][$i][$key] = ">";
} else {
$_SESSION['hits'][$i][$key] = "X";
}
// // Is ons schot de 1e?
// if ($usrShot == $fullArr[0]) {
// $_SESSION['hits'][$i][$key] = "<";
// // is ze de laatste?
// } elseif ($usrShot == $fullArr[count($fullArr) - 1]) {
// $_SESSION['hits'][$i][$key] = ">";
// } else {
// $_SESSION['hits'][$i][$key] = "X";
// }
} else {
// Gemist? Display dit dan in de rechter container
$_SESSION['gameMessage'][$i] = "Missed!";
}
// Is onze variabele array, waar onze geraakte schoten uit verwijderd word, leeg? Dan displayed we 'destroyed'
if (empty($ships[$i]->getLocArr())) {
$_SESSION['gameMessage'][$i] = "Destroyed!";
}
}
}

function randomGenerator($min, $max, $amount)
{
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $amount);
}


function checkOverlap($arr_ships, $board, $length)
{


for ($i = 0; $i < count($arr_ships); $i++) {
for ($j = 0; $j < count($arr_ships); $j++) {
if ($i <> $j) {


while (
in_array($board->getArrStartEnd()[$j][0], $arr_ships[$i]->getLocArrUntouched())
|| in_array($board->getArrStartEnd()[$j][1], $arr_ships[$i]->getLocArrUntouched())
) {
$arr_ships[$i]->calcLocMiddle($length * 10);
}




// if (
// $arr_ships[$i]->getLocStart() >= $board->getArrStartEnd()[$j][0] && $arr_ships[$i]->getLocStart() <= $board->getArrStartEnd()[$j][1] ||
// $arr_ships[$i]->getLocEnd() >= $board->getArrStartEnd()[$j][0] && $arr_ships[$i]->getLocEnd() <= $board->getArrStartEnd()[$j][1]
// ) {

// $arr_ships[$i]->calcLocMiddle($length * 10);
// $j--;
// }
}
}
}


for ($i = 0; $i < count($board->getArrStartEnd()); $i++) {

// if (
// $arr_ships[$i]->getLocStart() >= $board->getArrStartEnd()[$i][0] && $arr_ships[$i]->getLocStart() <= $board->getArrStartEnd()[$i][1] ||
// $arr_ships[$i]->getLocEnd() >= $board->getArrStartEnd()[$i][0] && $arr_ships[$i]->getLocEnd() <= $board->getArrStartEnd()[$i][1]
// ) {

// $arr_ships[$i]->calcLocMiddle($length * 10);
// $i--;
// }

// if ($i + 1 < count($board->getArrStartEnd())) {
// if (
// in_array($board->getArrStartEnd()[$i][0], $arr_ships->currentShips[$i + 1]->getLocArrUntouched())
// || in_array($board->getArrStartEnd()[$i][1], $arr_ships->currentShips[$i + 1]->getLocArrUntouched())
// ) {
// return true;
// }
// }
}
return false;
}

function generateShips($amount, $fieldLength)
{
@@ -203,9 +151,13 @@ function generateShips($amount, $fieldLength)
unset($_SESSION['ammo']);
$_SESSION['ammo'] = 0;

// Nieuwe class asignen
$board = new gameBoard($fieldLength, $amount);

// De schepen aanmaken en in een sessie steken
$_SESSION['curShips'] = $board->createShips();

// De ammo gaan definiëren
$_SESSION['ammo'] = $board->getAmmo();
}

@@ -213,11 +165,14 @@ function generateShips($amount, $fieldLength)

function printCurShotMessage()
{
// Voor elk schip op basis van uw difficulty
for ($i = 0; $i < count($_SESSION['curShips']); $i++) {
echo " <span class='ships-container__wrap ships-wrap'>";
// Naam displayenÒ
echo "<span class='ships-wrap__title'>{$_SESSION['curShips'][$i]->getName()}</span>";
echo "<span class='ships-wrap__item'>";

// Is er geschoten? Zeggen of ze geraakt is of niet
if (isset($_POST['shoot'])) {
echo $_SESSION['gameMessage'][$i];
} else {
@@ -228,19 +183,31 @@ function printCurShotMessage()
}
}


function printTable($rowLength)
{
echo "<table>";

// Rowlength is de variabele $diffTableRows in naval_battle -> Dit is de difficulty level -> beginner = 2, easy = 3, ...
for ($i = 0; $i < $rowLength; $i++) {
// Per rij een table row assignen
echo "<tr>";
// Elke rij heeft 10 kottekes
for ($j = 0; $j < 10; $j++) {
// Optellen van $i + $j, op een string niveau. Dit wordt dan het getal rechtsboven per table data
$tdLoc = intval($i . $j) + 1;

// Een id voor kweet niet welke reden
echo "<td id='" . $tdLoc . "'>";

// Het nummer displayen (rechtsbovenaan)
echo "<span class='td_number'>" . $tdLoc . "</span>";
if ($_SESSION['gameState'] === true) {
// Is er geschoten?
if (isset($_POST['shoot'])) {
// Kijk of onze huide locatie $tdLoc in onze scchoten array zit
if (in_array($tdLoc, $_SESSION['shots'])) {
// Dan onze functie oproepen om te weten of je geraakt hebt of niet
echo printSymbol($tdLoc, $_SESSION['curShips']);
}
}
@@ -249,6 +216,7 @@ function printTable($rowLength)
}
echo "</td>";
}
// Einde rij
echo "</tr>";
}

@@ -257,9 +225,14 @@ function printTable($rowLength)

function printSymbol($tdLoc, $ships)
{

// ons schot controleren voor elk schip
for ($i = 0; $i < count($ships); $i++) {
$fullArr = $ships[$i]->getLocArrUntouched();
// Zit ons shot in de één van onze locatie arrays?
if (in_array($tdLoc, $fullArr)) {

// return de volgende waarden
if ($tdLoc == $fullArr[0]) {
return "<";
} elseif ($tdLoc == $fullArr[count($fullArr) - 1]) {
@@ -267,7 +240,7 @@ function printSymbol($tdLoc, $ships)
} else {
return "X";
}
// als het nummer in geen enkel van de arrays zit
// als het schot in geen enkel van de arrays zit
} elseif ($i === count($ships) - 1) {
return "O";
}
@@ -278,6 +251,7 @@ function printSymbol($tdLoc, $ships)
function printDifficultyInput($difficultyStr)
{

// Just some html shizzle
$html = "<select name='difficulty' class='form__select' id='difficulty' autofocus>";
$shipConjunct = "Ship";
$selected = "selected";
@@ -303,6 +277,7 @@ function printDifficultyInput($difficultyStr)
return $html;
}

// Some more htmlShizzles
function printGameForm($difficultyStr)
{
echo "<legend>";
@@ -338,10 +313,12 @@ function printGameForm($difficultyStr)
echo "</form>";
}

// functie dij kijkt of alle schepen leeg zijn...
function checkIfAllDestroyed($ships)
{
for ($i = 0; $i < count($ships); $i++) {
if (empty($ships[$i]->getLocArr())) {
// Zijn alle schepen leeg?
if ($i == count($_SESSION['curShips']) - 1) {
$_SESSION['gameEndMessage'] = "You won!";
$_SESSION['won'] = 1;

+ 0
- 11
includes/head.inc Ver arquivo

@@ -1,17 +1,6 @@
<?php
session_start();
if ($_GET['logout']) {
// unset($_SESSION['usr_id']);
// unset($_SESSION['usr_name']);
// unset($_SESSION['mess']);
// unset($_SESSION['err_mess']);
// unset($_SESSION['gameMessage']);
// unset($_SESSION['ammo']);
// unset($_SESSION['difficulty']);


// session_destroy(): Trying to destroy uninitialized session
// vandaar session_start();

session_destroy();


+ 27
- 20
includes/ships.inc Ver arquivo

@@ -12,7 +12,6 @@ class Ship
protected $name;
protected $arrLocUntouched;
protected $ammo;
// protected $arrSymbols;


function __construct($fieldLength)
@@ -28,7 +27,6 @@ class Ship
$this->createLocArr();
}

// FIXME: The boat got position 51
protected function calcLocStart()
{
$this->locStart = $this->locMiddle - floor($this->shipLength / 2);
@@ -42,18 +40,20 @@ class Ship

public function calcLocMiddle($fieldLength)
{
// FIXME: whats this?
// -2 verzorgt ervoor dat we niet over onze grid gaan
$this->locMiddle = rand(4, $fieldLength - 2);
}

protected function createLocArr()
{
// 2 arrays opvullen, ene dynamisch, andere onaanpasbaar
for ($i = $this->locStart; $i <= $this->locEnd; $i++) {
$this->arrLoc[] = $i;
$this->arrLocUntouched[] = $i;
}
}

// deze functies spreken voor zich
public function getLocStart()
{
return $this->locStart;
@@ -62,26 +62,18 @@ class Ship
{
return $this->locEnd;
}


public function getLocArr()
{
return $this->arrLoc;
}


public function getLocArrUntouched()
{
return $this->arrLocUntouched;
}


public function hitOrMis($userShot)
{
// if($userShot >= $this->locStart && $userShot <= $this->locEnd){
// return true;
// }

// controleren of onze shot raak is, indien ja return true en verwijder deze uit onze dynamische arr
if (in_array($userShot, $this->arrLoc)) {
$key = array_search($userShot, $this->arrLoc);
unset($this->arrLoc[$key]);
@@ -98,6 +90,7 @@ class Ship
}
}

// Alle schepen die de class Ship extenden
class Sub extends Ship
{

@@ -195,6 +188,7 @@ class AircraftCarrier extends Ship
}
}

// class die onze board aanmaakt
class gameBoard
{
protected $ships;
@@ -209,9 +203,9 @@ class gameBoard

function __construct($length, $amount)
{
// $length is momenteel de variabele in naval_battle.php $diffTableRows (2,3,4,5)
$this->length = $length * 10;
$this->amountShips = intval($amount);
// $this->createShips($this->length);
}

// Functie die nooit dezelfde random nummer genereert
@@ -242,6 +236,7 @@ class gameBoard


for ($i = 0; $i < $this->amountShips; $i++) {
// counter voor onze overlappingscontrole
$counter = 0;

// Dit kiest gewoon een random schip
@@ -249,29 +244,37 @@ class gameBoard
$this->ammo += $this->currentShips[$i]->ammo();

// De 1e keer is deze arr null en moet de controle niet gedaan worden…
// dit is de controle om na te gaan of de schepen overlappen met elkaar, de 1e keer bij het aanmaken van een schip
// hoeft de onderstaan de controle niet uitgevoerd te worden
if ($this->arr_startEnd <> null) {


while ($counter <= count($this->arr_startEnd)) {
$minVal = $this->arr_startEnd[$counter][0];
$maxVal = $this->arr_startEnd[$counter][1];
if ($minVal <> null || $maxVal <> null) {
// overlapt het nieuwe schip met de vorige waarden? zie volgende functie om te zien wat checkoverlap doet
if ($this->checkOverlap($this->currentShips[$i]->getLocArrUntouched(), $minVal, $maxVal)) {
unset($ships);
// unset($this->currentShips[$i]);
// unset($this->arr_startEnd[$i]);

// Opnieuw nieuwe schepen aanmaken
$ships = $this->declareShips($this->length);
// Het nieuw schip overschrijven op de schip waar er overlapping gebeurd
$this->currentShips[$i] = $ships[$this->rdmNumbers[$i]];
// $this->arr_startEnd[$i][0] = $this->currentShips[$i]->getLocStart();
// $this->arr_startEnd[$i][1] = $this->currentShips[$i]->getLocEnd();
// Counter resetten, anders controleert ze het nieuw schip niet met de vorige schepen
// Ik was deze vergeten resetten en zocht dus 2weken achter andere opties, terwijl het gwn maar 1 lijn code was :O
$counter = 0;
} else {
// Overlapt het nieuwe schip niet met de vorige in arr_startEnd -> dan gaan we naar het volgend schip
$counter++;
}
} else {
// Is er geen volgend schip? Counter++ doen zodat we uit de while loop gaan
$counter++;
}
}
}

// De nieuwe begin-eindwaarden opslaan
$this->arr_startEnd[$i][0] = $this->currentShips[$i]->getLocStart();
$this->arr_startEnd[$i][1] = $this->currentShips[$i]->getLocEnd();
}
@@ -281,20 +284,24 @@ class gameBoard

protected function checkOverlap($arr, $minVal, $maxVal)
{
// elk element afgaan van onze huidige schip en kijken of die tussen onze waarden vallen van onze vorige schepen (parameter)
foreach ($arr as $el) {
if (
// de eerste is eigenlijk overbodig, but so be it
$el == $minVal || $el == $maxVal ||
$el >= $minVal && $el <= $maxVal
) {
// is er een overlapping, return true, en dan wordt er nieuwe schepen gegenereerd
return true;
}
}

// werkt ook
// werkt ook en is korter
// if (in_array($minVal, $arr) || in_array($maxVal, $arr)) {
// return true;
// }

// geen overlappingen
return false;
}


+ 4
- 4
index.php Ver arquivo

@@ -30,9 +30,7 @@ include 'includes/head.inc';
<div class="main__content message">

<?php

// FIXME:Wanneer een nieuw user is aangemaakt en dan foutief inloggen -> message session not updated
// Voor de signup.
// Message die displayed of er een fout wachtwoord is, ...
if (isset($_SESSION['mess'])) {
echo $_SESSION['mess'];
}
@@ -45,8 +43,9 @@ include 'includes/head.inc';
exit();
}

// Checken of er errors zijn en indien ja, ze printen
if (isset($_SESSION['err_mess'])) {
// Om te vermijden dat $_SESSION['mess'] nog een boodschap heeft en plakt aan $_SESSION['err_mess']
unset($_SESSION['mess']);
echo $_SESSION['err_mess'];
}
@@ -58,6 +57,7 @@ include 'includes/head.inc';
</div>

<?php

if ($_SESSION['teacherMode']) {

?>

+ 47
- 17
naval_battle.php Ver arquivo

@@ -4,13 +4,19 @@
include 'includes/ships.inc';
include "includes/head.inc";

// TODO: Vraagje voor ruben -> Werken op 2 branches tegelijk? Hoe best practice?



// Array om gwn de difficulty benaming te printen
$difficultyStr = ["Beginner", "Easy", "Intermediate", "Hard"];
$_SESSION['diffLabel'] = $difficultyStr;
// Waarden voor in de database
$_SESSION['statusLabel'] = ["You lost :(", "You won :)"];
// Dit gaat op basis van onze difficulty de tabelrijen aanpassen
$diffTableRows = [2, 3, 4, 5];

// gamestates setten
if (!isset($_SESSION['gameState'])) {
$_SESSION['gameState'] = false;
}
@@ -26,51 +32,74 @@
if (!isset($_SESSION['won'])) {
$_SESSION['won'] = false;
}
if ($_SESSION['tryAgain']) {
$_SESSION['gameState'] = true;
}


if (isset($_POST['startGame'])) {
// Session timeout setten
checkSession();

// Deze wordt indien iets inserted wordt in de db ge-unset. Dan doe ik de check, if isset... Dit zorgt er dan voor dat bij refresh er geen foutieve zaken geinsert wordt
$_SESSION['checkRefresh'] = true;

// Voor de zekerheid onze gamewaarden usnetten
unset($_SESSION['curShips']);
unset($_SESSION['shots']);

// Dit is belangerijk om onze form weer te geven voor onze shots in te voeren
$_SESSION['gameState'] = true;

// Als difficulty is geset
if (isset($_POST['difficulty'])) {
// Session timeout setten
checkSession();

$_SESSION['difficulty'] = intval($_POST['difficulty']);
} else {
// Difficulty niet geset? Dan gebeurd er niets
$_SESSION['gameState'] = false;
}

if (!isset($_SESSION['curShips'])) {
generateShips($_SESSION['difficulty'], $diffTableRows[$_SESSION['difficulty'] - 1]);
}
// Nog een extra check voor de zekerheid, deze keer op de session
if (!isset($_SESSION['difficulty'])) {
$_SESSION['gameState'] = false;
}

// Als current ships niet bestaat wordt de schepen gegenereerd
if (!isset($_SESSION['curShips'])) {
generateShips($_SESSION['difficulty'], $diffTableRows[$_SESSION['difficulty'] - 1]);
}
}

// TODO: Vraagje voor ruben -> Werken op 2 branches tegelijk? Hoe best practice?

// Wordt de shoot btn ingedrukt?
if (isset($_POST['shoot']) && !empty($_POST)) {
// Session timeout setten
checkSession();

// Ammo verminderen indien groter dan 0, in principe is deze if niet nodig, want als ammo 0 is komen we zelfs niet in deze iteratie
if ($_SESSION['ammo'] > 0) {
$_SESSION['ammo']--;
}

// Onze huidige shoten opslaan in een array, zodat we deze later kunnen printen in onze tabel
$_SESSION['shots'][] = $_POST['usrShot'];

// Check of we de duikoot raken
hitOrMis($_POST['usrShot'], $_SESSION['curShips']);

// controle of we alle schepen vernietigd hebben
checkIfAllDestroyed($_SESSION['curShips']);
}


// Deze session checkRefresh is om te vermijden dat er resubmission gebeurd on page refresh. Deze wordt unset als er score geinsert wordt in de db
if (isset($_SESSION['checkRefresh'])) {
if ($_SESSION['ammo'] === 0) {
$_SESSION['lost'] = true;
}
}

// FIXME: CHeck why when ammo ran out, on refresh it keeps inserting scores
// Is lost true en niet alle schepen destroyed? Dan is uw ammo leeg
if ($_SESSION['lost'] && !checkIfAllDestroyed($_SESSION['curShips'])) {
unset($_SESSION['gameEndMessage']);
unset($_SESSION['lost']);
@@ -85,7 +114,7 @@
$_SESSION['gameEndMessage'] = "You ran out of ammo";
}

// Deze session checkRefresh is om te vermijden dat er resubmission gebeurd on page refresh. Deze wordt unset als er score geinsert wordt in de db
if (isset($_SESSION['checkRefresh'])) {
if ($_SESSION['gameDone'] && $_SESSION['ammo'] > 0) {
writeScore($_SESSION['usr_id'], $_SESSION['difficulty'], $_SESSION['won'], $_SESSION['ammo']);
@@ -93,12 +122,14 @@
}
}

// Is het spel gedaan en druk je op try again?
if (isset($_POST['tryAgain'])) {
checkSession();
if (isset($_POST['difficulty'])) {
$_SESSION['difficulty'] = $_POST['difficulty'];
}
unset($_SESSION['gameMessage']);
// opnieuw schepen genereren op basis van uw difficulty
generateShips($_SESSION['difficulty'], $diffTableRows[$_SESSION['difficulty'] - 1]);
$_SESSION['tryAgain'] = false;
$_SESSION['gameDone'] = false;
@@ -110,9 +141,9 @@

?>

<!-- Is de gameState true dan krijgen we onze difficulty selection te zien -->
<?php if ($_SESSION['gameState']) { ?>

<!-- TODO: Add the folowing together with the printCurShotMessage() fn -->
<div class="main__content info">
<div class="info-container">
<span class="info-container__wrap">
@@ -132,15 +163,14 @@
<fieldset class="main__content content">

<?php
// Functie die de input shot form genereert
printGameForm($difficultyStr);
?>
</fieldset>


<!-- TODO:Dit ook in php omzetten en variabele gamestate meegeven -->

<?php if ($_SESSION['gameState']) { ?>
<!-- Dit is de linkse container die onze schepen weergeeft -->
<section class="main__content ships-container">
<h2 class="ships-container__title">

@@ -154,14 +184,14 @@
</h2>
<?php

// Deze functie print onze huidige schepen en wordt geupdate of we ze raken of niet
printCurShotMessage();

?>
</section>
<?php } ?>
<div class="main__content content">
<!-- TODO: variabele moeilijkheidsgraad meegeven om de rijen van de tabel aan te passen -->
<!-- Deze functie print de tabel op basis van difficulty level en update ze -->
<?php printTable($diffTableRows[$_SESSION['difficulty'] - 1]); ?>
</div>


+ 1
- 0
scores.php Ver arquivo

@@ -2,6 +2,7 @@
require_once 'includes/dbase.inc';
include 'includes/functions.inc';
include "includes/head.inc";

// anders wordt de insert herdaan
$_SESSION['gameDone'] = false;
?>

+ 0
- 2
signup.php Ver arquivo

@@ -32,8 +32,6 @@ include 'includes/head.inc';
if (isset($_POST['btn-sign-up'])) {


//FIXME: CONTROLERN waar hier de check wordt gedaan -> liefst niet in functie, dus true of false hieronder checken

registerUser($_POST['usr-name'], $_POST['password'], $_POST['confirm-password']);

if (isset($_SESSION['mess'])) {

Carregando…
Cancelar
Salvar