|
| 1 | +#!python3 |
| 2 | +# Code Challenge 02 - Word Values Part II - a simple game |
| 3 | +# http://pybit.es/codechallenge02.html |
| 4 | + |
| 5 | +import random |
| 6 | +from collections import Counter |
| 7 | +from typing import Dict, List |
| 8 | + |
| 9 | +from data import DICTIONARY, LETTER_SCORES, POUCH |
| 10 | + |
| 11 | +NUM_LETTERS = 7 |
| 12 | +PERCENTAGE_MULTIPLIER = 100 |
| 13 | + |
| 14 | + |
| 15 | +# re-use from challenge 01 |
| 16 | +def calc_word_value(word): |
| 17 | + """Calc a given word value based on Scrabble LETTER_SCORES mapping""" |
| 18 | + return sum(LETTER_SCORES.get(char.upper(), 0) for char in word) |
| 19 | + |
| 20 | + |
| 21 | +# re-use from challenge 01 |
| 22 | +def max_word_value(words): |
| 23 | + """Calc the max value of a collection of words""" |
| 24 | + return max(words, key=calc_word_value) |
| 25 | + |
| 26 | + |
| 27 | +def draw_letters() -> List[str]: |
| 28 | + return random.sample(POUCH, NUM_LETTERS) |
| 29 | + |
| 30 | + |
| 31 | +def is_legal_word(word: str, drawn_letters_count: Dict[str, int]) -> bool: |
| 32 | + word_letters_count = Counter(word.upper()) |
| 33 | + for letter, count in word_letters_count.items(): |
| 34 | + if count > drawn_letters_count.get(letter, 0): |
| 35 | + return False |
| 36 | + |
| 37 | + return True |
| 38 | + |
| 39 | + |
| 40 | +def get_possible_dict_words(drawn_letters: List[str]) -> List[str]: |
| 41 | + drawn_letters_count = Counter(drawn_letters) |
| 42 | + return [word for word in DICTIONARY if is_legal_word(word, drawn_letters_count)] |
| 43 | + |
| 44 | + |
| 45 | +def main() -> None: |
| 46 | + drawn_letters = draw_letters() |
| 47 | + legal_words = get_possible_dict_words(drawn_letters) |
| 48 | + print(f"Letters drawn: {', '.join(drawn_letters)}") |
| 49 | + |
| 50 | + user_input = input("Form a valid word: ") |
| 51 | + while user_input not in legal_words: |
| 52 | + user_input = input("Nope, please try a different word: ") |
| 53 | + |
| 54 | + user_word = user_input.upper() |
| 55 | + user_score = calc_word_value(user_word) |
| 56 | + print(f"Word chosen: {user_word} (value: {user_score})") |
| 57 | + |
| 58 | + best_word = max_word_value(legal_words) |
| 59 | + best_score = calc_word_value(best_word) |
| 60 | + print(f"Optimal word possible: {best_word} (value: {best_score})") |
| 61 | + |
| 62 | + print(f"You scored: {PERCENTAGE_MULTIPLIER * user_score / best_score : .2f}") |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + main() |
0 commit comments