Getting REALLY frustrated making this hangman-type game

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
KyZu
Forum Newbie
Posts: 17
Joined: Sun Apr 24, 2011 9:13 pm

Getting REALLY frustrated making this hangman-type game

Post by KyZu »

So I started learning PHP a few days ago and I sort of dived right in trying to make things, this was my first program (a simple BMI calculator)
http://pastebin.com/SHfA4pt5

Okay but now I wanted to make hangman, and I'm just...so lost, like, I don't even know how to go about it. Here is the code I have so far (some of it commented out because it was just "ideas" I had). Here is what I have so far:
http://pastebin.com/FyQPmR8U

So can somebody give me some direction? Is there anything I wrote that is REALLY dumb and unnecessary? Basically I'm trying to find a way to:
- log the guesses (how can I do this if I don't have an array, or nothing to put the values in...do I need to duplicate anything?)
- check to see if a guess has already been made
- replace the underscores with the letter corresponding to that position.

and hell I don't even know what else, just trying to get it to work :(
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Getting REALLY frustrated making this hangman-type game

Post by Jonah Bron »

You should store the user's guesses in the session ($_SESSION variable) as an array, like this:

Code: Select all

if (isset($_GET['guess']) && strlen($_GET['guess']) == 1) {
    $guess = strtolower($_GET['guess']);
    if (in_array($guess, range('a', 'b')) && !in_array($guess, $_SESSION['guesses'])) {
        $_SESSION['guesses'][] = $guess;
    }
}
And instead of displaying the word by repeating " _ ", do it more like this:

Code: Select all

$display = '';
$word = explode('', $word);
$won = true;
foreach ($word as $char) {
    if (in_array($char, $_SESSION['guesses'])) {
        $display .= " $char ";
    } else {
        $display .= " _ ";
        $won = false;
    }
}

$wrongGuesses = 0;
foreach ($_SESSION['guesses'] as $guess) {
    if (!in_array($guess, $word)) {
        $wrongGuesses++;
    }
}
The first loop correctly displays the word, and checks if the player has won yet ($won is true if they won). The second loop determines how many incorrect guesses the player has made. You can use that number to properly render the gallows, and to know if the player has lost yet.

I recommend you display the word in a monospace font, so that the formatting is correct.
Post Reply