Dieser Beitrag ist Teil meiner Sourcecode a Day Aktion.
Vor langer Zeit habe ich mir mal eine kleine Klasse zur Lösung von Galgenmännchen-Spielen geschrieben. Man benötigt zur Verwendung der Klasse eine Datei wordlist.txt, in der möglichst viele deutsche Wörter gespeichert sind!
<?php
/**
* Solve a Hangman game
*
* @author Alexander Thiemann
*/
class Hangman {
/**
* asked letters
*
* @var array
*/
public $asked_letters = array();
/**
* possible words
*
* @var array
*/
public $possible_worlds = array();
/**
* construct hangman ;)
*
* @param string $state
*/
public function __construct($state) {
$lines = file("wordlist.txt");
foreach($lines As $line) {
$n = strtolower(trim($line));
if ($this->WordCompare($state, $n)) {
$this->possible_worlds[] = $n;
}
}
}
/**
* fetch suggestion
*
* @return string
*/
public function getSuggestion() {
$w = "enisratdhulcgmobwfkzpvjyxq"; // change this if you dont use german words!!
for($i=0;$iasked_letters) && $this->LetterInWords($w{$i})) {
$this->asked_letters[] = $w{$i};
return $w{$i};
}
}
}
/**
* check if letter is usefull
*
* @param string $letter
* @return bool
*/
public function LetterInWords($letter) {
foreach ($this->possible_worlds As $w_out) {
if (strpos($w_out, $letter) !== false) {
return true;
}
}
return false;
}
/**
* compare two words, * is placeholder
*
* @param string $word
* @param string $compare
* @return bool
*/
public function WordCompare($word, $compare) {
$ln = strlen($word);
if ($ln != strlen($compare)) {
return false;
}
for ($i=0;$i
Ein Beispiel zur Verwendung:
if (!isset($_GET["state"])) {
$state = "***";
}
else {
$state = $_GET["state"];
}
$Man = new Hangman($state);
if (isset($_GET["letters"])) {
$Man->asked_letters = explode("|", $_GET["letters"]);
}
echo "Es sind noch ".count($Man->possible_worlds)." Kombinationen möglich.";
if (count($Man->possible_worlds) < 50) {
echo "
".implode(", ", $Man->possible_worlds);
}
echo "
";
echo $Man->getSuggestion();
echo "
";
echo "";