Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import time
- import os
- class Cup:
- """Класс для представления кружки"""
- def __init__(self, capacity, owner, index=0):
- self.capacity = capacity # Емкость кружки в мл
- self.owner = owner # Владелец кружки
- self.index = index # Индекс кружки у владельца (для множественных кружек)
- self.current_juice = None # Тип сока в кружке (None если пусто)
- def fill(self, juice_type):
- """Наполнить кружку соком определенного типа"""
- self.current_juice = juice_type
- return self.capacity
- def drink(self):
- """Выпить сок из кружки"""
- amount = self.capacity if self.current_juice else 0
- self.current_juice = None
- return amount
- def __str__(self):
- status = f"{self.current_juice} сок" if self.current_juice else "пусто"
- return f"Кружка {self.index+1} ({self.capacity} мл): {status}"
- class Player:
- """Базовый класс для представления игрока"""
- def __init__(self, name):
- self.name = name
- self.cups = []
- self.total_drunk = 0
- self.current_move_drunk = 0
- def add_cup(self, capacity):
- """Добавить кружку игроку"""
- cup = Cup(capacity, self, len(self.cups))
- self.cups.append(cup)
- return cup
- def can_make_move(self, cherry_juice, pear_juice):
- """Проверка возможности хода игрока"""
- for cup in self.cups:
- if cherry_juice >= cup.capacity or pear_juice >= cup.capacity:
- return True
- return False
- def make_move(self, cherry_juice, pear_juice):
- """Абстрактный метод хода игрока"""
- raise NotImplementedError("Этот метод должен быть переопределен в подклассах")
- def drink_all(self):
- """Выпить сок из всех кружек"""
- amount = 0
- for cup in self.cups:
- amount += cup.drink()
- self.total_drunk += amount
- self.current_move_drunk = amount
- return amount
- class HumanPlayer(Player):
- """Класс для представления игрока-человека"""
- def make_move(self, cherry_juice, pear_juice):
- """Ход игрока-человека"""
- print(f"\n{self.name}, ваш ход!")
- print(f"Доступно: {cherry_juice/1000:.2f} л вишневого сока и {pear_juice/1000:.2f} л грушевого сока")
- # Информация о кружках
- print("Ваши кружки:")
- for i, cup in enumerate(self.cups):
- print(f"{i+1}. Кружка {cup.capacity} мл")
- # Проверка возможности заполнить каждую кружку
- can_fill_cherry = [cup for cup in self.cups if cherry_juice >= cup.capacity]
- can_fill_pear = [cup for cup in self.cups if pear_juice >= cup.capacity]
- # Если нельзя заполнить ни одну кружку
- if not can_fill_cherry and not can_fill_pear:
- print("Вы не можете сделать ход! Недостаточно сока для заполнения кружек.")
- return 0, 0
- # Выбор типа сока
- juice_choice = None
- filled_cups = []
- # Заполняем все кружки одним типом сока
- while True:
- print("\nКаким соком вы хотите наполнить все свои кружки?")
- if can_fill_cherry:
- print("1. Вишневый сок")
- if can_fill_pear:
- print("2. Грушевый сок")
- try:
- choice = int(input("Ваш выбор (введите номер): "))
- if choice == 1 and can_fill_cherry:
- juice_choice = "вишневый"
- filled_cups = can_fill_cherry
- break
- elif choice == 2 and can_fill_pear:
- juice_choice = "грушевый"
- filled_cups = can_fill_pear
- break
- else:
- print("Некорректный выбор! Попробуйте снова.")
- except ValueError:
- print("Пожалуйста, введите число!")
- # Заполняем кружки и считаем использованный сок
- cherry_used = 0
- pear_used = 0
- print(f"\nВы наполняете все свои кружки {juice_choice} соком...")
- for cup in self.cups:
- if cup in filled_cups:
- if juice_choice == "вишневый":
- cherry_used += cup.fill("вишневый")
- else:
- pear_used += cup.fill("грушевый")
- print(f"Кружка {cup.index+1} ({cup.capacity} мл) наполнена {juice_choice} соком")
- else:
- print(f"Кружка {cup.index+1} ({cup.capacity} мл) не может быть наполнена - недостаточно сока")
- # Выпиваем сок
- print("\nВы выпиваете сок из всех наполненных кружек...")
- amount = self.drink_all()
- print(f"Вы выпили {amount/1000:.2f} л {juice_choice} сока")
- return cherry_used, pear_used
- class ComputerPlayer(Player):
- """Класс для представления компьютерного противника"""
- def __init__(self, name, difficulty="normal"):
- super().__init__(name)
- self.difficulty = difficulty # Сложность: 'easy', 'normal', 'hard'
- def make_move(self, cherry_juice, pear_juice):
- """Ход компьютерного противника"""
- print(f"\n{self.name} думает над ходом...")
- time.sleep(1) # Имитация размышления
- # Проверка возможности заполнить каждую кружку
- can_fill_cherry = [cup for cup in self.cups if cherry_juice >= cup.capacity]
- can_fill_pear = [cup for cup in self.cups if pear_juice >= cup.capacity]
- # Если нельзя заполнить ни одну кружку
- if not can_fill_cherry and not can_fill_pear:
- print(f"{self.name} не может сделать ход! Недостаточно сока для заполнения кружек.")
- return 0, 0
- juice_choice = None
- filled_cups = []
- # Выбор сока в зависимости от сложности
- if self.difficulty == "easy":
- # Случайный выбор
- options = []
- if can_fill_cherry:
- options.append(("вишневый", can_fill_cherry))
- if can_fill_pear:
- options.append(("грушевый", can_fill_pear))
- juice_choice, filled_cups = random.choice(options)
- elif self.difficulty == "normal":
- # Выбираем сок, которого больше
- if can_fill_cherry and can_fill_pear:
- if cherry_juice > pear_juice:
- juice_choice = "вишневый"
- filled_cups = can_fill_cherry
- else:
- juice_choice = "грушевый"
- filled_cups = can_fill_pear
- elif can_fill_cherry:
- juice_choice = "вишневый"
- filled_cups = can_fill_cherry
- else:
- juice_choice = "грушевый"
- filled_cups = can_fill_pear
- else: # hard
- # Выбираем сок, которого меньше (оптимальная стратегия)
- if can_fill_cherry and can_fill_pear:
- if cherry_juice < pear_juice:
- juice_choice = "вишневый"
- filled_cups = can_fill_cherry
- else:
- juice_choice = "грушевый"
- filled_cups = can_fill_pear
- elif can_fill_cherry:
- juice_choice = "вишневый"
- filled_cups = can_fill_cherry
- else:
- juice_choice = "грушевый"
- filled_cups = can_fill_pear
- # Заполняем кружки и считаем использованный сок
- cherry_used = 0
- pear_used = 0
- print(f"{self.name} наполняет все доступные кружки {juice_choice} соком...")
- for cup in self.cups:
- if cup in filled_cups:
- if juice_choice == "вишневый":
- cherry_used += cup.fill("вишневый")
- else:
- pear_used += cup.fill("грушевый")
- print(f"Кружка {cup.index+1} ({cup.capacity} мл) наполнена {juice_choice} соком")
- # Выпиваем сок
- print(f"{self.name} выпивает сок из всех наполненных кружек...")
- amount = self.drink_all()
- print(f"{self.name} выпил(а) {amount/1000:.2f} л {juice_choice} сока")
- return cherry_used, pear_used
- class JuiceGame:
- """Основной класс игры"""
- def __init__(self):
- self.players = []
- self.cherry_juice = 24000 # 24 литра в мл
- self.pear_juice = 24000 # 24 литра в мл
- self.current_player_idx = 0
- self.game_over = False
- self.winner = None
- def clear_screen(self):
- """Очистка экрана для лучшего отображения"""
- os.system('cls' if os.name == 'nt' else 'clear')
- def setup_game(self):
- """Настройка игры: создание игроков и кружек"""
- self.clear_screen()
- print("=== СОКОВАЯ СТРАТЕГИЯ ===")
- print("Добро пожаловать в игру 'Соковая Стратегия'!")
- print("В этой игре вы будете соревноваться, кто выпьет больше сока.")
- print("У нас есть 24 литра вишневого и 24 литра грушевого сока.")
- # Выбор режима игры
- while True:
- print("\nВыберите режим игры:")
- print("1. Игрок против компьютера")
- print("2. Два игрока")
- print("3. Компьютер против компьютера (демонстрация)")
- try:
- mode = int(input("Ваш выбор (введите номер): "))
- if mode in [1, 2, 3]:
- break
- else:
- print("Некорректный выбор! Попробуйте снова.")
- except ValueError:
- print("Пожалуйста, введите число!")
- # Настройка игроков в зависимости от режима
- if mode == 1:
- # Создаем игрока
- player_name = input("\nВведите ваше имя: ")
- player = HumanPlayer(player_name)
- self.players.append(player)
- # Выбор сложности компьютера
- while True:
- print("\nВыберите сложность компьютерного противника:")
- print("1. Легкий")
- print("2. Средний")
- print("3. Сложный")
- try:
- difficulty = int(input("Ваш выбор (введите номер): "))
- if difficulty == 1:
- comp_difficulty = "easy"
- break
- elif difficulty == 2:
- comp_difficulty = "normal"
- break
- elif difficulty == 3:
- comp_difficulty = "hard"
- break
- else:
- print("Некорректный выбор! Попробуйте снова.")
- except ValueError:
- print("Пожалуйста, введите число!")
- # Создаем компьютерного противника
- computer = ComputerPlayer("Компьютер", comp_difficulty)
- self.players.append(computer)
- elif mode == 2:
- # Создаем двух игроков
- player1_name = input("\nВведите имя первого игрока: ")
- player1 = HumanPlayer(player1_name)
- self.players.append(player1)
- player2_name = input("Введите имя второго игрока: ")
- player2 = HumanPlayer(player2_name)
- self.players.append(player2)
- else: # mode == 3
- # Создаем двух компьютерных игроков
- computer1 = ComputerPlayer("Компьютер 1", "hard")
- self.players.append(computer1)
- computer2 = ComputerPlayer("Компьютер 2", "hard")
- self.players.append(computer2)
- # Настройка кружек (по условию задачи)
- print("\nНастройка кружек...")
- # Для дяди Андрея (первого игрока)
- self.players[0].add_cup(500)
- print(f"{self.players[0].name} получает кружку объемом 500 мл")
- # Для Маши (второго игрока)
- self.players[1].add_cup(240)
- self.players[1].add_cup(240)
- print(f"{self.players[1].name} получает две кружки по 240 мл")
- # Кто ходит первым
- if mode != 3: # Если не компьютер против компьютера
- while True:
- print("\nКто ходит первым?")
- print(f"1. {self.players[0].name}")
- print(f"2. {self.players[1].name}")
- try:
- first = int(input("Ваш выбор (введите номер): "))
- if first in [1, 2]:
- self.current_player_idx = first - 1
- break
- else:
- print("Некорректный выбор! Попробуйте снова.")
- except ValueError:
- print("Пожалуйста, введите число!")
- print("\nИгра настроена! Нажмите Enter, чтобы начать...")
- input()
- def play_turn(self):
- """Выполнение одного хода игры"""
- current_player = self.players[self.current_player_idx]
- # Проверяем, может ли текущий игрок сделать ход
- if not current_player.can_make_move(self.cherry_juice, self.pear_juice):
- print(f"\n{current_player.name} не может сделать ход. Переход хода.")
- self.current_player_idx = (self.current_player_idx + 1) % len(self.players)
- # Проверяем, может ли следующий игрок сделать ход
- next_player = self.players[self.current_player_idx]
- if not next_player.can_make_move(self.cherry_juice, self.pear_juice):
- print("Ни один из игроков не может сделать ход. Игра окончена!")
- self.game_over = True
- return
- return
- # Выполняем ход текущего игрока
- cherry_used, pear_used = current_player.make_move(self.cherry_juice, self.pear_juice)
- # Обновляем запасы сока
- self.cherry_juice -= cherry_used
- self.pear_juice -= pear_used
- # Переход к следующему игроку
- self.current_player_idx = (self.current_player_idx + 1) % len(self.players)
- def show_game_state(self):
- """Отображение текущего состояния игры"""
- print("\n=== ТЕКУЩЕЕ СОСТОЯНИЕ ИГРЫ ===")
- print(f"Осталось вишневого сока: {self.cherry_juice/1000:.2f} л")
- print(f"Осталось грушевого сока: {self.pear_juice/1000:.2f} л")
- print("\nСтатистика игроков:")
- for player in self.players:
- print(f"{player.name}: выпито {player.total_drunk/1000:.2f} л сока")
- # Если это был последний ход этого игрока
- if player.current_move_drunk > 0:
- print(f" Последний ход: +{player.current_move_drunk/1000:.2f} л")
- player.current_move_drunk = 0 # Сбрасываем счетчик
- def determine_winner(self):
- """Определение победителя игры"""
- if len(self.players) == 1:
- return self.players[0]
- max_drunk = max(player.total_drunk for player in self.players)
- winners = [player for player in self.players if player.total_drunk == max_drunk]
- if len(winners) == 1:
- return winners[0]
- else:
- return None # Ничья
- def show_results(self):
- """Отображение результатов игры"""
- print("\n=== РЕЗУЛЬТАТЫ ИГРЫ ===")
- for player in self.players:
- print(f"{player.name} выпил(а) {player.total_drunk/1000:.2f} л сока")
- winner = self.determine_winner()
- if winner:
- print(f"\nПобедитель: {winner.name}! Поздравляем!")
- else:
- print("\nНичья! Все игроки выпили одинаковое количество сока.")
- # Отображение оставшегося сока
- print(f"\nОсталось вишневого сока: {self.cherry_juice/1000:.2f} л")
- print(f"Осталось грушевого сока: {self.pear_juice/1000:.2f} л")
- def run(self):
- """Запуск и выполнение игры"""
- self.setup_game()
- while not self.game_over:
- self.clear_screen()
- self.show_game_state()
- self.play_turn()
- if not self.game_over:
- input("\nНажмите Enter для следующего хода...")
- self.show_results()
- print("\nСпасибо за игру!")
- # Запуск игры
- if __name__ == "__main__":
- game = JuiceGame()
- game.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement