By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 main.py

View raw Download
text/x-script.python • 5.27 kiB
Python script, ASCII text executable
        
            
1
#!/usr/bin/python3
2
3
__version__ = "v0.1"
4
5
from termcolor import colored as col
6
import colorama
7
from random import choice
8
import time
9
import argparse
10
11
colorama.init()
12
13
logo = col("TTY-WORDLE", "light_yellow", attrs=["bold"])
14
15
16
parser = argparse.ArgumentParser(prog="tty-wordle", description="A Wordle for your console.")
17
parser.add_argument("-a", "--analyser", dest="analyser", action="store_true", help="add the analyser, a row of all found letters")
18
parser.add_argument("-p", "--placeholder", dest="placeholder", action="store_true", help="add a word placeholder")
19
parser.add_argument("-x", "--hard", dest="hard", action="store_true", help="enable hard Wordle: you must use all found letters in your guesses")
20
parser.add_argument("--delay", dest="delay", type=float, default=1, help="time to show error messages for, in seconds")
21
parser.add_argument("-l", "--list", dest="words", default="./guesses.txt", help="file to pull allowed guesses from")
22
parser.add_argument("-n", "--answers", dest="answers", default="./answers.txt", help="file to pull a random answer from")
23
parser.add_argument("-t", "--tries", dest="guesses", type=int, default=6, help="number of tries")
24
args = parser.parse_args()
25
analyser = args.analyser
26
placeholder = args.placeholder
27
hard = args.hard
28
errorDelay = args.delay
29
guesses = args.guesses
30
with open(args.words) as file:
31
words = [line.rstrip().upper() for line in file]
32
with open(args.answers) as file:
33
answers = [line.rstrip().upper() for line in file]
34
word = choice(answers)
35
36
37
def clearLines(n=1):
38
up = '\033[1A'
39
clear = '\x1b[2K'
40
for i in range(n):
41
print(up, end=clear)
42
43
44
def getPlaced(letter):
45
return col("[" + letter + "]", "white", "on_green", attrs=["bold"])
46
47
48
def getFound(letter):
49
return col("(" + letter + ")", "white", "on_yellow")
50
51
52
def getBad(letter):
53
return col(" " + letter + " ", "white", "on_grey")
54
55
56
placed = {}
57
found = set()
58
bad = set()
59
60
61
def getWord(guess):
62
global word, placed, found, bad
63
ci = 0
64
formatted = ""
65
correct = True
66
67
for c in guess:
68
if c == word[ci]:
69
formatted += getPlaced(c)
70
placed[c] = ci
71
elif c in word:
72
formatted += getFound(c)
73
correct = False
74
found.add(c)
75
else:
76
formatted += getBad(c)
77
correct = False
78
bad.add(c)
79
ci += 1
80
return formatted, correct
81
82
83
def getPlaceholder():
84
global word
85
placeholder = col(len(word) * "[ ]", "light_grey", "on_grey", attrs=["dark"])
86
return placeholder
87
88
89
# Information
90
print(f"{ logo } {__version__} ({ col('tty-wordle --help', 'light_blue') } for more information)")
91
92
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
93
print(f"Guess a {len(word)}-letter word")
94
print(f"{ getPlaced(choice(alphabet)) } - letter is in the word and at the correct position")
95
print(f"{ getFound(choice(alphabet)) } - letter appears in the word, but at another position")
96
print(f"{ getBad(choice(alphabet)) } - letter isn't anywhere in the word")
97
98
99
# Game
100
i = 1
101
while i <= guesses:
102
if placeholder:
103
print(getPlaceholder())
104
try:
105
guess = input(f"Your Guess ({i}/{guesses}) > ").upper()
106
except KeyboardInterrupt:
107
try:
108
print()
109
clearLines()
110
giveup = input(f"{ col('Give up?', 'light_red') } (y/n/^C) > ").upper()
111
if giveup == "Y" or giveup == "YES":
112
clearLines(1 + placeholder)
113
print(f"{ col('Game Over:', 'light_red', attrs=['bold']) } You gave up at guess {i}/{guesses}.")
114
break
115
else:
116
clearLines(1 + placeholder)
117
continue
118
except KeyboardInterrupt:
119
print()
120
exit()
121
122
if hard:
123
invalid = False
124
for c in found:
125
if c not in guess:
126
invalid = True
127
for c in placed.keys():
128
if c != guess[placed[c]]:
129
invalid = True
130
if invalid:
131
print(f"{ col('Error:', 'light_red', attrs=['bold']) } Hard Mode: Please use all revealed hints")
132
time.sleep(errorDelay)
133
clearLines(2)
134
continue
135
if guess not in words or len(guess) != len(word):
136
if not guess:
137
clearLines()
138
continue
139
else:
140
print(f"{ col('Error:', 'light_red', attrs=['bold']) } Invalid word")
141
try:
142
time.sleep(errorDelay)
143
clearLines(2 + placeholder)
144
continue
145
except KeyboardInterrupt:
146
print()
147
clearLines(3 + placeholder)
148
continue
149
else:
150
clearLines(1 + (analyser if i > 1 else 0) + placeholder)
151
formatted, correct = getWord(guess)
152
print(str(i) + ". " + formatted)
153
if analyser:
154
print("Letters:", end=" ")
155
for c in placed.keys():
156
print(getPlaced(c), end="")
157
for c in found:
158
print(getFound(c), end="")
159
for c in bad:
160
print(getBad(c), end="")
161
print()
162
if correct:
163
print(f"{ col('Game Over:', 'light_green', attrs=['bold']) } You guessed the word in {i} tries.")
164
break
165
if i == guesses and not correct:
166
print(f"{ col('Game Over:', 'light_red', attrs=['bold']) }: You lost.")
167
i += 1
168
print(f"The word was { col(word, color='light_green', attrs=['underline']) }")
169