Advertisement
Hasli4

Untitled

Mar 21st, 2025
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.77 KB | None | 0 0
  1. import random
  2. import time
  3.  
  4. class Point:
  5.     """Класс для представления точки на окружности"""
  6.     def __init__(self, index):
  7.         self.index = index
  8.         self.color = None  # None - не окрашена, 'red' - красная, 'blue' - синяя
  9.    
  10.     def is_colored(self):
  11.         """Проверяет, окрашена ли точка"""
  12.         return self.color is not None
  13.    
  14.     def set_color(self, color):
  15.         """Устанавливает цвет точки"""
  16.         if color not in ['red', 'blue']:
  17.             raise ValueError("Цвет должен быть 'red' или 'blue'")
  18.         self.color = color
  19.  
  20. class Game:
  21.     """Основной класс игры"""
  22.     def __init__(self, num_points=9, player_vs_computer=True):
  23.         self.num_points = num_points
  24.         self.points = [Point(i) for i in range(num_points)]
  25.         self.current_player = "Петя"  # Петя ходит первым
  26.         self.player_vs_computer = player_vs_computer
  27.         self.last_colored_points = []  # Список последних окрашенных точек для отслеживания
  28.    
  29.     def get_available_moves(self):
  30.         """Возвращает список доступных ходов"""
  31.         if all(point.is_colored() for point in self.points):
  32.             return []  # Нет доступных ходов, если все точки окрашены
  33.        
  34.         # Для первого хода Пети доступны все точки
  35.         if not any(point.is_colored() for point in self.points):
  36.             return list(range(self.num_points))
  37.        
  38.         available_moves = []
  39.         for i in range(self.num_points):
  40.             if not self.points[i].is_colored():
  41.                 # Проверяем, есть ли окрашенные соседние точки
  42.                 left_neighbor = (i - 1) % self.num_points
  43.                 right_neighbor = (i + 1) % self.num_points
  44.                
  45.                 if self.points[left_neighbor].is_colored() or self.points[right_neighbor].is_colored():
  46.                     available_moves.append(i)
  47.        
  48.         return available_moves
  49.    
  50.     def make_move(self, point_index, color):
  51.         """Выполняет ход - окрашивает выбранную точку в указанный цвет"""
  52.         if point_index not in self.get_available_moves():
  53.             return False, "Недопустимый ход!"
  54.        
  55.         self.points[point_index].set_color(color)
  56.         self.last_colored_points.append(point_index)
  57.        
  58.         # Меняем текущего игрока
  59.         self.current_player = "Вася" if self.current_player == "Петя" else "Петя"
  60.        
  61.         return True, f"Точка {point_index} окрашена в {color} цвет"
  62.    
  63.     def check_equilateral_triangles(self):
  64.         """Проверяет наличие равносторонних треугольников одного цвета"""
  65.         # В окружности с 9 равноотстоящими точками равносторонний треугольник
  66.         # образуют точки, индексы которых отличаются на 3
  67.         # (например, 0, 3, 6 или 1, 4, 7 или 2, 5, 8)
  68.         triangles = []
  69.        
  70.         for start in range(3):
  71.             points_indices = [start, (start + 3) % 9, (start + 6) % 9]
  72.             colors = [self.points[i].color for i in points_indices]
  73.            
  74.             # Проверяем, что все точки окрашены и имеют один цвет
  75.             if colors[0] is not None and colors[0] == colors[1] == colors[2]:
  76.                 triangles.append((points_indices, colors[0]))
  77.        
  78.         return triangles
  79.    
  80.     def is_game_over(self):
  81.         """Проверяет, закончилась ли игра"""
  82.         # Игра заканчивается, когда все точки окрашены
  83.         if not all(point.is_colored() for point in self.points):
  84.             return False, None
  85.        
  86.         # Проверяем наличие равносторонних треугольников одного цвета
  87.         triangles = self.check_equilateral_triangles()
  88.        
  89.         if triangles:
  90.             # Вася выигрывает, если есть равносторонний треугольник одного цвета
  91.             return True, "Вася"
  92.         else:
  93.             # Петя выигрывает, если нет равностороннего треугольника одного цвета
  94.             return True, "Петя"
  95.    
  96.     def computer_move(self):
  97.         """Реализует ход компьютера"""
  98.         available_moves = self.get_available_moves()
  99.         if not available_moves:
  100.             return False, "Нет доступных ходов"
  101.        
  102.         # Проверяем, является ли компьютер Петей или Васей
  103.         is_computer_petya = self.current_player == "Петя"
  104.        
  105.         # Простая стратегия для компьютера
  106.         best_move = None
  107.         best_color = None
  108.        
  109.         # Перебираем все возможные ходы и цвета
  110.         for point_index in available_moves:
  111.             for color in ['red', 'blue']:
  112.                 # Временно делаем ход
  113.                 self.points[point_index].set_color(color)
  114.                
  115.                 # Проверяем наличие треугольников
  116.                 triangles = self.check_equilateral_triangles()
  117.                
  118.                 # Если компьютер играет за Васю и может выиграть
  119.                 if not is_computer_petya and triangles:
  120.                     best_move = point_index
  121.                     best_color = color
  122.                     self.points[point_index].color = None  # Отменяем временный ход
  123.                     break
  124.                
  125.                 # Если компьютер играет за Петю и может предотвратить победу Васи
  126.                 if is_computer_petya:
  127.                     # Проверяем, может ли следующий ход Васи привести к победе
  128.                     will_vasya_win = False
  129.                     temp_current_player = self.current_player
  130.                     self.current_player = "Вася" if self.current_player == "Петя" else "Петя"
  131.                    
  132.                     next_available_moves = self.get_available_moves()
  133.                     for next_move in next_available_moves:
  134.                         for next_color in ['red', 'blue']:
  135.                             self.points[next_move].set_color(next_color)
  136.                             if self.check_equilateral_triangles():
  137.                                 will_vasya_win = True
  138.                             self.points[next_move].color = None
  139.                             if will_vasya_win:
  140.                                 break
  141.                         if will_vasya_win:
  142.                             break
  143.                    
  144.                     self.current_player = temp_current_player
  145.                    
  146.                     if not will_vasya_win and (best_move is None or random.random() < 0.3):
  147.                         best_move = point_index
  148.                         best_color = color
  149.                
  150.                 # Отменяем временный ход
  151.                 self.points[point_index].color = None
  152.        
  153.         # Если нет хорошего хода, выбираем случайный
  154.         if best_move is None:
  155.             best_move = random.choice(available_moves)
  156.             best_color = random.choice(['red', 'blue'])
  157.        
  158.         # Делаем ход
  159.         success, message = self.make_move(best_move, best_color)
  160.         return success, f"Компьютер ({self.current_player if not success else ('Петя' if self.current_player == 'Вася' else 'Вася')}): {message}"
  161.  
  162.     def display_board(self):
  163.         """Отображает текущее состояние игрового поля"""
  164.         print("\nСостояние игры:")
  165.         print("  ", end="")
  166.         for i in range(self.num_points):
  167.             if self.points[i].color == 'red':
  168.                 print("R", end=" ")
  169.             elif self.points[i].color == 'blue':
  170.                 print("B", end=" ")
  171.             else:
  172.                 print("○", end=" ")
  173.         print("\n  ", end="")
  174.         for i in range(self.num_points):
  175.             print(i, end=" ")
  176.         print("\n")
  177.        
  178.         # Показываем последний ход
  179.         if self.last_colored_points:
  180.             last_point = self.last_colored_points[-1]
  181.             print(f"Последний ход: точка {last_point} окрашена в {self.points[last_point].color}")
  182.        
  183.         # Показываем текущего игрока
  184.         print(f"Сейчас ходит: {self.current_player}")
  185.        
  186.         # Показываем доступные ходы
  187.         available_moves = self.get_available_moves()
  188.         if available_moves:
  189.             print(f"Доступные ходы: {available_moves}")
  190.  
  191. def play_game():
  192.     """Функция для запуска игры с пользовательским вводом"""
  193.     print("Добро пожаловать в игру Strat17!")
  194.     print("Правила:")
  195.     print("- На окружности отмечено 9 точек, делящих окружность на 9 равных дуг")
  196.     print("- Петя и Вася по очереди окрашивают точки в красный (R) или синий (B) цвет")
  197.     print("- Первым ходит Петя, который может окрасить любую точку")
  198.     print("- Далее можно окрашивать только неокрашенные точки, соседние с уже окрашенными")
  199.     print("- Вася выигрывает, если после окрашивания всех точек найдётся равносторонний")
  200.     print("  треугольник, все вершины которого окрашены в один цвет")
  201.     print("- В окружности с 9 точками равносторонними треугольниками являются наборы точек:")
  202.     print("  (0,3,6), (1,4,7), (2,5,8)")
  203.    
  204.     game_mode = input("\nВыберите режим игры:\n1. Против компьютера (вы - Петя)\n2. Против компьютера (вы - Вася)\n3. Два игрока\nВыбор: ")
  205.    
  206.     player_vs_computer = True
  207.     player_is_petya = True
  208.    
  209.     if game_mode == "1":
  210.         player_vs_computer = True
  211.         player_is_petya = True
  212.     elif game_mode == "2":
  213.         player_vs_computer = True
  214.         player_is_petya = False
  215.     elif game_mode == "3":
  216.         player_vs_computer = False
  217.     else:
  218.         print("Неверный выбор. Выбран режим против компьютера (вы - Петя)")
  219.    
  220.     game = Game(player_vs_computer=player_vs_computer)
  221.    
  222.     while True:
  223.         game.display_board()
  224.        
  225.         game_over, winner = game.is_game_over()
  226.         if game_over:
  227.             print(f"\nИгра окончена! Победитель: {winner}")
  228.             triangles = game.check_equilateral_triangles()
  229.             if triangles:
  230.                 for triangle, color in triangles:
  231.                     print(f"Треугольник с вершинами {triangle} окрашен в {color} цвет")
  232.             break
  233.        
  234.         # Определяем, кто сейчас ходит - компьютер или игрок
  235.         computer_turn = (player_vs_computer and
  236.                         ((game.current_player == "Петя" and not player_is_petya) or
  237.                         (game.current_player == "Вася" and player_is_petya)))
  238.        
  239.         if computer_turn:
  240.             print("Компьютер думает...")
  241.             time.sleep(1)  # Небольшая задержка для эффекта "размышления"
  242.             success, message = game.computer_move()
  243.             print(message)
  244.         else:
  245.             # Ход игрока
  246.             available_moves = game.get_available_moves()
  247.             if not available_moves:
  248.                 print("Нет доступных ходов!")
  249.                 break
  250.            
  251.             try:
  252.                 point_index = int(input(f"{game.current_player}, выберите точку для окрашивания {available_moves}: "))
  253.                 if point_index not in available_moves:
  254.                     print("Недопустимый ход! Попробуйте снова.")
  255.                     continue
  256.                
  257.                 color = input("Выберите цвет (r - красный, b - синий): ").lower()
  258.                 if color == 'r':
  259.                     color = 'red'
  260.                 elif color == 'b':
  261.                     color = 'blue'
  262.                 else:
  263.                     print("Неверный цвет! Используйте 'r' для красного или 'b' для синего.")
  264.                     continue
  265.                
  266.                 success, message = game.make_move(point_index, color)
  267.                 if not success:
  268.                     print(message)
  269.             except ValueError:
  270.                 print("Пожалуйста, введите корректное число!")
  271.  
  272. if __name__ == "__main__":
  273.     play_game()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement