import os
import random
import sys

# ANSI 색상 코드
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
RESET = "\033[0m"

# 카드 ASCII 아트
CARD_ART = {
    "Emperor": f"""{YELLOW}
 ┌─────────────────┐
 │E                │
 │  ♔♔♔♔♔♔♔♔♔     │
 │  ♔  EMPEROR  ♔  │
 │  ♔♔♔♔♔♔♔♔♔     │
 │                E│
 └─────────────────┘{RESET}""",
    "Slave": f"""{BLUE}
 ┌─────────────────┐
 │S                │
 │  ⚓⚓⚓⚓⚓⚓⚓⚓⚓     │
 │  ⚓  SLAVE    ⚓  │
 │  ⚓⚓⚓⚓⚓⚓⚓⚓⚓     │
 │                S│
 └─────────────────┘{RESET}""",
    "Citizen": f"""{GREEN}
 ┌─────────────────┐
 │C                │
 │  ☺☺☺☺☺☺☺☺☺      │
 │  ☺ CITIZEN   ☺  │
 │  ☺☺☺☺☺☺☺☺☺      │
 │                C│
 └─────────────────┘{RESET}"""
}

def clear_screen():
    os.system('clear')

def get_key():
    return sys.stdin.read(1)

def title_screen():
    clear_screen()
    print(f"{CYAN}========================{RESET}")
    print(f"{MAGENTA}        E 카드         {RESET}")
    print(f"{YELLOW}  제작자: songyc.eng{RESET}")
    print(f"{CYAN}========================{RESET}")
    print("엔터를 눌러 시작하세요")
    while True:
        if get_key() == '\n':
            break

def initialize_game():
    return {
        "player_money": 100,
        "computer_money": 100,
        "round": 1,
        "player_role": "Emperor",
        "computer_role": "Slave",
        "set_results": []
    }

def create_deck(role):
    if role == "Emperor":
        return ["Emperor"] + ["Citizen"] * 4
    elif role == "Slave":
        return ["Slave"] + ["Citizen"] * 4

def display_cards(cards, cursor_index):
    for i, card in enumerate(cards):
        if i == cursor_index:
            print(f"{RED}>{RESET} {CARD_ART[card]}")
        else:
            print(f"  {CARD_ART[card]}")

def compare_cards(player_card, computer_card):
    if player_card == "Emperor" and computer_card == "Citizen":
        return "Player"
    elif player_card == "Citizen" and computer_card == "Slave":
        return "Player"
    elif player_card == "Slave" and computer_card == "Emperor":
        return "Player"
    elif computer_card == "Emperor" and player_card == "Citizen":
        return "Computer"
    elif computer_card == "Citizen" and player_card == "Slave":
        return "Computer"
    elif computer_card == "Slave" and player_card == "Emperor":
        return "Computer"
    else:
        return "Draw"

def display_menu(cursor_index):
    options = ["게임 계속하기", "타이틀 화면으로 돌아가기", "게임 종료하기"]
    for i, option in enumerate(options):
        if i == cursor_index:
            print(f"{RED}> {option} <{RESET}")
        else:
            print(f"  {option}")

def menu():
    cursor_index = 0
    while True:
        clear_screen()
        print(f"{YELLOW}메뉴{RESET}")
        display_menu(cursor_index)
        key = get_key()
        if key == 'j' and cursor_index < 2:
            cursor_index += 1
        elif key == 'k' and cursor_index > 0:
            cursor_index -= 1
        elif key == '\n':
            return cursor_index

def play_round(game_state):
    player_deck = create_deck(game_state["player_role"])
    computer_deck = create_deck(game_state["computer_role"])
    cursor_index = 0

    while player_deck and computer_deck:
        clear_screen()
        print(f"{GREEN}플레이어 소지금: {game_state['player_money']} Ferica{RESET}")
        print(f"{RED}컴퓨터 소지금: {game_state['computer_money']} Ferica{RESET}")
        print(f"라운드: {game_state['round']}")
        print(f"플레이어 역할: {game_state['player_role']}")
        print(f"컴퓨터 역할: {game_state['computer_role']}")
        print(f"{YELLOW}당신의 카드:{RESET}")
        display_cards(player_deck, cursor_index)

        key = get_key()
        if key == 'j' and cursor_index < len(player_deck) - 1:
            cursor_index += 1
        elif key == 'k' and cursor_index > 0:
            cursor_index -= 1
        elif key == '\n':
            player_card = player_deck.pop(cursor_index)
            computer_card = random.choice(computer_deck)
            computer_deck.remove(computer_card)

            print(f"당신이 낸 카드: {CARD_ART[player_card]}")
            print(f"컴퓨터가 낸 카드: {CARD_ART[computer_card]}")

            result = compare_cards(player_card, computer_card)
            if result == "Player":
                print(f"{GREEN}당신이 이번 라운드에서 이겼습니다!{RESET}")
                game_state["player_money"] += game_state["bet"]
                game_state["computer_money"] -= game_state["bet"]
            elif result == "Computer":
                print(f"{RED}컴퓨터가 이번 라운드에서 이겼습니다!{RESET}")
                game_state["player_money"] -= game_state["bet"]
                game_state["computer_money"] += game_state["bet"]
            else:
                print(f"{YELLOW}무승부입니다!{RESET}")

            input("계속하려면 엔터를 누르세요...")
            if result != "Draw":
                return result
        elif key == 'm':
            menu_choice = menu()
            if menu_choice == 1:
                return "Title"
            elif menu_choice == 2:
                sys.exit()

    return "Draw"

def main():
    while True:
        title_screen()
        game_state = initialize_game()

        while game_state["round"] <= 10:
            clear_screen()
            print(f"{MAGENTA}라운드 {game_state['round']}{RESET}")
            try:
                game_state["bet"] = int(input("배팅 금액을 입력하세요: "))
                if game_state["bet"] <= 0 or game_state["bet"] > min(game_state["player_money"], game_state["computer_money"]):
                    raise ValueError
            except ValueError:
                print("잘못된 배팅입니다. 유효한 금액을 입력해주세요.")
                input("다시 시도하려면 엔터를 누르세요...")
                continue

            result = play_round(game_state)
            if result == "Title":
                break
            game_state["set_results"].append(result)

            if game_state["player_money"] <= 0:
                print(f"{RED}당신의 소지금이 모두 소진되었습니다. 게임 오버!{RESET}")
                break
            elif game_state["computer_money"] <= 0:
                print(f"{GREEN}컴퓨터의 소지금이 모두 소진되었습니다. 당신이 승리했습니다!{RESET}")
                break

            game_state["round"] += 1
            game_state["player_role"], game_state["computer_role"] = game_state["computer_role"], game_state["player_role"]

        if result != "Title":
            if game_state["round"] > 10:
                if game_state["player_money"] > game_state["computer_money"]:
                    print(f"{GREEN}당신이 게임에서 승리했습니다!{RESET}")
                elif game_state["player_money"] < game_state["computer_money"]:
                    print(f"{RED}컴퓨터가 게임에서 승리했습니다!{RESET}")
                else:
                    print(f"{YELLOW}게임이 무승부로 끝났습니다!{RESET}")

            print("\n세트 결과:")
            for i, result in enumerate(game_state["set_results"], 1):
                print(f"세트 {i}: {result}")

            input("타이틀 화면으로 돌아가려면 엔터를 누르세요...")

if __name__ == "__main__":
    main()
