Simple Hangman Game
Posted 09-16-2008 at 07:35 AM by ghostdog74
I was so bored today, that i created this simple hangman game to entertain myself. Makes use of a dictionary file called "english" to get random word to guess. No fancy stuff like drawing the man, only number of tries (set to 10)
Code:
#!/bin/bash
awk 'BEGIN{
dictfile="english"
l="abcdefghijklmnopqrstuvwxyz"
while (1) {
srand()
lm=split(l,letters,"")
if ( ( getline < dictfile) <= 0 ) {
print "Dictionary file does not exists"
}else {
tries=10
count=getlinecount(dictfile)
num=int(rand() * count) + 1
WORD=randomword(dictfile,num)
gsub(/[[:blank:]]$|[[:space:]]|[0-9]+$/,"",WORD)
WORD=tolower(WORD)
m=split(WORD,word,"")
for(i=1;i<=m;i++){ THEWORD[i] ="_" }
for(j=1;j<=m;j++){ printf "%s",THEWORD[j] }
print ""
while(tries>0){
flag=0
printf "Choose a letter (Enter full word to complete): "
printf "You have "tries" tries\n"
for(o=1;o<=lm;o++){ printf letters[o] }
print ""
getline LETTER < "-"
if ( LETTER==WORD || join(THEWORD,1,m,SUBSEP) == WORD ) {
print "congratulations! "
exit
}
system("clear")
for( o=1;o<=m;o++) {
if ( word[o] == LETTER ) {
flag=1
THEWORD[o]=LETTER
for(i in letters){
if ( letters[i]==LETTER) { delete letters[i] }
}
}
}
if (flag==0){ tries-- }
for(i=1;i<=m;i++){
printf THEWORD[i]
}
print ""
}
print "You hanged yourself!"
print "The answer is "WORD
}
}
}
function getlinecount(file){
count=0
while ( ( getline < file ) > 0 ) count++
close(file)
return count
}
function randomword(file,linenumber){
count=0
while ( ( getline dictline< file) > 0 ) {
count++
if ( count == linenumber) {
gsub(/[[:punct:]]/,"",dictline)
gsub(/ +$/,"",dictline)
m=split(dictline,toguess," ")
if (m>1){
num = int(rand() * m) + 1
return toguess[num]
}else {
return dictline
}
}
}
close(file)
}
function join(array, start, end, sep, result, i)
{
if (sep == "")
sep = " "
else if (sep == SUBSEP) # magic value
sep = ""
result = array[start]
for (i = start + 1; i <= end; i++)
result = result sep array[i]
return result
}
'









