You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.6 KiB

  1. import argparse
  2. from string import ascii_lowercase
  3. import cmd2
  4. import re
  5. import os
  6. from candidates import candidates, filter_possibilities
  7. from dictionary import DEFAULT, ALTERNATE
  8. from word_remove_dialog import RemoveWordsActivity
  9. LOWERCASE = set(ascii_lowercase)
  10. DICTS = {"default": DEFAULT, "alt": ALTERNATE}
  11. # argparsers
  12. dictionary_manage_parser = argparse.ArgumentParser()
  13. commands = dictionary_manage_parser.add_mutually_exclusive_group()
  14. commands.add_argument(
  15. "-l", "--list", action="store_true", help="List available dictionaries"
  16. )
  17. commands.add_argument("-s", "--switch", help="Dictionary to swap to")
  18. letter_set_manage = argparse.ArgumentParser()
  19. letter_set_manage.add_argument("letter", nargs="+")
  20. guessing = argparse.ArgumentParser()
  21. guessing.add_argument("pattern", help="Pattern to match")
  22. class MainLoop(cmd2.Cmd):
  23. """Loop for wordscape commands
  24. """
  25. prompt = "<{}> $ "
  26. def __init__(self):
  27. self.dict = "default"
  28. self.excludes = set()
  29. self.init_letters(input("Enter letters: "))
  30. super().__init__()
  31. def init_letters(self, letters):
  32. if not isinstance(letters, str):
  33. letters = "".join(letters)
  34. letters = letters.lower()
  35. self.letters = [l for l in letters if l in LOWERCASE]
  36. self.prompt = MainLoop.prompt.format(", ".join(self.letters))
  37. self.candidates = candidates(self.letters, DICTS[self.dict], self.excludes)
  38. @cmd2.with_argparser(dictionary_manage_parser)
  39. def do_dict(self, args):
  40. """list/switch dict"""
  41. if args.list:
  42. print(
  43. "\n".join(
  44. (
  45. "{} {}".format("*" if key == self.dict else " ", key)
  46. for key in DICTS.keys()
  47. )
  48. )
  49. )
  50. else:
  51. DICTS[args.switch]
  52. self.dict = args.switch
  53. @cmd2.with_argparser(letter_set_manage)
  54. def do_change_letters(self, args):
  55. """Change the letters on the board"""
  56. self.init_letters(args.letter)
  57. @cmd2.with_argparser(guessing)
  58. def do_find(self, args):
  59. """Find words that match a pattern"""
  60. pattern = re.compile(args.pattern + "$")
  61. matching_words = filter_possibilities(self.candidates, pattern)
  62. app = RemoveWordsActivity(matching_words, self.excludes)
  63. if os.name == "nt":
  64. app.run(fork=False)
  65. else:
  66. app.run()
  67. was_canceled, new_exludes = app.get_results()
  68. if not was_canceled:
  69. self.excludes.update(new_exludes)
  70. if __name__ == "__main__":
  71. MainLoop().cmdloop()