mastermind.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import random
  2. COLORS = {
  3. 'R': 'red',
  4. 'G': 'green',
  5. 'B': 'blue',
  6. 'Y': 'yellow',
  7. 'O': 'orange',
  8. 'P': 'purple',
  9. }
  10. SLOTS = 4
  11. class Mastermind():
  12. riddle: list
  13. guesses: list
  14. def __init__(self):
  15. self.reset()
  16. def guess(self, combination: list):
  17. self.guesses.append(combination)
  18. black = len([1 for c, r in zip(combination, self.riddle) if c == r])
  19. white = -black
  20. for c in COLORS.keys():
  21. white += max(combination.count(c) - self.riddle.count(c), 0)
  22. return (black, white)
  23. def reset(self):
  24. self.riddle = random.choices(list(COLORS.keys()), k=SLOTS)
  25. self.guesses = []
  26. if __name__ == '__main__':
  27. mm = Mastermind()
  28. print("Colors:")
  29. for k, c in COLORS.items():
  30. print(" " + k + ": " + c)
  31. print("")
  32. while True:
  33. guess = input("What's your guess? ")
  34. res = mm.guess(list(guess))
  35. print(res)
  36. if res[0] == 4:
  37. print("That's right! Congratulations!")
  38. mm.reset()