#!/usr/bin/env python3
# -*-coding:utf-8;-*-
"""
Детская игра в карточки
https://kmsvsr.ru/wp-admin/post.php?post=1558
"""

from random import randint, sample
from os import listdir

# класс игрока
class Player:
    """Участник игры"""
    def __init__(self, name):
        """Создание игрока"""
        self.name = name
        self.values = [0, 0, 0]
        self.score = 0
    def next_turn(self):
        """Следующий ход"""
        for value_pos in range(3):
            self.values[value_pos] = randint(1, 105)
    def get_values_string(self):
        """Вернуть значения через пробел"""
        return " ".join(
            list(
                map(str, self.values)
            )
        )

class HtmlPage:
    """Страница с игрой"""
    def __init__(self):
        """Подготовка к формированию"""
        self.content = ""
        self.card_images = list(listdir("./cards"))
    def clear(self):
        """Очистка содержимого страницы"""
        self.content = ""
    def update(self, game):
        """Обновление страницы"""
        with open("game.html", "w", encoding="utf-8") as page_file:
            self.content = """<!DOCTYPE>
    <html>
    <head>
      <title>Карточки</title>
      <!--meta http-equiv="content-type" content="text/html; charset=utf-8" /-->
      <meta http-equiv="Refresh" content="3" />
      <link rel="stylesheet" type="text/css" href="cards.css" />
    </head>
    <body>
      <div class='game'>
        """
            for player in game.players:
                self.content += f"""
          <div class='player'>
            <h2 class='name'>{player.name}</h2>
            <div class='score'>{player.score} очков</div>
            <div class='card'>
              <img src='cards/{sample(self.card_images, 1)[0]}'>
            </div>
            <div class='value value1'>{player.values[0]}</div>
            <div class='value value2'>{player.values[1]}</div>
            <div class='value value3'>{player.values[2]}</div>
          </div>
          """
            self.content += f"<div class='congrats'>Победитель - {game.last_winner}!</div>"
            self.content += "</div><!--game--></body></html>"
            page_file.write(self.content)

# игра
class Game:
    """Игра в карточки"""
    def __init__(self):
        """Подготовка к игре"""
        self.players = []
        self.last_winner = ""
    def get_last_winner(self):
        """Кто победил"""
        return self.last_winner
    def next_turn(self):
        """Следующий ход"""
        values = [[], [], []]
        for player in self.players:
            player.next_turn()
            print(f"Игрок {player.name}: {player.get_values_string()}")
            values[0].append(player.values[0])
            values[1].append(player.values[1])
            values[2].append(player.values[2])
        max_values = [
            max(values[0]),
            max(values[1]),
            max(values[2])
        ]
        max_value_wins = 0
        for player in self.players:
            player.value_wins = 0
            for value_pos, _ in enumerate(player.values):
                if player.values[value_pos] == max_values[value_pos]:
                    player.value_wins += 1
            if player.value_wins > max_value_wins:
                max_value_wins = player.value_wins
        self.last_winner = ""
        for player in self.players:
            if player.value_wins == max_value_wins:
                player.score += 1
                self.last_winner += player.name
        print(f"Победитель - {self.last_winner}!")
        print("Результаты:")
        for player in self.players:
            print(f"{player.name}: {player.score} очков")

print("Игра в карточки")
g = Game()
# сколько игроков?
num_players = int(input("сколько игроков? (2 - 4): "))
if 1 < num_players <= 4:
    # имена игроков
    for i in range(0, num_players):
        new_name = input(f"Введи имя игрока {i+1}: ")
        g.players.append(Player(new_name))
    while True:
        print("Играем дальше...")
        g.next_turn()
        h = HtmlPage()
        h.update(g)
        input()
print("до новых встреч и всё такое")
