-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwurdle.py
More file actions
executable file
·92 lines (75 loc) · 2.84 KB
/
wurdle.py
File metadata and controls
executable file
·92 lines (75 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/bin/env python3
import pathlib
import random
from string import ascii_letters
from rich.console import Console
from rich.theme import Theme
console = Console(width=80, theme= Theme({"warning": "red on yellow"}))
def refresh_page(headline):
console.clear()
console.rule(f"[bold blue]:leafy_green: {headline} :leafy_green: [/]")
def show_guesses(guesses, word):
for guess in guesses:
styled_guess = []
for letter, correct in zip(guess, word):
if letter == correct:
style = "bold white on green"
elif letter in word:
style = "bold white on yellow"
elif letter in ascii_letters:
style = "white on #666666"
else:
style = "dim"
styled_guess.append(f"[{style}]{letter}[/]")
console.print("".join(styled_guess), justify="center")
def get_random_word(wordlist: list):
"""choose a word at random from an existing word list
Ensure that the word is five letters long
"""
if words := [
word.upper()
for word in wordlist
if len(word) == 5 and all(letter in ascii_letters for letter in word)
]:
return random.choice(words)
else:
console.print("No words of lenth 5 in the word list", style="warning")
raise SystemExit()
def game_over(guesses, word, guessed_correctly):
refresh_page(headline="Game Over")
show_guesses(guesses, word)
if guessed_correctly:
console.print(f"\n[bold wjite on green]correct, the word is {word}[/]")
else:
console.print(f"\n[bold white on red] Sorry, the word was {word}[/]")
def guess_word(previous_guesses):
guess = console.input("\nGuess word: ").upper()
if guess in previous_guesses:
console.print(f"You've already guessed {guess}.", style="warning")
return guess_word(previous_guesses)
if len(guess) != 5:
console.print("Your guess must be 5 letters.", style="warning")
return guess_word(previous_guesses)
if any((invalid := letter) not in ascii_letters for letter in guess):
console.print(
f"Invalid letter: '{invalid}'. Please use English letters.",
style="warning",
)
return guess_word(previous_guesses)
return guess
def main():
# Pre-process
words_path = pathlib.Path("wordlist.txt")
word = get_random_word(words_path.read_text(encoding="utf-8").split("\n"))
guesses = ["_" * 5] * 6
# Process (main loop)
for idx in range(6):
refresh_page(headline=f"Guess {idx + 1}")
show_guesses(guesses, word)
guesses[idx] = guess_word(previous_guesses=guesses[:idx])
if guesses[idx] == word:
break
# Post-process
game_over(guesses, word, guessed_correctly=guesses[idx] == word)
if __name__ == "__main__":
main()