Skip to content

Instantly share code, notes, and snippets.

@y1n0
Created February 27, 2017 19:44
Show Gist options
  • Select an option

  • Save y1n0/2151c2cfb099a51ee558ad590adfbc68 to your computer and use it in GitHub Desktop.

Select an option

Save y1n0/2151c2cfb099a51ee558ad590adfbc68 to your computer and use it in GitHub Desktop.
the hangman game. Exercise 30 from practicepython.org
#!/usr/bin/python3.5
import random
def pickWord():
with open('hang_words.txt', 'r') as f:
x = random.randint(0, 267750)
# print x
for i in range(267750):
line = f.readline()
if x==i:
return line.strip('\n');
word = pickWord()
guess = ['_' for i in range(len(word))]
triedLetters = []
tries = 6
print(' '.join(guess))
while tries > 0:
letter = input('enter your letter: ').upper()
while len(letter) > 1 or len(letter) == 0:
letter = input('Please enter only one letter: ').upper()
if letter in triedLetters:
print('this letter is used before')
elif letter in word:
i = 0
for l in word:
if l == letter:
guess[i] = letter
elif l in guess:
guess[i] = guess[i]
else:
guess[i] = '_'
i += 1
print(''.join(guess))
if '_' not in guess:
print('you won!')
break;
else:
print('incorrect!')
tries -= 1
if tries != 0:
print('you have', tries, 'left')
else:
print('you lost! the word was :', word)
triedLetters.append(letter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment