View Full Version : Hang-man #2
This was posted ages ago but was lost when the forum went down, so I've decided to post it again.
This isn't the version which Mentor made changes to, as I have lost my copy of it.
<?php
/*
-------------------------------
To customize the file name of the text
document and the character separating
the words, modify the code just bellow
this sentence.
------------------------------- */
$word_list_location = 'word_list.txt'; // Location of file containing the words
$word_separator = '|'; // Character used to separate the words
$file_name = 'hang_man.php'; // The name of this file
/* Don't edit bellow this line unless you know what you're doing */
session_start();
$users_guess = $_GET['guess'];
// If game hasn't started
if(!isset($_SESSION['hangman_word']))
{
unset($users_guess);
// Choose a random word
$handle = fopen($word_list_location, 'r');
$word_list = fread($handle, filesize($word_list_location));
$word_list = explode($word_separator, $word_list);
fclose($handle);
$word_list_count = (count($word_list) - 1);
$choosen_word = $word_list[rand(0, $word_list_count)];
// Put word into session
$_SESSION['hangman_word'] = $choosen_word;
}
// Check guess length
if(isset($users_guess) && strlen($users_guess) != 1)
{
session_destroy();
die("<script language=\"JavaScript\">
alert(\"Only enter one letter!\");
document.location.href=\"$file_name\";
</script>");
}
// Check if max loses has been met
if($_SESSION['hangman_loses'] > 9)
{
session_destroy();
die("<script language=\"JavaScript\">
alert(\"All lifes used up!\");
document.location.href=\"$file_name\";
</script>");
}
// Switches guessed letters to upper case
$correct_word = $_SESSION['hangman_word'];
$guess_check = str_replace($users_guess, strtoupper($users_guess), $correct_word);
// Checks if user guessed an incorrect letter
if (isset($users_guess) && $guess_check == $correct_word)
{
$_SESSION['hangman_loses']++;
}
else
{
$_SESSION['hangman_word'] = $guess_check;
// Check for win
if($_SESSION['hangman_word'] == strtoupper($_SESSION['hangman_word']))
{
session_destroy();
die("<script language=\"JavaScript\">
alert(\"You have won!\");
document.location.href=\"$file_name\";
</script>");
}
}
?>
<html>
<head>
<title>Hang-man</title>
</head>
<body>
<form>
<input type="text" name="guess" size="1" maxlength="1" value="" />
<input type="submit" value="Go" />
<br />
Word:
<?php
// Print word, with lower caps (non-guessed) hidden
print ereg_replace('[a-z]','_ ', $_SESSION['hangman_word']);
?>
<br />
Lifes:
<?php
// Put loses as zero if unset
if(!isset($_SESSION['hangman_loses'])) $_SESSION['hangman_loses'] = 0;
print $_SESSION['hangman_loses'].'/10';
?>
</form>
</body>
</html>
You can play it at (It is another version, but is pretty similar):
http://www.thybag.co.uk/test/hangyman.php
D3stroyer
23-02-2006, 05:55 PM
Yeh i was getting bored and wondered where this went thanks for re-posting.
Once again Nets has done it.
-Daza
:Blob
23-02-2006, 06:04 PM
You've won!
The word was rich!
How hard!
timROGERS
23-02-2006, 06:27 PM
I won on my last chance :P The word was morning :P
Luckyrare
23-02-2006, 08:45 PM
Ah you helped me <3
I needed something like strlen, very helpful I will read it more and see if there is anything else I may help me with my system.
Thanks Nets ;)
Mentor
23-02-2006, 09:05 PM
Nets could u IM me, as css is driveing me mad and your the only one i know who can actaly use the stuff, without exsploaions and death "/
Plus, The updated script is here.
<?php
/*
-------------------------------
To customize the file name of the text
document and the character separating
the words, modify the code just bellow
this sentence.
------------------------------- */
$word_list_location = 'word_list.txt'; // Location of file containing the words
$word_separator = '|'; // Character used to separate the words
$file_name = 'hangyman.php'; // Name of this file
$Game_lifes = '10'; // How many lifes a use has
$use_images = true ; //if you dont want to use images set to false.
//if you want to use images
$image_locations =""; //images must have names 0 to the maximum number of lives allowed, the top number is the hanging.
$image_type = "gif" ; //file exstention
/* Don't edit bellow this line unless you know what you're doing */
//As suggested by luckyrare, do we want to reset?
if($_GET['reset'] == "yes"){
session_start();
session_destroy();
header("Location: ".$file_name);
}
session_start();
$users_guess = $_GET['guess'];
// If game hasn't started
if(!isset($_SESSION['hangman_word']))
{
unset($users_guess);
// Choose a random word
$handle = fopen($word_list_location, 'r');
$word_list = fread($handle, filesize($word_list_location));
$word_list = explode($word_separator, $word_list);
fclose($handle);
$word_list_count = (count($word_list) - 1);
$choosen_word = $word_list[rand(0, $word_list_count)];
// Put word into session
$_SESSION['hangman_word'] = $choosen_word;
//Create alphabet
$_SESSION['letters'] = "abcdefghijklmnopqrstuvwxyz";
}
// Check guess length
if(isset($users_guess) && strlen($users_guess) != 1)
{
die('You must enter only one letter. <a href="'.$file_name.'">Return</a>');
}
// Check there letters
if (ereg('[^A-Za-z]', $users_guess))
{
die('You may only use letters. <a href="'.$file_name.'">Return</a>');
}
// Make sure havent already guessed letter
if(preg_match(strtoupper("/".$users_guess."/"), $_SESSION['letters']) && isset($users_guess))
{
$Letter_Twice="1" ;
}
// Switches guessed letters to upper case
$correct_word = $_SESSION['hangman_word'];
$guess_check = str_replace($users_guess, strtoupper($users_guess), $correct_word);
//Updates Alphabet with letter guessed
$_SESSION['letters'] = str_replace($users_guess, strtoupper($users_guess), $_SESSION['letters']);
// Checks if user guessed an incorrect letter
if (isset($users_guess) && $guess_check == $correct_word AND $Letter_Twice !=="1")
{
$_SESSION['hangman_loses']++;
// Check if max loses has been met
if($_SESSION['hangman_loses'] > $Game_lifes-1)
{
session_destroy();
echo ' All lifes used up :(<br> The word was <b>'.strtolower($_SESSION['hangman_word']).'</b><br>';
if($use_images == true){
echo "<img src='".$image_locations."".$Game_lifes.".".$image_type."'>";
}
echo '<a href="'.$file_name.'">Start New Game?</a> ' ;
die();
}
}
else
{
$_SESSION['hangman_word'] = $guess_check;
// Check for win
if($_SESSION['hangman_word'] == strtoupper($_SESSION['hangman_word']))
{
session_destroy();
die('You\'ve won!<br> The word was <b>'.strtolower($_SESSION['hangman_word']).'!</b><br> <a href="'.$file_name.'">Start New Game?</a>');
}
}
?>
<html>
<head>
<title>Hang-man</title>
<style>
a:visited {color:0000ff;}
a:link {color:0000ff;}
</style>
</head>
<body>
<?php
//Choose Whether to Link or Not link Letter
function buttons($let){
if(preg_match(strtoupper("/".$let."/"), $_SESSION['letters'])){
$let = $let." ";
} else {
$let = "<b><a href='".$file_name."?guess=".$let."'>".$let."</a> ";
}
return $let;
}
//Letters
echo buttons("a");
echo buttons("b");
echo buttons("c");
echo buttons("d");
echo buttons("e");
echo buttons("f");
echo buttons("g");
echo buttons("h");
echo buttons("i");
echo buttons("j");
echo buttons("k");
echo buttons("l");
echo buttons("m");
echo buttons("n");
echo buttons("o");
echo buttons("p");
echo buttons("q");
echo buttons("r");
echo buttons("s");
echo buttons("t");
echo buttons("u");
echo buttons("v");
echo buttons("w");
echo buttons("x");
echo buttons("y");
echo buttons("z");
?>
<br />
<?php
//do we want images?
if($use_images == true){
if(isset($_SESSION['hangman_loses'])){
echo "<img src='".$image_locations."".$_SESSION['hangman_loses'].".".$image_type."'>";
}else{
echo "<img src='".$image_locations."0.".$image_type."'>";
}
}
?>
<br />
Word:
<?php
// Print word, with lower caps (non-guessed) hidden
print ereg_replace('[a-z]','_ ', $_SESSION['hangman_word']);
if($Letter_Twice =="1"){echo"<br><br>Sorry. You Cannot Enter the Same Letter twice.";}
?>
<br />
Lifes:
<?php
// Put loses as zero if unset
if(!isset($_SESSION['hangman_loses'])) $_SESSION['hangman_loses'] = 0;
print $_SESSION['hangman_loses'].'/'.$Game_lifes;
?>
<div style="position:absolute; width: 80px; height: 30px; right: 0px; top: 0px;">
<div align="center"><strong><a href="<?php echo $file_name; ?>?reset=yes"> Reset</a> </strong></div>
</div>
</body>
</html>
And the bigger word list, off wiki pedia with 2 letter words removed.
about|above|across|act|active|activity|add|afraid| after|again|age|ago|agree|air|all|alone|along|alre ady|always|amount|and|angry|another|answer|anyone| anything|anytime|appear|apple|area|arm|army|around |arrive|art|ask|attack|aunt|autumn|away|baby|base| back|bad|bag|ball|bank|basket|bath|bean|bear|beaut iful|beer|bed|bedroom|behave|before|begin|behind|b ell|below|besides|best|better|between|big|bird|bir th|birthday|bit|bite|black|bleed|block|blood|blow| blue|board|boat|body|boil|bone|book|border|born|bo rrow|both|bottle|bottom|bowl|box|boy|branch|brave| bread|break|breakfast|breathe|bridge|bright|bring| brother|brown|brush|build|burn|business|bus|busy|b ut|buy|cake|call|can|candle|cap|car|card|care|care ful|careless|carry|case|cat|catch|central|century| certain|chair|chance|change|chase|cheap|cheese|chi cken|child|children|chocolate|choice|choose|circle |city|class|clever|clean|clear|climb|clock|cloth|c lothes|cloud|cloudy|close|coffee|coat|coin|cold|co llect|colour|comb|comfortable|common|compare|come| complete|computer|condition|continue|control|cook| cool|copper|corn|corner|correct|cost|contain|count |country|course|cover|crash|cross|cry|cup|cupboard |cut|dance|dangerous|dark|daughter|day|dead|decide |decrease|deep|deer|depend|desk|destroy|develop|di e|different|difficult|dinner|direction|dirty|disco ver|dish|direction|dog|door|double|down|draw|dream |dress|drink|drive|drop|dry|duck|dust|duty|each|ea r|early|earn|earth|east|easy|eat|education|effect| egg|eight|either|electric|elephant|else|empty|end| enemy|enjoy|enough|enter|equal|entrance|escape|eve n|evening|event|ever|every|everyone|exact|everybod y|examination|example|except|excited|exercise|expe ct|expensive|explain|extremely|eye|face|fact|fail| fall|false|family|famous|far|farm|father|fast|fat| fault|fear|feed|feel|female|fever|few|fight|fill|f ilm|find|fine|finger|finish|fire|first|fit|five|fi x|flag|flat|float|floor|flour|flower|fly|fold|food |fool|foot|football|for|force|foreign|forest|forge t|forgive|fork|form|fox|four|free|freedom|freeze|f resh|friend|friendly|from|front|fruit|full|fun|fun ny|furniture|further|future|game|garden|gate|gener al|gentleman|get|gift|give|glad|glass|goat|god|gol d|good|goodbye|grandfather|grandmother|grass|grave |great|green|grey|ground|group|grow|gun|hair|half| hall|hammer|hand|happen|happy|hard|hat|hate|have|h e|head|healthy|hear|heavy|hello|help|heart|heaven| height|help|hen|her|here|hers|hide|high|hill|him|h is|hit|hobby|hold|hole|holiday|home|hope|horse|hos pital|hot|hotel|house|how|hundred|hungry|hour|hurr y|husband|hurt|ice|idea|important|increase|inside| into|introduce|invent|iron|invite|island|jelly|job |join|juice|jump|just|keep|key|kill|kind|king|kitc hen|knee|knife|knock|know|ladder|lady|lamp|land|la rge|last|late|lately|laugh|lazy|lead|leaf|learn|le ave|leg|left|lend|length|less|lesson|let|letter|li brary|lie|life|light|like|lion|lip|list|listen|lit tle|live|lock|lonely|long|look|lose|lot|love|low|l ower|luck|machine|main|make|male|man|many|map|mark |market|marry|matter|may|meal|mean|measure|meat|me dicine|meet|member|mention|method|middle|milk|mill ion|mind|minute|miss|mistake|mix|model|modern|mome nt|money|monkey|month|moon|more|morning|most|mothe r|mountain|mouth|move|much|music|must|name|narrow| nation|nature|near|nearly|neck|need|needle|neighbo ur|neither|net|never|new|news|newspaper|next|nice| night|nine|noble|noise|none|nor|north|nose|not|not hing|notice|now|number|obey|object|ocean|of|off|of fer|office|often|oil|old|one|only|open|opposite|or ange|order|other|our|out|outside|over|own|page|pai n|paint|pair|pan|paper|parent|park|part|partner|pa rty|pass|past|path|pay|peace|pen|pencil|people|pep per|per|perfect|period|person|petrol|photograph|pi ano|pick|picture|piece|pig|pin|pink|place|plane|pl ant|plastic|plate|play|please|pleased|plenty|pocke t|point|poison|police|polite|pool|poor|popular|pos ition|possible|potato|pour|power|present|press|pre tty|prevent|price|prince|prison|private|prize|prob ably|problem|produce|promise|proper|protect|provid e|public|pull|punish|pupil|push|put|queen|question |quick|quiet|quite|radio|rain|rainy|raise|reach|re ad|ready|real|really|receive|record|red|remember|r emind|remove|rent|repair|repeat|reply|report|rest| restaurant|result|return|rice|rich|ride|right|ring |rise|road|rob|rock|room|round|rubber|rude|rule|ru ler|run|rush|sad|safe|sail|salt|same|sand|save|say |school|science|scissors|search|seat|second|see|se em|sellsend|sentence|serve|seven|several|***|shade |shadow|shake|shape|share|sharp|she|sheep|sheet|sh elf|shine|ship|shirt|shoe|shoot|shop|short|should| shoulder|shout|show|sick|side|signal|silence|silly |silver|similar|simple|single|since|sing|sink|sist er|sit|six|size|skill|skin|skirt|sky|sleep|slip|sl ow|smoke|small|smell|smile|smoke|snow|soap|sock|so ft|some|someone|something|sometimes|son|soon|sorry |sound|soup|south|space|speak|special|speed|spell| spend|spoon|sport|spread|spring|square|stamp|stand |star|start|station|stay|steal|steam|step|still|st omach|stone|stop|store|storm|story|strange|street| strong|structure|student|study|stupid|subject|subs tance|successful|such|sudden|sugar|suitable|summer |sun|sunny|support|sure|surprise|sweet|swim|sword| table|take|talk|tall|taste|taxi|tea|teach|team|tea r|telephone|television|tell|ten|tennis|terrible|te st|than|that|the|their|then|there|therefore|these| thick|thin|thing|think|third|this|though|threat|th ree|tidy|tie|title|today|toe|together|tomorrow|ton ight|too|tool|tooth|top|total|touch|town|train|tra m|travel|tree|trouble|true|trust|twice|try|turn|ty pe|uncle|under|understand|unit|until|up|use|useful |usual|usually|vegetable|very|village|voice|visit| wait|wake|walk|want|warm|wash|waste|watch|water|wa y|weak|wear|weather|wedding|week|weight|welcome|we ll|west|wet|what|wheel|when|where|which|while|whit e|who|why|wide|wife|wild|will|win|wind|window|wine |winter|wire|wise|wish|with|without|woman|wonder|w ord|work|world|worry|worry|worst|write|wrong|year| yes|yesterday|yet|you|young|your|zero|zebra
timROGERS
24-02-2006, 07:17 PM
Tomorrow I might do a version of this with AJAX :P
Tomorrow I might do a version of this with AJAX :P
Wouldn't it be easier and more effective just to rewrite it in 100% JavaScript? As not only would it not "reload" the page, but no loading after you've initially loaded it would be necessary.
Mentor
24-02-2006, 09:40 PM
Wouldn't it be easier and more effective just to rewrite it in 100% JavaScript? As not only would it not "reload" the page, but no loading after you've initially loaded it would be necessary.
Writing compleaty in JS would do my head in lol. But you have a point, shoudl add some php value, i may add a score board etc :D
(btw about the css bit, i figured it out, the doctype was forcing it in to a strct mode in firefox, while the test version i was working wasnt, so my less than standard css useage wasnt working to well :D )
Want to hide these adverts? Register an account for free!
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.