#! /usr/bin/perl ###hangman### use strict; my @words = ( "hi", "cat", "home", "country", "computer", "irc", "hat", "wow", "Berlin", "fly", "airplane", "cow", "maps", "make", "run", "sigh", "golf", "running", "hat", "television", "games", "hangman", "pearl", "cat", "dog", "snake", "black", "white", "cabin", "trees", "birds", "animals"); my @hangman = (">", "=", "(", ")", "-", "|", "-", "<"); my $hangman; my @word; my $word; my %found; my $input; #make the input variable global, so all functions can use it. &setup; while(1) { #start the game... $input = &getInput; &checkInputAgainstWord; &checkForWord; } exit; sub setup() { $hangman = 0; print "Welcome to hangman, the goal is to guess all the letters in the word shown!\n"; print "If you guess a wrong letter, you'll see another body part of this: \n @hangman. If you see all of the body, you lose.\n"; sleep(1); my $number = int( rand( scalar( @words ) ) ); if ($number >= scalar(@words)) { $number -= 1;} #just in case the rand function is exactly the number of scalars in the words array, this will subtract the number variable by 1 so that it doesn't get an index out-of-bound error. $word = $words[$number]; @word = split //, $word; %found = (); foreach my $char (@word) { $found{$char} = 0; print "_"; } print "\n"; } sub getInput() { my $input; while (length($input) != 1) { $input = ; chomp($input); if (length($input) > 1) { print "you entered more than one character.\n"; } } return $input; } sub checkInputAgainstWord() { my $true = 0; foreach my $char (@word) { if ($input =~ m/^$char$/) { $found{$char} = 1; $true = 1; } else { } } if ($true) { &showWord; } else { &showHangman; } } sub showWord() { #show the word with the guessed characters. foreach my $char (@word) { if ($found{$char} == 1) { print $char; } else { print "_"; } } print "\n"; } sub checkForWord() { my $true = 1; foreach my $char (@word) { if ($found{$char} == 1) { } else { $true = 0; } } if ($true==1) { &Won } } sub Won() { print "You got it! play again?y/n\n"; my $answer = ; chomp($answer); if($answer =~ m/y/) { &setup; } else { exit; } } sub showHangman() { for (my $i = 0; $i < ($hangman+1); $i++) { print $hangman[$i]; } print "\n"; $hangman++; if ($hangman >= scalar(@hangman)) { &Lost; } } sub Lost() { print "\nYou lost! The word was $word. Play again? y/n\n"; my $input = ; chomp($input); if ($input =~ m/y/) { &setup; } else { exit; } }