Made after seeing A Simple Word Guessing Game. Any code critique is welcome!
import urllib.request as Web
import random
import string
def get_words():
url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
req = Web.Request(url)
res = Web.urlopen(req).read().splitlines()
return res
def get_target():
words = get_words()
while True:
target = random.choice(words).decode('utf8')
if len(target) > 2 and "'" not in target and '.' not in target:
return target
def get_guess():
print('Guess a single letter!')
while True:
guess = input().strip()
if len(guess) == 1:
if guess.isalpha():
return guess
elif guess.isdigit():
return string.ascii_lowercase[int(guess)]
else:
print('[!] Needs to be alnum << ', end='', flush=True)
else:
print('[!] Needs only one char << ', end='', flush=True)
def play_game():
print('Fetching a random word...')
target = get_target()
comp = ['_' for _ in target]
print("Alright, we're ready to play!\n")
while True:
print('Target:', ' '.join(comp))
guess = get_guess()
if guess in target:
for i, c in enumerate(target):
if c == guess:
comp[i] = c
if '_' in comp:
print()
else:
print('Congrats! You won!')
return 0
if __name__ == "__main__":
play_game()