Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / PHP
Technical Blog

Hangman (game) script in PHP

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
26 Mar 2013CPOL1 min read 51K   4   1
Hangman (game) script in PHP.

To start off, here is a little information about the Hangman game. From Wikipedia:

The word to guess is represented by a row of dashes, giving the number of letters and category of the word. If the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions. If the suggested letter does not occur in the word, the other player draws one element of the hanged man stick figure as a tally mark. The game is over when:

    The guessing player completes the word, or guesses the whole word correctly
    The other player completes the diagram

Here, is the code:

config.php

It has two variables, $MAX_ATTEMPTS to store the number of maximum attempts the player has and $WORDLISTFILE to store the location of the text file that contains all the words which will be used in the game.

PHP
<?php
    $MAX_ATTEMPTS = 7;
    $WORDLISTFILE = 'wordlist.txt';
?>

functions.php

This file has all the important functions that are used in the script. Functions present in this file are:

  • fetchWordArray(): It returns a random word that is going to be used in the game from the specified text file.
  • hideCharacters(): It hides certain characters of the word that has been generated by fetchWordArray().
  • checkAndReplace(): This function checks if the character entered by the user is one of the missing characters of the hidden word. If the character is found in the word, it is placed into its exact location.
  • checkGameOver(): This function checks if the game is over. Games ends when user exceeds maximum allowed attempts or if the user guesses the word right.

PHP
<?php
/*
    Function Name: fetchWordArray()
    Parameters: None
    Return values: Returns an array of characters.
*/
    function fetchWordArray($wordFile)
    {
        $file = fopen($wordFile,'r');
           if ($file)
        {
            $random_line = null;
            $line = null;
            $count = 0;
            while (($line = fgets($file)) !== false) 
            {
                $count++;
                if(rand() % $count == 0) 
                {
                      $random_line = trim($line);
                }
        }
        if (!feof($file)) 
        {
            fclose($file);
            return null;
        }else 
        {
            fclose($file);
        }
    }
        $answer = str_split($random_line);
        return $answer;
    }
/*
    Function Name: hideCharacters()
    Parameters: Word whose characters are to be hidden.
    Return values: Returns a string of characters.
*/
    function hideCharacters($answer)
    {
        $noOfHiddenChars = floor((sizeof($answer)/2) + 1);
        $count = 0;
        $hidden = $answer;
        while ($count < $noOfHiddenChars )
        {
            $rand_element = rand(0,sizeof($answer)-2);
            if( $hidden[$rand_element] != '_' )
            {
                $hidden = str_replace($hidden[$rand_element],'_',$hidden,$replace_count);
                $count = $count + $replace_count;
            }
        }
        return $hidden;
    }
/*
    Function Name: checkAndReplace()
    Parameters: UserInput, Hidden string and the answer.
    Return values: Returns a character array.
*/
    function checkAndReplace($userInput, $hidden, $answer)
    {
        $i = 0;
        $wrongGuess = true;
        while($i < count($answer))
        {
            if ($answer[$i] == $userInput)
            {
                $hidden[$i] = $userInput;
                $wrongGuess = false;
            }
            $i = $i + 1;
        }
        if (!$wrongGuess) $_SESSION['attempts'] = $_SESSION['attempts'] - 1;
        return $hidden;
    }
    
    
/*
    Function Name: checkGameOver()
    Parameters: Maximum attempts, no. of attempts made by user, Hidden string and the answer.
    Return values: Returns a character array.
*/
    function checkGameOver($MAX_ATTEMPTS,$userAttempts, $answer, $hidden)
    {
        if ($userAttempts >= $MAX_ATTEMPTS)
            {
                echo "Game Over. The correct word was ";
                foreach ($answer as $letter) echo $letter;
                echo '<br><form action = "" method = "post"><input type = "submit" name' + 
                  ' = "newWord" value = "Try another Word"/></form><br>';
                die();
            }
            if ($hidden == $answer)
            {
                echo "Game Over. The correct word is indeed ";
                foreach ($answer as $letter) echo $letter;
                echo '<br><form action = "" method = "post"><input ' + 
                  'type = "submit" name = "newWord" value = "Try another Word"/></form><br>';
                die();
            }
    }
?>

Finally, the index page:

index.php

It is responsible for initiating a session, validation of user input and calling the functions appropriately.

XML
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hangman</title>
</head>

<body>
<?php
    include 'config.php';
    include 'functions.php';
    if (isset($_POST['newWord'])) unset($_SESSION['answer']);
    if (!isset($_SESSION['answer']))
    {
        $_SESSION['attempts'] = 0;
        $answer = fetchWordArray($WORDLISTFILE);
        $_SESSION['answer'] = $answer;
        $_SESSION['hidden'] = hideCharacters($answer);
        echo 'Attempts remaining: '.($MAX_ATTEMPTS - $_SESSION['attempts']).'<br>';
    }else
    {
        if (isset ($_POST['userInput']))
        {
            $userInput = $_POST['userInput'];
            $_SESSION['hidden'] = checkAndReplace(strtolower($userInput), $_SESSION['hidden'], $_SESSION['answer']);
            checkGameOver($MAX_ATTEMPTS,$_SESSION['attempts'], $_SESSION['answer'],$_SESSION['hidden']);
        }
        $_SESSION['attempts'] = $_SESSION['attempts'] + 1;
        echo 'Attempts remaining: '.($MAX_ATTEMPTS - $_SESSION['attempts'])."<br>";
    }
    $hidden = $_SESSION['hidden'];
    foreach ($hidden as $char) echo $char."  ";
?>
<script type="application/javascript">
    function validateInput()
    {
    var x=document.forms["inputForm"]["userInput"].value;
    if (x=="" || x==" ")
      {
          alert("Please enter a character.");
          return false;
      }
    if (!isNaN(x))
    {
        alert("Please enter a character.");
        return false;
    }
}
</script>
<form name = "inputForm" action = "" method = "post">
Your Guess: <input name = "userInput" type = "text" size="1" maxlength="1"  />
<input type = "submit"  value = "Check" onclick="return validateInput()"/>
<input type = "submit" name = "newWord" value = "Try another Word"/>
</form>
</body>
</html>

Check the demo here: http://dev.mycoding.net/Hangman/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSlight change to code to get it to work for me Pin
renaultF13-Apr-13 10:30
renaultF13-Apr-13 10:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.