Advertisement
Hasli4

Untitled

Mar 21st, 2025
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.93 KB | None | 0 0
  1. import random
  2. import time
  3. import os
  4.  
  5. class Cup:
  6.     """Класс для представления кружки"""
  7.     def __init__(self, capacity, owner, index=0):
  8.         self.capacity = capacity  # Емкость кружки в мл
  9.         self.owner = owner  # Владелец кружки
  10.         self.index = index  # Индекс кружки у владельца (для множественных кружек)
  11.         self.current_juice = None  # Тип сока в кружке (None если пусто)
  12.    
  13.     def fill(self, juice_type):
  14.         """Наполнить кружку соком определенного типа"""
  15.         self.current_juice = juice_type
  16.         return self.capacity
  17.    
  18.     def drink(self):
  19.         """Выпить сок из кружки"""
  20.         amount = self.capacity if self.current_juice else 0
  21.         self.current_juice = None
  22.         return amount
  23.    
  24.     def __str__(self):
  25.         status = f"{self.current_juice} сок" if self.current_juice else "пусто"
  26.         return f"Кружка {self.index+1} ({self.capacity} мл): {status}"
  27.  
  28.  
  29. class Player:
  30.     """Базовый класс для представления игрока"""
  31.     def __init__(self, name):
  32.         self.name = name
  33.         self.cups = []
  34.         self.total_drunk = 0
  35.         self.current_move_drunk = 0
  36.    
  37.     def add_cup(self, capacity):
  38.         """Добавить кружку игроку"""
  39.         cup = Cup(capacity, self, len(self.cups))
  40.         self.cups.append(cup)
  41.         return cup
  42.    
  43.     def can_make_move(self, cherry_juice, pear_juice):
  44.         """Проверка возможности хода игрока"""
  45.         for cup in self.cups:
  46.             if cherry_juice >= cup.capacity or pear_juice >= cup.capacity:
  47.                 return True
  48.         return False
  49.    
  50.     def make_move(self, cherry_juice, pear_juice):
  51.         """Абстрактный метод хода игрока"""
  52.         raise NotImplementedError("Этот метод должен быть переопределен в подклассах")
  53.    
  54.     def drink_all(self):
  55.         """Выпить сок из всех кружек"""
  56.         amount = 0
  57.         for cup in self.cups:
  58.             amount += cup.drink()
  59.         self.total_drunk += amount
  60.         self.current_move_drunk = amount
  61.         return amount
  62.  
  63.  
  64. class HumanPlayer(Player):
  65.     """Класс для представления игрока-человека"""
  66.     def make_move(self, cherry_juice, pear_juice):
  67.         """Ход игрока-человека"""
  68.         print(f"\n{self.name}, ваш ход!")
  69.         print(f"Доступно: {cherry_juice/1000:.2f} л вишневого сока и {pear_juice/1000:.2f} л грушевого сока")
  70.        
  71.         # Информация о кружках
  72.         print("Ваши кружки:")
  73.         for i, cup in enumerate(self.cups):
  74.             print(f"{i+1}. Кружка {cup.capacity} мл")
  75.        
  76.         # Проверка возможности заполнить каждую кружку
  77.         can_fill_cherry = [cup for cup in self.cups if cherry_juice >= cup.capacity]
  78.         can_fill_pear = [cup for cup in self.cups if pear_juice >= cup.capacity]
  79.        
  80.         # Если нельзя заполнить ни одну кружку
  81.         if not can_fill_cherry and not can_fill_pear:
  82.             print("Вы не можете сделать ход! Недостаточно сока для заполнения кружек.")
  83.             return 0, 0
  84.        
  85.         # Выбор типа сока
  86.         juice_choice = None
  87.         filled_cups = []
  88.        
  89.         # Заполняем все кружки одним типом сока
  90.         while True:
  91.             print("\nКаким соком вы хотите наполнить все свои кружки?")
  92.            
  93.             if can_fill_cherry:
  94.                 print("1. Вишневый сок")
  95.             if can_fill_pear:
  96.                 print("2. Грушевый сок")
  97.            
  98.             try:
  99.                 choice = int(input("Ваш выбор (введите номер): "))
  100.                 if choice == 1 and can_fill_cherry:
  101.                     juice_choice = "вишневый"
  102.                     filled_cups = can_fill_cherry
  103.                     break
  104.                 elif choice == 2 and can_fill_pear:
  105.                     juice_choice = "грушевый"
  106.                     filled_cups = can_fill_pear
  107.                     break
  108.                 else:
  109.                     print("Некорректный выбор! Попробуйте снова.")
  110.             except ValueError:
  111.                 print("Пожалуйста, введите число!")
  112.        
  113.         # Заполняем кружки и считаем использованный сок
  114.         cherry_used = 0
  115.         pear_used = 0
  116.        
  117.         print(f"\nВы наполняете все свои кружки {juice_choice} соком...")
  118.         for cup in self.cups:
  119.             if cup in filled_cups:
  120.                 if juice_choice == "вишневый":
  121.                     cherry_used += cup.fill("вишневый")
  122.                 else:
  123.                     pear_used += cup.fill("грушевый")
  124.                 print(f"Кружка {cup.index+1} ({cup.capacity} мл) наполнена {juice_choice} соком")
  125.             else:
  126.                 print(f"Кружка {cup.index+1} ({cup.capacity} мл) не может быть наполнена - недостаточно сока")
  127.        
  128.         # Выпиваем сок
  129.         print("\nВы выпиваете сок из всех наполненных кружек...")
  130.         amount = self.drink_all()
  131.         print(f"Вы выпили {amount/1000:.2f} л {juice_choice} сока")
  132.        
  133.         return cherry_used, pear_used
  134.  
  135.  
  136. class ComputerPlayer(Player):
  137.     """Класс для представления компьютерного противника"""
  138.     def __init__(self, name, difficulty="normal"):
  139.         super().__init__(name)
  140.         self.difficulty = difficulty  # Сложность: 'easy', 'normal', 'hard'
  141.    
  142.     def make_move(self, cherry_juice, pear_juice):
  143.         """Ход компьютерного противника"""
  144.         print(f"\n{self.name} думает над ходом...")
  145.         time.sleep(1)  # Имитация размышления
  146.        
  147.         # Проверка возможности заполнить каждую кружку
  148.         can_fill_cherry = [cup for cup in self.cups if cherry_juice >= cup.capacity]
  149.         can_fill_pear = [cup for cup in self.cups if pear_juice >= cup.capacity]
  150.        
  151.         # Если нельзя заполнить ни одну кружку
  152.         if not can_fill_cherry and not can_fill_pear:
  153.             print(f"{self.name} не может сделать ход! Недостаточно сока для заполнения кружек.")
  154.             return 0, 0
  155.        
  156.         juice_choice = None
  157.         filled_cups = []
  158.        
  159.         # Выбор сока в зависимости от сложности
  160.         if self.difficulty == "easy":
  161.             # Случайный выбор
  162.             options = []
  163.             if can_fill_cherry:
  164.                 options.append(("вишневый", can_fill_cherry))
  165.             if can_fill_pear:
  166.                 options.append(("грушевый", can_fill_pear))
  167.             juice_choice, filled_cups = random.choice(options)
  168.            
  169.         elif self.difficulty == "normal":
  170.             # Выбираем сок, которого больше
  171.             if can_fill_cherry and can_fill_pear:
  172.                 if cherry_juice > pear_juice:
  173.                     juice_choice = "вишневый"
  174.                     filled_cups = can_fill_cherry
  175.                 else:
  176.                     juice_choice = "грушевый"
  177.                     filled_cups = can_fill_pear
  178.             elif can_fill_cherry:
  179.                 juice_choice = "вишневый"
  180.                 filled_cups = can_fill_cherry
  181.             else:
  182.                 juice_choice = "грушевый"
  183.                 filled_cups = can_fill_pear
  184.                
  185.         else:  # hard
  186.             # Выбираем сок, которого меньше (оптимальная стратегия)
  187.             if can_fill_cherry and can_fill_pear:
  188.                 if cherry_juice < pear_juice:
  189.                     juice_choice = "вишневый"
  190.                     filled_cups = can_fill_cherry
  191.                 else:
  192.                     juice_choice = "грушевый"
  193.                     filled_cups = can_fill_pear
  194.             elif can_fill_cherry:
  195.                 juice_choice = "вишневый"
  196.                 filled_cups = can_fill_cherry
  197.             else:
  198.                 juice_choice = "грушевый"
  199.                 filled_cups = can_fill_pear
  200.        
  201.         # Заполняем кружки и считаем использованный сок
  202.         cherry_used = 0
  203.         pear_used = 0
  204.        
  205.         print(f"{self.name} наполняет все доступные кружки {juice_choice} соком...")
  206.         for cup in self.cups:
  207.             if cup in filled_cups:
  208.                 if juice_choice == "вишневый":
  209.                     cherry_used += cup.fill("вишневый")
  210.                 else:
  211.                     pear_used += cup.fill("грушевый")
  212.                 print(f"Кружка {cup.index+1} ({cup.capacity} мл) наполнена {juice_choice} соком")
  213.        
  214.         # Выпиваем сок
  215.         print(f"{self.name} выпивает сок из всех наполненных кружек...")
  216.         amount = self.drink_all()
  217.         print(f"{self.name} выпил(а) {amount/1000:.2f} л {juice_choice} сока")
  218.        
  219.         return cherry_used, pear_used
  220.  
  221.  
  222. class JuiceGame:
  223.     """Основной класс игры"""
  224.     def __init__(self):
  225.         self.players = []
  226.         self.cherry_juice = 24000  # 24 литра в мл
  227.         self.pear_juice = 24000    # 24 литра в мл
  228.         self.current_player_idx = 0
  229.         self.game_over = False
  230.         self.winner = None
  231.    
  232.     def clear_screen(self):
  233.         """Очистка экрана для лучшего отображения"""
  234.         os.system('cls' if os.name == 'nt' else 'clear')
  235.    
  236.     def setup_game(self):
  237.         """Настройка игры: создание игроков и кружек"""
  238.         self.clear_screen()
  239.         print("=== СОКОВАЯ СТРАТЕГИЯ ===")
  240.         print("Добро пожаловать в игру 'Соковая Стратегия'!")
  241.         print("В этой игре вы будете соревноваться, кто выпьет больше сока.")
  242.         print("У нас есть 24 литра вишневого и 24 литра грушевого сока.")
  243.        
  244.         # Выбор режима игры
  245.         while True:
  246.             print("\nВыберите режим игры:")
  247.             print("1. Игрок против компьютера")
  248.             print("2. Два игрока")
  249.             print("3. Компьютер против компьютера (демонстрация)")
  250.            
  251.             try:
  252.                 mode = int(input("Ваш выбор (введите номер): "))
  253.                 if mode in [1, 2, 3]:
  254.                     break
  255.                 else:
  256.                     print("Некорректный выбор! Попробуйте снова.")
  257.             except ValueError:
  258.                 print("Пожалуйста, введите число!")
  259.        
  260.         # Настройка игроков в зависимости от режима
  261.         if mode == 1:
  262.             # Создаем игрока
  263.             player_name = input("\nВведите ваше имя: ")
  264.             player = HumanPlayer(player_name)
  265.             self.players.append(player)
  266.            
  267.             # Выбор сложности компьютера
  268.             while True:
  269.                 print("\nВыберите сложность компьютерного противника:")
  270.                 print("1. Легкий")
  271.                 print("2. Средний")
  272.                 print("3. Сложный")
  273.                
  274.                 try:
  275.                     difficulty = int(input("Ваш выбор (введите номер): "))
  276.                     if difficulty == 1:
  277.                         comp_difficulty = "easy"
  278.                         break
  279.                     elif difficulty == 2:
  280.                         comp_difficulty = "normal"
  281.                         break
  282.                     elif difficulty == 3:
  283.                         comp_difficulty = "hard"
  284.                         break
  285.                     else:
  286.                         print("Некорректный выбор! Попробуйте снова.")
  287.                 except ValueError:
  288.                     print("Пожалуйста, введите число!")
  289.            
  290.             # Создаем компьютерного противника
  291.             computer = ComputerPlayer("Компьютер", comp_difficulty)
  292.             self.players.append(computer)
  293.            
  294.         elif mode == 2:
  295.             # Создаем двух игроков
  296.             player1_name = input("\nВведите имя первого игрока: ")
  297.             player1 = HumanPlayer(player1_name)
  298.             self.players.append(player1)
  299.            
  300.             player2_name = input("Введите имя второго игрока: ")
  301.             player2 = HumanPlayer(player2_name)
  302.             self.players.append(player2)
  303.            
  304.         else:  # mode == 3
  305.             # Создаем двух компьютерных игроков
  306.             computer1 = ComputerPlayer("Компьютер 1", "hard")
  307.             self.players.append(computer1)
  308.            
  309.             computer2 = ComputerPlayer("Компьютер 2", "hard")
  310.             self.players.append(computer2)
  311.        
  312.         # Настройка кружек (по условию задачи)
  313.         print("\nНастройка кружек...")
  314.        
  315.         # Для дяди Андрея (первого игрока)
  316.         self.players[0].add_cup(500)
  317.         print(f"{self.players[0].name} получает кружку объемом 500 мл")
  318.        
  319.         # Для Маши (второго игрока)
  320.         self.players[1].add_cup(240)
  321.         self.players[1].add_cup(240)
  322.         print(f"{self.players[1].name} получает две кружки по 240 мл")
  323.        
  324.         # Кто ходит первым
  325.         if mode != 3:  # Если не компьютер против компьютера
  326.             while True:
  327.                 print("\nКто ходит первым?")
  328.                 print(f"1. {self.players[0].name}")
  329.                 print(f"2. {self.players[1].name}")
  330.                
  331.                 try:
  332.                     first = int(input("Ваш выбор (введите номер): "))
  333.                     if first in [1, 2]:
  334.                         self.current_player_idx = first - 1
  335.                         break
  336.                     else:
  337.                         print("Некорректный выбор! Попробуйте снова.")
  338.                 except ValueError:
  339.                     print("Пожалуйста, введите число!")
  340.        
  341.         print("\nИгра настроена! Нажмите Enter, чтобы начать...")
  342.         input()
  343.    
  344.     def play_turn(self):
  345.         """Выполнение одного хода игры"""
  346.         current_player = self.players[self.current_player_idx]
  347.        
  348.         # Проверяем, может ли текущий игрок сделать ход
  349.         if not current_player.can_make_move(self.cherry_juice, self.pear_juice):
  350.             print(f"\n{current_player.name} не может сделать ход. Переход хода.")
  351.             self.current_player_idx = (self.current_player_idx + 1) % len(self.players)
  352.            
  353.             # Проверяем, может ли следующий игрок сделать ход
  354.             next_player = self.players[self.current_player_idx]
  355.             if not next_player.can_make_move(self.cherry_juice, self.pear_juice):
  356.                 print("Ни один из игроков не может сделать ход. Игра окончена!")
  357.                 self.game_over = True
  358.                 return
  359.            
  360.             return
  361.        
  362.         # Выполняем ход текущего игрока
  363.         cherry_used, pear_used = current_player.make_move(self.cherry_juice, self.pear_juice)
  364.        
  365.         # Обновляем запасы сока
  366.         self.cherry_juice -= cherry_used
  367.         self.pear_juice -= pear_used
  368.        
  369.         # Переход к следующему игроку
  370.         self.current_player_idx = (self.current_player_idx + 1) % len(self.players)
  371.    
  372.     def show_game_state(self):
  373.         """Отображение текущего состояния игры"""
  374.         print("\n=== ТЕКУЩЕЕ СОСТОЯНИЕ ИГРЫ ===")
  375.         print(f"Осталось вишневого сока: {self.cherry_juice/1000:.2f} л")
  376.         print(f"Осталось грушевого сока: {self.pear_juice/1000:.2f} л")
  377.        
  378.         print("\nСтатистика игроков:")
  379.         for player in self.players:
  380.             print(f"{player.name}: выпито {player.total_drunk/1000:.2f} л сока")
  381.            
  382.             # Если это был последний ход этого игрока
  383.             if player.current_move_drunk > 0:
  384.                 print(f"  Последний ход: +{player.current_move_drunk/1000:.2f} л")
  385.                 player.current_move_drunk = 0  # Сбрасываем счетчик
  386.    
  387.     def determine_winner(self):
  388.         """Определение победителя игры"""
  389.         if len(self.players) == 1:
  390.             return self.players[0]
  391.            
  392.         max_drunk = max(player.total_drunk for player in self.players)
  393.         winners = [player for player in self.players if player.total_drunk == max_drunk]
  394.        
  395.         if len(winners) == 1:
  396.             return winners[0]
  397.         else:
  398.             return None  # Ничья
  399.    
  400.     def show_results(self):
  401.         """Отображение результатов игры"""
  402.         print("\n=== РЕЗУЛЬТАТЫ ИГРЫ ===")
  403.        
  404.         for player in self.players:
  405.             print(f"{player.name} выпил(а) {player.total_drunk/1000:.2f} л сока")
  406.        
  407.         winner = self.determine_winner()
  408.         if winner:
  409.             print(f"\nПобедитель: {winner.name}! Поздравляем!")
  410.         else:
  411.             print("\nНичья! Все игроки выпили одинаковое количество сока.")
  412.        
  413.         # Отображение оставшегося сока
  414.         print(f"\nОсталось вишневого сока: {self.cherry_juice/1000:.2f} л")
  415.         print(f"Осталось грушевого сока: {self.pear_juice/1000:.2f} л")
  416.    
  417.     def run(self):
  418.         """Запуск и выполнение игры"""
  419.         self.setup_game()
  420.        
  421.         while not self.game_over:
  422.             self.clear_screen()
  423.             self.show_game_state()
  424.             self.play_turn()
  425.            
  426.             if not self.game_over:
  427.                 input("\nНажмите Enter для следующего хода...")
  428.        
  429.         self.show_results()
  430.         print("\nСпасибо за игру!")
  431.  
  432.  
  433. # Запуск игры
  434. if __name__ == "__main__":
  435.     game = JuiceGame()
  436.     game.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement