Created
September 6, 2018 14:03
-
-
Save mguijarr/8850ff20f7b932f05c0929fc59ce4532 to your computer and use it in GitHub Desktop.
Jeu du pendu
This file contains hidden or 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
import random | |
import os | |
import sys | |
import unidecode | |
HANGMAN = [""" | |
_______ | |
|/ | | |
| | |
| | |
| | |
| | |
| | |
_|___ | |
""", | |
""" | |
_______ | |
|/ | | |
| (_) | |
| | |
| | |
| | |
| | |
_|___ | |
""", | |
""" | |
_______ | |
|/ | | |
| (_) | |
| \|/ | |
| | |
| | |
| | |
_|___ | |
""", | |
""" | |
_______ | |
|/ | | |
| (_) | |
| \|/ | |
| | | |
| | |
| | |
_|___ | |
""", | |
""" | |
_______ | |
|/ | | |
| (_) | |
| \|/ | |
| | | |
| / L | |
| | |
_|___ | |
"""] | |
def find_word(): | |
word = None | |
dictionary_file = os.path.join(os.path.dirname(__file__), "french.txt") | |
with open(dictionary_file, encoding='latin-1') as df: | |
while True: | |
i = random.randint(0, 22739) | |
word = next((line.strip() for j, line in enumerate(df) if i==j)) | |
if word[0].isupper(): | |
df.seek(0) | |
else: | |
break | |
return word | |
def g_display_hangman(): | |
"""Display hangman""" | |
for h in HANGMAN: | |
yield h+'\n' | |
def g_ask_for_char(): | |
already_tried = [] | |
while True: | |
input_char = input("Proposer une lettre: ").upper() | |
if len(input_char) > 1: | |
continue | |
if input_char in already_tried: | |
print(f"Deja essaye: {input_char}") | |
continue | |
already_tried.append(input_char) | |
yield input_char | |
def display_word(word, found): | |
print('\n') | |
print("Mot: {}".format(" ".join([c if found[i] else "_" for i,c in enumerate(word)]))) | |
print('\n') | |
def start_game(debug): | |
game_over = False | |
word = find_word() | |
assert word is not None | |
if debug: | |
print(f'Mot a trouver = {word}') | |
normalized_word = unidecode.unidecode(word).upper() | |
found_chars = [False]*len(word) | |
display_hangman = g_display_hangman() | |
ask_for_char = g_ask_for_char() | |
print(next(display_hangman)) | |
while not game_over: | |
display_word(word, found_chars) | |
input_char = next(ask_for_char) | |
if input_char in word.upper(): | |
found_chars = [found_chars[i] or input_char==c for i,c in enumerate(normalized_word)] | |
if all(found_chars): | |
break | |
else: | |
try: | |
print(next(display_hangman)) | |
except StopIteration: | |
game_over = True | |
if game_over: | |
print(f"Dommage... Le mot etait: {word}") | |
else: | |
print("Super!") | |
if __name__ == '__main__': | |
debug = False | |
if '-d' in sys.argv[1:]: | |
debug = True | |
start_game(debug) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment