Files
intecsync/cgi-bin/uebung08/hangman_lib.php
2019-06-30 20:45:26 +02:00

95 lines
2.3 KiB
PHP

<?php
//Aufgabe 1
//Bringt ein Wort in das richtige Format
function transformWord($word) {
$word = str_replace("ä", "AE", $word);
$word = str_replace("ö", "OE", $word);
$word = str_replace("ü", "UE", $word);
$word = str_replace("ß", "SS", $word);
$word = strtoupper($word);
return $word;
}
//Maskiert ein Wort mit _
function maskWord($word) {
$arr = array();
for ($i = 0; $i < strlen($word); $i++) {
$arr[] = "_";
}
return $arr;
}
function getAllWords() {
$str = file_get_contents("words-array.php");
$str = str_replace('"', '', $str);
$str = str_replace('[', '', $str);
$str = str_replace(']', '', $str);
$str = str_replace(';', '', $str);
return explode(", ", $str);
}
//Aufgabe 2
function getRandomWord() {
$arr = getAllWords();
return array_rand($arr)[0];
}
// startet die Session und initialisiert das tasks-Array
function initGame()
{
//session_name(get_current_user() . "hangman");
//session_start();
$randword = getRandomWord();
$_SESSION['toGuess'] = $randword;
$_SESSION['mask'] = maskWord($randword);
$_SESSION['guessedLetters'] = [];
$_SESSION['errorCount'] = 0;
$_SESSION['state'] = 0;
}
//Aufgabe 3
function guessLetter($letter) {
//convert to uppercase letter
$letter = strtoupper($letter);
//stop here if the letter is in guessedLetters
if (in_array($letter, $_SESSION['guessedLetters'])) {
return;
}
//Append the guessed letter
array_push($_SESSION['guessedLetters'], $letter);
//Add the letter to the mask
$guessword = str_split($_SESSION['toGuess']);
$newMask = $_SESSION['mask'];
$wordcontainsletter = false;
for ($i = 0; $i < count($guessword); $i++) {
if ($guessword[$i] == $letter) {
$newMask[$i] = $letter;
$wordcontainsletter = true;
}
}
$_SESSION['mask'] = $newMask;
//if the guessword doesn't contain the letter increment errorCount
if (!$wordcontainsletter) {
$_SESSION['errorCount'] = $_SESSION['errorCount'] + 1;
}
//refresh the state
if ($_SESSION['errorCount'] > 8) {
$_SESSION['state'] = 2;
} else if (!in_array("_", $_SESSION['mask'])) {
$_SESSION['state'] = 1;
}
}
?>