import random
from collections import Counter

print(
    """ __  ____   __ ____  _____  _____ 
 \ \/ /\ \ / // ___||_   _||  ___|
  \  /  \ V /| |      | |  | |_   
  /  \   | | | |___   | |  |  _|  
 /_/\_\  |_|  \____|  |_|  |_|    """
)
print()
print()
print(
    "Welcome to the XYCTF AI Match, where you will play against an AI designed by Adwa in a game of Rock, Paper, Scissors. You will play 100 games against it, and if you can win 100 games, you will be awarded a flag by Adwa."
)
print("You can input Rock、Paper or Scissors.")

rpsbox = {"Rock": 1, "Paper": 2, "Scissors": 3}
palyerinputs = []
count = 1
win = 0
flag = open("flag.txt", "r").read()


def find_keys(dictionary, value):
    for k, v in dictionary.items():
        if v == value:
            return k


def most_common_element(arr):
    counter = Counter(arr)
    most_common = counter.most_common(1)
    return most_common[0][0] if most_common else None


def rps(player, ai):
    result_matrix = [
        [0, -1, 1],
        [1, 0, -1],
        [-1, 1, 0],
    ]
    player_result = result_matrix[player - 1][ai - 1]

    if player_result == 0:
        return -1
    elif player_result == 1:
        return 0
    else:
        return 1


def random_ai(palyerinputs):
    seed = palyerinputs[:-1]
    if len(seed) == 0:
        return random.randint(1, 3)
    else:
        return (most_common_element(seed) - 2) % 3 + 1


while 1:
    if count == 1:
        print("Now, let's start the first round")
    else:
        print(f"Now, let's start the {count}th round")
    playerinput = input("> ")
    if playerinput not in rpsbox:
        print("Please enter Rock Paper scissors")
        continue
    player = rpsbox[playerinput]
    palyerinputs.append(player)
    aiinput = random_ai(palyerinputs)
    print(f"ai> {find_keys(rpsbox,aiinput)}")
    x = rps(player, aiinput)
    if x == 1:
        win += 1
        print("You win!")
    elif x == 0:
        print("You lost!")
    else:
        print("draw")
    count += 1
    if count > 100:
        break
if win == 100:
    print(flag)
