Skip to content

Instantly share code, notes, and snippets.

@billtubbs
Created January 19, 2017 05:03
Show Gist options
  • Save billtubbs/228688a2934ae1620719910ad291a88f to your computer and use it in GitHub Desktop.
Save billtubbs/228688a2934ae1620719910ad291a88f to your computer and use it in GitHub Desktop.
Hangman Game - Part 2
#!/usr/bin/env python
# PRACTICE PYTHON script
# Part 1. Pick Word
# Part 2. User guesses letters until they get it right
# http://www.practicepython.org/exercise/2016/09/24/30-pick-word.html
import random
SOWPODS_FILE = "sowpods.txt"
def random_word(filename=SOWPODS_FILE):
"""Returns a random word from a local
copy of the SOWPODS dictionary downloaded
from here:
http://norvig.com/ngrams/sowpods.txt"""
f = open(filename, 'r')
lines = f.readlines()
f.close()
return random.choice(lines).strip()
print "\n -------- Hangman Game --------\n"
word = random_word().lower()
print "Uncover the mystery word by guessing which"
print "letters it contains."
found_letters = []
incorrect_guesses = []
while len(found_letters) < len(word):
print ''.join([a + ' ' if a in found_letters else '_ ' for a in word ])
print "Incorrect guesses:", incorrect_guesses
print "Guess a new letter:"
while True:
c = raw_input(">").lower()
if len(c) != 1:
print "Enter one letter at a time"
continue
if c.isalpha():
if c in incorrect_guesses or c in found_letters:
print "You already tried that."
else:
break
else:
print "Must be between a-z."
if c in word:
found_letters.append(c)
else:
incorrect_guesses.append(c)
print "Correct. Well done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment