game_logic.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import random
  2. from typing import List, Dict, Optional, Tuple
  3. from dataclasses import dataclass
  4. @dataclass
  5. class Card:
  6. id: int
  7. color: int
  8. shape: int
  9. fill: int
  10. count: int
  11. class SetGame:
  12. def __init__(self):
  13. self.deck = self._generate_deck()
  14. self.field = []
  15. self.score = 0
  16. self.game_over = False
  17. self._initialize_field()
  18. def _generate_deck(self) -> List[Card]:
  19. deck = []
  20. card_id = 0
  21. for color in [1, 2, 3]:
  22. for shape in [1, 2, 3]:
  23. for fill in [1, 2, 3]:
  24. for count in [1, 2, 3]:
  25. deck.append(Card(
  26. id=card_id,
  27. color=color,
  28. shape=shape,
  29. fill=fill,
  30. count=count
  31. ))
  32. card_id += 1
  33. random.shuffle(deck)
  34. return deck
  35. def _initialize_field(self):
  36. for _ in range(12):
  37. if self.deck:
  38. self.field.append(self.deck.pop())
  39. def get_field(self) -> List[Dict]:
  40. return [
  41. {
  42. "id": card.id,
  43. "color": card.color,
  44. "shape": card.shape,
  45. "fill": card.fill,
  46. "count": card.count
  47. }
  48. for card in self.field
  49. ]
  50. def check_set(self, card_ids: List[int]) -> bool:
  51. if len(card_ids) != 3:
  52. return False
  53. cards = [card for card in self.field if card.id in card_ids]
  54. if len(cards) != 3:
  55. return False
  56. for attribute in ['color', 'shape', 'fill', 'count']:
  57. values = [getattr(card, attribute) for card in cards]
  58. unique_values = set(values)
  59. if len(unique_values) not in [1, 3]:
  60. return False
  61. return True
  62. def remove_cards(self, card_ids: List[int]):
  63. self.field = [card for card in self.field if card.id not in card_ids]
  64. while len(self.field) < 12 and self.deck:
  65. self.field.append(self.deck.pop())
  66. if not self.deck and len(self.field) < 3:
  67. self.game_over = True
  68. def add_cards(self, count: int = 3):
  69. for _ in range(min(count, len(self.deck))):
  70. if self.deck:
  71. self.field.append(self.deck.pop())
  72. def is_game_over(self) -> bool:
  73. return self.game_over
  74. def find_sets_on_field(self) -> List[List[int]]:
  75. sets = []
  76. n = len(self.field)
  77. for i in range(n):
  78. for j in range(i + 1, n):
  79. for k in range(j + 1, n):
  80. if self.check_set([self.field[i].id, self.field[j].id, self.field[k].id]):
  81. sets.append([self.field[i].id, self.field[j].id, self.field[k].id])
  82. return sets
  83. def get_deck_size(self) -> int:
  84. return len(self.deck)