-
-
Save horstjens/6041081 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.3 | |
# -*- coding: utf-8 -*- | |
"""A Hangman Demo for Python3 form yipyip. Guess some python3 keywords ! | |
see https://gist.github.com/yipyip/6038584 for original code | |
""" | |
#### | |
import random | |
#### | |
def hangman(solution, percent=0, placeholder='_', prompt='? '): | |
"""Hangman game loop. | |
""" | |
task = make_task(solution, percent, placeholder) | |
while placeholder in task: | |
print(task) | |
guess = input(prompt) | |
if not guess: | |
continue | |
guess0 = guess[0] | |
task = ''.join(guess0 if guess0 == solution_char else task_char | |
for task_char, solution_char in zip(task, solution)) | |
else: | |
print(task) | |
#### | |
def make_task(solution, percent, placeholder): | |
"""Return list of chars to guess. | |
""" | |
task_len = len(solution) | |
show_len = int(task_len * percent / 100.0) | |
chars = [1] * show_len + [0] * (task_len - show_len) | |
random.shuffle(chars) | |
return ''.join(char if i else placeholder for char, i in zip(solution, chars)) | |
#### | |
def get_words(placeholder): | |
"""Return list of words to guess. | |
""" | |
import builtins | |
return [s.lower() for s in builtins.__dict__ \ | |
if not placeholder in s] | |
#### | |
def main(conf): | |
"""Play multiple rounds of hangman. | |
""" | |
words = get_words(conf['placeholder']) | |
while words: | |
task = random.choice(words) | |
hangman(task, **conf) | |
print("You got it!") | |
words.remove(task) | |
if not input("Again? [y|n] ") == "y": | |
break | |
else: | |
print("Nothing left.") | |
#### | |
CONFIG = {'percent': 25, | |
'placeholder': '_', | |
'prompt': "Lowercase letter? "} | |
if __name__ == '__main__': | |
main(CONFIG) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment