I’m trying to make a fairly simple Hangman app, and I’ve somehow hung myself up on it. I was hoping someone would be willing to help me get it sorted. I can’t figure out how to make it properly interact with the page, and my execution flow is getting all gummed up by my poor brain planning. I’m using this site for guidance but the implementations are different enough that it’s doing more harm than good:
I was trying to do it TDD style. That failed, obviously. Help? Thoughts? Thanks!
index.php
[php]<?php
//include the required files
require_once(‘HangmanGame.php’);
require_once(‘WordList.php’);
//this will keep the game data as they refresh the page
session_start();
//load a game if one hasn’t started yet
/if (!isset($_SESSION[‘game’][‘hangman’])) {
$_SESSION[‘game’][‘hangman’] = new HangmanGame();
}/
?>
HangmanGame.php
[php]<?php
namespace Hangman;
class HangmanGame
{
public $word;
public $maskedWord = array();
private $guesses = 6;
private $letters = array();
private $gameOver = false;
public function __construct($word = null) {
$this->newGame($word);
}
public function newGame($word = null) {
// can be passed a word to start, or get a random one from the word list
if (is_null($word)) {
$wordList = new WordList;
$this->word = $wordList->getRandomWord();
} else {
$this->word = $word;
}
// set the masked word
$this->maskedWord = str_split(str_repeat("_",strlen($this->word)));
}
public function nextRound() {
if (($this->guesses == 0) || ($this->word == implode($this->maskedWord))) {
$this->gameOver();
} else {
}
}
public function guess($letter) {
$hit = 0;
for ($i=0; $i<strlen($this->word); $i++) {
if ($this->word{$i} == $letter) {
$hit++;
$this->maskedWord[$i] = $letter;
}
}
if ($hit == 0) {
if ($this->guesses == 0) {
$this->gameOver = true;
} else {
array_push($this->letters, $letter);
$this->guesses -= 1;
}
}
echo $this->word;
echo "\n" . implode($this->maskedWord) . "\n";
}
public function hasWon() {
return $this->word == implode($this->maskedWord);
}
}[/php]
WordList.php
[php]<?php
namespace Hangman;
class WordList
{
const DEFAULT_WORDLIST = array(“word”, “list”, “missing”);
// const DEFAULT_PATH = ‘data/words.txt’;
private $path = ‘data/words.txt’;
private $wordList = null;
public function __construct($wordListPath = null) {
$this->wordList = (is_null($wordListPath)) ? file($this->path) : file($wordListPath);
}
public function getRandomWord() {
$randomKey = array_rand($this->wordList, 1);
return $this->wordList[$randomKey];
}
}[/php]