Skip to content

Instantly share code, notes, and snippets.

@paiv
Created October 25, 2022 16:00
Show Gist options
  • Save paiv/128c742ae5ef74158bc6eb5042ba6ba7 to your computer and use it in GitHub Desktop.
Save paiv/128c742ae5ef74158bc6eb5042ba6ba7 to your computer and use it in GitHub Desktop.
Wordle game
usage: wordle.py [-h] [-n N] [--word WORD] wordlist
positional arguments:
wordlist word list file
options:
-h, --help show this help message and exit
-n N, --max-attempts N
maximum attempts
--word WORD play this word
#!/usr/bin/env python
import random
import re
import readline
def main(wordlist, max_attempts, secret):
clean = re.compile(r'\W+')
def norm(w): return clean.sub('', w.lower())
with open(wordlist) as fp:
db = [s.strip() for s in fp]
words = set(db)
if secret:
target = norm(secret)
size = len(target)
else:
size = max(map(len, map(norm, db)))
while True:
secret, = random.sample(db, 1)
if len(set(norm(secret))) == size: break
target = norm(secret)
err = '\001\033[40;31m\002'
warm = '\001\033[43;30m\002'
exact = '\001\033[42;30m\002'
reset = '\001\033[m\002'
palette = [reset, warm, exact]
def check(a, t):
return [(2 if x == w else int(x in t)) for x,w in zip(a, t)]
attempts = list()
seen = set()
prompt = '?' * size
solved = False
while len(attempts) < max_attempts:
if seen:
print('-', ''.join(sorted(seen)))
attempt = input(f'{prompt} > ').strip().lower()
if attempt not in words:
if attempt: print(f'{err}not a word{reset}')
continue
attempt = norm(attempt)
seen |= set(attempt) - set(target)
attempts.append(attempt)
qs = check(attempt, target)
prompt = ''.join(f'{palette[q]}{x}{reset}' for x,q in zip(attempt,qs))
if all(x == w for x,w in zip(attempt, target)):
solved = True
print(prompt)
break
sn = ['-', len(attempts)][solved]
print(secret, f'{sn}/{max_attempts}')
pw = ['⬜️','🟨','🟩']
for w in attempts:
print(''.join(pw[i] for i in check(w, target)))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('wordlist', help='word list file')
parser.add_argument('-n', '--max-attempts', metavar='N', type=int, default=6, help='maximum attempts')
parser.add_argument('--word', help='play this word')
args = parser.parse_args()
main(args.wordlist, args.max_attempts, args.word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment