View Single Post
Old May 10th, 2006, 1:48 PM   #1
commodore
Programmer
 
Join Date: Nov 2005
Location: Estonia
Posts: 97
Rep Power: 0 commodore is an unknown quantity at this point
Noob trying to code hangman :(

I wanted to create a CLI hangman. It's supposed to read words from a while, choose a random word, let people do the guessing and stuff and if someone guesses the word it will be removed from the file. It somewhat worked but I didn't get any further. Don't laugh too hard at me...

import random
import sys
import time
filer=open('words.txt', 'r')

words=filer.read().split('\n') # puts the words in a list
orgwordstring=str(words[random.randint(0, (len(words)-1))]) # chooses a random word from the list
orgword=[]
for i in orgwordstring: # puts the letters in a string
    orgword.append(i)

ranges=len(orgword)-2 # how many letters have to be replaced with '_'
newword=[orgword[0]]
for i in range(1, ranges+1):
    newword.append('_')
newword.append(orgword[-1])

life=10
while newword!=orgword or life!=0:
    print 'The word is: %s' % (' '.join(newword))
    print ''
    what=str(raw_input('Type in a letter that you think should be in that word or leave empty if you want to quit: '))
    if what=="":
        sys.exit()
    elif ''.join(orgword).find(what)==-1:
        life=life-1
        print 'Sorry this letter isn\'t included in the word. You have lost a life. You have %d lives left' % (life)
    else:
        finding=''.join(orgword).find(what)
        while finding!=-1:
            newword[finding]=orgword[finding]

filer.close()
if life!=0:
    'Gongratulations! You have guessed the word! It is ', newword
    wordloc=''.join(words).find(orgword)
    del words[wordloc]  # deletes the guessed word from the list
    words='\n'.join(words)                     
    filew=open('words.txt', 'w')
    filew.write(words)  # writes the words back to the file, now without the guessed word
    filew.close()
else:
    'You have 0 lives left. You didn\'t guess the word.'
time.sleep(10)
sys.exit()
commodore is offline   Reply With Quote