# LICENCIATURA EM ENGENHARIA INFORMÁTICA
# MESTRADO integrado EM ENGENHARIA INFORMÁTICA

# Inteligência Artificial
# 2022/23

# Draft Ficha 1

# Biblioteca de tratamento de grafos necessária para desenhar graficamente o grafo
import networkx as nx
# Biblioteca de tratamento de grafos necessária para desenhar graficamente o grafo
import matplotlib.pyplot as plt

# biblioteca necessária para se poder utilizar o valor math.inf  (infinito)
import math

# Importar a classe nodo
from nodo import Node
from mapa import *
from vector import Vector

# Definição da classe grafo:
# Um grafo tem uma lista de nodos,
# um dicionário:  nome_nodo -> lista de tuplos (nome_nodo,peso)
# para representar as arestas
# uma flag para indicar se é direcionado ou não

class Graph:
    # Construtor da classe
    def __init__(self, directed=False):
        self.m_nodes = []   # lista de nodos do grafo
        self.m_directed = directed   # se o grafo é direcionado ou nao
        self.m_graph = {}  # dicionario para armazenar os nodos, arestas  e pesos

        self.debug = []

    ##############################
    # Escrever o grafo como string
    ##############################

    def __str__(self):
        out = ""
        for key in self.m_graph.keys():
            out = out + "node " + str(key) + ": " + \
                str(self.m_graph[key]) + "\n"
        return out

    #####################################
    # Adicionar aresta no grafo, com peso
    ####################################

    def addNode(self, node1,vector, tipo):
        # cria um objeto node  com o nome passado como parametro
        n1 = Node(node1,vector, tipo)

        if (n1 not in self.m_nodes):
            self.m_nodes.append(n1)
            self.m_graph[vector] = set()
        return n1

    def addEdge(self, node1, node2, weight):  # node1 e node2 são os 'nomes' de cada nodo
        if not node2 in self.m_graph[node1]:
            self.m_graph[node1].add((node2, weight))

        # se o grafo for nao direcionado, colocar a aresta inversa
        if not self.m_directed:
            self.m_graph[node2].add((node1, weight))

    ################################
    # Encontrar nodo pelo nome
    ################################
    def get_node_by_name(self, name):
        search_node = Node(name)
        for node in self.m_nodes:
            if node == search_node:
                return node
        return None

    def get_node_by_vector(self, vector):

        name = str((vector.x,vector.y))
        search_node = Node(name)
        for node in self.m_nodes:
            if node == search_node:
                return node
        return None

    def vector_exists(self, vector):

        name = str((vector.x,vector.y))
        search_node = Node(name)
        for node in self.m_nodes:
            if node == search_node:
                return 1
        return 0

    ###########################
    # Imprimir arestas
    ###########################

    def imprime_aresta(self):
        listaA = ""
        for nodo in self.m_graph.keys():
            for (nodo2, custo) in self.m_graph[nodo]:
                listaA = listaA + nodo + " ->" + \
                    nodo2 + " custo:" + str(custo) + "\n"
        return listaA

    ################################
    # Devolver o custo de uma aresta
    ################################
    def get_arc_cost(self, node1, node2):
        custoT = math.inf
        a = self.m_graph[node1]    # lista de arestas para aquele nodo
        for (nodo, custo) in a:
            if nodo == node2:
                custoT = custo

        return custoT

    ######################################
    # Dado um caminho calcula o seu custo
    #####################################

    def calcula_custo(self, caminho):
        """Dado um caminho calcula o seu custo
        Um caminho é uma lista de nomes de nodos"""
        teste = caminho
        custo = 0
        i = 0
        while i+1 < len(teste):
            custo = custo + self.get_arc_cost(teste[i], teste[i+1])
            i = i+1
        return custo

    def desenha(self):
        """Desenha grafo modo grafico"""

        # criar lista de vertices
        lista_v = self.m_nodes
        lista_a = []
        g = nx.Graph()

        # Converter para o formato usado pela biblioteca networkx
        for nodo in lista_v:
            n = nodo.getName()
            g.add_node(nodo.vector)
            for (adjacente, peso) in self.m_graph[nodo.vector]:
                lista = (nodo.vector, adjacente)
                # lista_a.append(lista)
                g.add_edge(nodo.vector, adjacente, weight=peso)

        # desenhar o grafo
        pos = nx.spring_layout(g)
        nx.draw_networkx(g, pos, with_labels=True, font_weight='bold')
        labels = nx.get_edge_attributes(g, 'weight')
        nx.draw_networkx_edge_labels(g, pos, edge_labels=labels)

        plt.draw()
        plt.show()

    def dist(self, x0, y0, x1, y1):
        a = (x1 - x0)**2 + (y1 - y0)**2
        b = math.sqrt(a)
        return b

    def distnodos(self, node1, node2):
        tuplo1 = node1.nodetotuple()
        tuplo2 = node2.nodetotuple()
        r = self.dist(tuplo1[0], tuplo1[1], tuplo2[0], tuplo2[1])
        return r

    def createGraphCartesian(self, mapa):

        # comeca por criar o nodo para a posicao (0,0)
        self.addNode(str((0,0)),Vector(0,0), 0)

        # para cada celula do mapa vamos:
        for line in range(mapa.lines):
            for row in range(mapa.rows):

                # checar todas as celulas a volta
                for i in range(3):
                    for j in range(3):

                        if not ((i == 1 and j == 1) or # nao criar aresta para a propria celula
                                (i == 0 and j == 0) or # nem nas celulas diagonais
                                (i == 0 and j == 2) or
                                (i == 2 and j == 0) or
                                (i == 2 and j == 2)):

                            x = i-1+row  # coordenada x do nodo a tentar criar
                            y = j-1+line # coordenada y do nodo a tentar criar

                            search = (x, y)

                            # se o nodo estiver dentro dos limites do mapa
                            if x > -1 and x < mapa.rows and y > -1 and y < mapa.lines:
                                celValue = mapa.getCelValue(search)
                                # se o valor relativo ao nodo no mapa for TRACK
                                if celValue == TRACK:
                                    self.addNode(str(search), Vector(x, y),TRACK)

                                # se o valor relativo ao nodo no mapa for WALL
                                if celValue == WALL:
                                    self.addNode(str(search), Vector(x, y) ,WALL)

                                # se o valor relativo ao nodo no mapa for START
                                if celValue == START:
                                    self.addNode(str(search), Vector(x, y),START)

                                # se o valor relativo ao nodo no mapa for FINISH
                                if celValue == FINISH:
                                    self.addNode(str(search), Vector(x, y),FINISH)

                                #DEPRECATED self.addEdge(str((row, line)),str(search), 1)
                                self.addEdge(Vector(row, line), Vector(x, y), 1)
    # deprecated
    # def createGraph1(self, mapa):
    #     (xstart, ystart) = mapa.start
    #     self.addNode(f"{mapa.start}", 0)
    #     self.addEdges(xstart, ystart, mapa)
#
    # # deprecated
    # def addEdges(self, xstart, ystart, mapa, visited=[], depth=0):
#
    #     nextNodes = []
    #     depth += 1
    #
    #     visited.append((xstart, ystart))
#
    #     for i in range(3):
    #         for j in range(3):
    #             if not (i == 1 and j == 1):  # nao quero procurar na propria celula
    #                 search = (i-1+xstart, j-1+ystart)
#
    #                 if search not in visited:
    #                     if mapa.getCelValue(search) == TRACK:
    #                         self.addNode(str(search), 0)
    #                         self.addEdge(str((xstart, ystart)), str(search), 1)
    #                         nextNodes.append(search)
#
    #                     if mapa.getCelValue(search) == WALL:
    #                         self.addNode(str(search), 0)
    #                         self.addEdge(str((xstart, ystart)),
    #                                      str(search), 25)
#
    #                     elif mapa.getCelValue(search) == FINISH:
    #                         self.addNode(str(search), 0)
    #                         self.addEdge(str((xstart, ystart)), str(search), 1)
#
    #     for (x, y) in nextNodes:
    #         self.addEdges(x, y, mapa, visited, depth)  # visited.copy(), depth)

    def checkPath(self, inicio, destino):
        custo = destino-inicio
        x = custo.x
        y = custo.y
        currentPosition = inicio

        while x != 0 or y != 0:
            lastPosition = currentPosition

            nodeType = self.get_node_by_vector(currentPosition).type
            if  nodeType == FINISH:
                return currentPosition, FINISH
            if  nodeType == WALL:
                return lastPosition, WALL

            if x > 0:
                x = x-1
                currentPosition += Vector(1,0)
            elif x < 0:
                x = x+1
                currentPosition += Vector(-1,0)
            if y > 0:
                y = y-1
                currentPosition += Vector(0,1)
            elif y < 0:
                y = y+1
                currentPosition += Vector(0,-1)
            nodeType = self.get_node_by_vector(currentPosition).type

            if  nodeType == FINISH:
                return currentPosition, FINISH
            if  nodeType == WALL:
                return lastPosition, WALL

        return currentPosition, TRACK


import streamlit as st  #importing libraries
import pickle
import time
model = pickle.load(open('RF_model.pkl','rb'))  #importing the model that was trained using Random forest algo

def main(): #defining main function
    string = "CAR PRICE PREDICTOR"
    st.set_page_config(page_title=string, page_icon="ðŸš—", layout = "wide") #setting configuration of web page
    st.title("Car Price Predictor")

    st.markdown(""" <style>
    #MainMenu {visibility: hidden;}        #For hiding the menu bar
    footer {visibility: hidden;}
    </style> """, unsafe_allow_html=True)

    padding = 0
    st.markdown(f""" <style>
    .reportview-container .main .block-container{{      #For condensing the page layout
        padding-top: {padding}rem;
        padding-right: {padding}rem;
        padding-left: {padding}rem;
        padding-bottom: {padding}rem;
    }} </style> """, unsafe_allow_html=True)

    st.markdown("##### This web application predicts the prices of cars based on your inputs. The model is trained using Random Forest algorithm.\n##### So let's try evaluating the price based on your inputs.")
    st.image(
            "https://media2.giphy.com/media/cWWwLuxISKDRMyuqGB/giphy.gif?cid=ecf05e47ar2uwxm3xvoc30ogvz4ks96bho6ksszjrjvhw2h8&rid=giphy.gif&ct=g",
            width=280, # Manually Adjust the width of the image as per requirement
               )
    st.write('')
    st.write('')
    with st.spinner('Prediction is being done!'):
        time.sleep(8)  # Loading spinner call so that user does not get bored
    power = st.number_input('The Engine Power ( in hp ):', 33,779, step = 4 , key = 'Power') #Taking numer input as power with upper and lower limit as 779 and 33 respectively
    displacement = st.number_input('The Engine Capacity ( in cc ):', 624 , 6752 , step = 8 , key = 'Displacement') #Taking displacement as input through number input with respective limits
    mileage = st.number_input('The mileage of car :', 3.4 , 28.4 , step = 0.5 , key = 'Mileage') #mileage as number input with respective limits
    airbags = st.radio("Number of airbags :",(0,1,2,3,4,5,6,7,8,9,10,14), key = 'Airbags') #number of airbags as radio input
    st.write('<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True) #For radio buttons to be horizontal
    seats = st.radio("Number of seats :",(2,4,5,6,7,8,9), key = 'Seats') #seats as radio input
    Manufacturer_Audi = st.selectbox('Which company do you want?', ('Tata', 'Datsun', 'Renault', 'Maruti Suzuki', 'Hyundai', 'Premier', 'Toyota',
                 'Nissan', 'Volkswagen', 'Ford', 'Mahindra', 'Fiat', 'Honda',
                 'Jeep' ,'Isuzu', 'Skoda', 'Audi', 'Dc', 'Mini',
                 'Jaguar', 'Bmw', 'Porsche', 'Lexus', 'Maserati','Lamborghini', 'Bentley',
                 'Ferrari', 'Force', 'Volvo' , 'Land Rover Rover' , 'Kia',
                 'Mitsubishi', 'Maruti Suzuki R', 'Land Rover','Aston Martin'), key = 'Manufacturer') #Taking input of company name

    dict_manufacturer = {'Tata' : 30, 'Datsun' : 3, 'Renault':28, 'Maruti Suzuki' : 20, 'Hyundai' : 10, 'Premier':27, 'Toyota' : 31,
                 'Nissan' : 25, 'Volkswagen':32, 'Ford' : 8, 'Mahindra' : 19, 'Fiat' : 6, 'Honda' : 9,
                 'Jeep' : 13,'Isuzu' : 11, 'Skoda' : 29, 'Audi': 0, 'Dc' : 4, 'Mini' : 23,
                 'Jaguar' : 12, 'Bmw' : 2, 'Porsche' : 26, 'Lexus':18, 'Maserati' : 22,'Lamborghini':15, 'Bentley' : 1,
                 'Ferrari' : 5, 'Force' : 7, 'Volvo' : 33 , 'Land Rover Rover' : 17 , 'Kia': 14,
                 'Mitsubishi' : 24, 'Maruti Suzuki R' : 21, 'Land Rover' : 16}   # I define a dictionary where company name is key and lexicographic order is value
                 #This dictionary would be furthur used.

    list_manufacturer = ['Manufacturer_Audi', 'Manufacturer_Bentley',
       'Manufacturer_Bmw', 'Manufacturer_Datsun', 'Manufacturer_Dc',
       'Manufacturer_Ferrari', 'Manufacturer_Fiat', 'Manufacturer_Force',
       'Manufacturer_Ford', 'Manufacturer_Honda', 'Manufacturer_Hyundai',
       'Manufacturer_Isuzu', 'Manufacturer_Jaguar', 'Manufacturer_Jeep',
       'Manufacturer_Kia', 'Manufacturer_Lamborghini',
       'Manufacturer_Land_Rover', 'Manufacturer_Land_Rover_Rover',
       'Manufacturer_Lexus', 'Manufacturer_Mahindra',
       'Manufacturer_Maruti_Suzuki', 'Manufacturer_Maruti_Suzuki_R',
       'Manufacturer_Maserati', 'Manufacturer_Mini',
       'Manufacturer_Mitsubishi', 'Manufacturer_Nissan',
       'Manufacturer_Porsche', 'Manufacturer_Premier',
       'Manufacturer_Renault', 'Manufacturer_Skoda', 'Manufacturer_Tata',
       'Manufacturer_Toyota', 'Manufacturer_Volkswagen',
       'Manufacturer_Volvo'] #A list of columns created by get_dummies function on our dataset. These will be n-1 where n be unique elements in that particular column

    list_feat = [] #Define an empty list
    if(Manufacturer_Audi != 'Aston Martin'): #Aston Martin does not get any dummy variable so exclusing it.
        if(Manufacturer_Audi):
            for i in range(34):
                if (dict_manufacturer[Manufacturer_Audi] != i): # When value from dictionary associated with input ( i.e. key ) then we append 1 to list.
                   list_feat.append(0)
                else:
                   list_feat.append(1)
        #For example, if user chooses car company as Mini, so value associated to Manufacturer Mini is 23.
        # So list_feat[23] = 1 and rest all would be zero
            Manufacturer_Audi = list_feat[0]      #Here I need to write all variables individually as they would input in model later
            Manufacturer_Bentley = list_feat[1]
            Manufacturer_Bmw = list_feat[2]
            Manufacturer_Datsun = list_feat[3]
            Manufacturer_Dc = list_feat[4]
            Manufacturer_Ferrari = list_feat[5]
            Manufacturer_Fiat = list_feat[6]
            Manufacturer_Force = list_feat[7]
            Manufacturer_Ford = list_feat[8]
            Manufacturer_Honda = list_feat[9]
            Manufacturer_Hyundai = list_feat[10]
            Manufacturer_Isuzu = list_feat[11]
            Manufacturer_Jaguar = list_feat[12]
            Manufacturer_Jeep = list_feat[13]
            Manufacturer_Kia = list_feat[14]
            Manufacturer_Lamborghini = list_feat[15]
            Manufacturer_Land_Rover = list_feat[16]
            Manufacturer_Land_Rover_Rover = list_feat[17]
            Manufacturer_Lexus = list_feat[18]
            Manufacturer_Mahindra = list_feat[19]
            Manufacturer_Maruti_Suzuki = list_feat[20]
            Manufacturer_Maruti_Suzuki_R = list_feat[21]
            Manufacturer_Maserati = list_feat[22]
            Manufacturer_Mini = list_feat[23]
            Manufacturer_Mitsubishi = list_feat[24]
            Manufacturer_Nissan = list_feat[25]
            Manufacturer_Porsche = list_feat[26]
            Manufacturer_Premier = list_feat[27]
            Manufacturer_Renault = list_feat[28]
            Manufacturer_Skoda = list_feat[29]
            Manufacturer_Tata = list_feat[30]
            Manufacturer_Toyota = list_feat[31]
            Manufacturer_Volkswagen = list_feat[32]
            Manufacturer_Volvo = list_feat[33]

    #If input is Aston Martin then all variables will be equal to 0
    elif(Manufacturer_Audi == 'Aston Martin'):
        Manufacturer_Audi = 0
        Manufacturer_Bentley = 0
        Manufacturer_Bmw = 0
        Manufacturer_Datsun = 0
        Manufacturer_Dc = 0
        Manufacturer_Ferrari = 0
        Manufacturer_Fiat = 0
        Manufacturer_Force = 0
        Manufacturer_Ford = 0
        Manufacturer_Honda = 0
        Manufacturer_Hyundai = 0
        Manufacturer_Isuzu = 0
        Manufacturer_Jaguar = 0
        Manufacturer_Jeep = 0
        Manufacturer_Kia = 0
        Manufacturer_Lamborghini = 0
        Manufacturer_Land_Rover = 0
        Manufacturer_Land_Rover_Rover = 0
        Manufacturer_Lexus = 0
        Manufacturer_Mahindra = 0
        Manufacturer_Maruti_Suzuki = 0
        Manufacturer_Maruti_Suzuki_R = 0
        Manufacturer_Maserati = 0
        Manufacturer_Mini = 0
        Manufacturer_Mitsubishi = 0
        Manufacturer_Nissan = 0
        Manufacturer_Porsche = 0
        Manufacturer_Premier = 0
        Manufacturer_Renault = 0
        Manufacturer_Skoda = 0
        Manufacturer_Tata = 0
        Manufacturer_Toyota = 0
        Manufacturer_Volkswagen = 0
        Manufacturer_Volvo = 0

    #Taking input of fuel type:
    #Defining these variables is necessary as i need to input these in model later
    Fuel_Type_Petrol = st.selectbox('What is the fuel type of the car ?',('Petrol','Diesel', 'Hybrid', 'CNG + Petrol'), key='Fuel_Type')
    if(Fuel_Type_Petrol=='Petrol'): #if selected is petrol then petrol type would be 1 and rest 0
        Fuel_Type_Petrol=1
        Fuel_Type_Diesel=0
        Fuel_Type_Hybrid=0
    elif(Fuel_Type_Petrol=='Diesel'): #if selected is diesel then diesel type would be 1 and rest 0
        Fuel_Type_Petrol=0
        Fuel_Type_Diesel=1
        Fuel_Type_Hybrid=0
    elif(Fuel_Type_Petrol=='Hybrid'): #if selected is hybrid then hybrid type would be 1 and rest 0
        Fuel_Type_Petrol=0
        Fuel_Type_Diesel=0
        Fuel_Type_Hybrid=1
    else:                    #if selected is CNG+Petrol then all would be 0
        Fuel_Type_Petrol=0
        Fuel_Type_Diesel=0
        Fuel_Type_Hybrid=0

    #Taking input of gear type:
    #Defining these variables is necessary as i need to input these in model later
    Gear_Type_Automatic = st.selectbox('What is gear type?',('Automatic','CVT','DCT','Manual','AMT'), key = 'Gear_Type')
    if(Gear_Type_Automatic=='Automatic'): #if selected is automatic then automatic type would be 1 and rest 0
        Gear_Type_Automatic=1
        Gear_Type_CVT = 0
        Gear_Type_DCT = 0
        Gear_Type_Manual=0
    elif(Gear_Type_Automatic=='CVT'): #if selected is CVT then CVT type would be 1 and rest 0
        Gear_Type_Automatic=0
        Gear_Type_CVT = 1
        Gear_Type_DCT = 0
        Gear_Type_Manual=0
    elif(Gear_Type_Automatic=='DCT'): #if selected is DCT then DCT Type would be 1 and rest 0
        Gear_Type_Automatic=0
        Gear_Type_CVT = 0
        Gear_Type_DCT = 1
        Gear_Type_Manual=0
    elif(Gear_Type_Automatic=='Manual'): #if selected is Manual then manual type would be 1 and rest 0
        Gear_Type_Automatic=0
        Gear_Type_CVT = 0
        Gear_Type_DCT = 0
        Gear_Type_Manual=1
    else: #if selected is AMT then all would be 0
        Gear_Type_Automatic=0
        Gear_Type_CVT = 0
        Gear_Type_DCT = 0
        Gear_Type_Manual=0

    #The logic behind these variable is same as earlier two inputs
    Drivetrain_AWD = st.selectbox('Select Drive Train:',('AWD (All Wheel Drive)','FWD (Front Wheel Drive)','RWD (Rear Wheel Drive)','4WD'), key = 'Drivetrain')
    if(Drivetrain_AWD == 'AWD (All Wheel Drive)'):
       Drivetrain_AWD = 1
       Drivetrain_FWD = 0
       Drivetrain_RWD = 0
    elif(Drivetrain_AWD == 'FWD (Front Wheel Drive)'):
       Drivetrain_AWD = 0
       Drivetrain_FWD = 1
       Drivetrain_RWD = 0
    elif(Drivetrain_AWD == 'RWD (Rear Wheel Drive)'):
       Drivetrain_AWD = 0
       Drivetrain_FWD = 0
       Drivetrain_RWD = 1
    else:
       Drivetrain_AWD = 0
       Drivetrain_FWD = 0
       Drivetrain_RWD = 0

    if st.button("Estimate Price", key = 'predict'): #If user presses estimate price
        Model = model #get_model
        #using predict() and giving all variables as input and store that in prediction named variable
        prediction = Model.predict([[power,displacement,airbags,seats,mileage,Manufacturer_Audi,Manufacturer_Bentley,Manufacturer_Bmw,Manufacturer_Datsun,Manufacturer_Dc,Manufacturer_Ferrari,Manufacturer_Fiat,
                                        Manufacturer_Force,Manufacturer_Ford,Manufacturer_Honda,Manufacturer_Hyundai,Manufacturer_Isuzu,Manufacturer_Jaguar,Manufacturer_Jeep, Manufacturer_Kia,Manufacturer_Lamborghini,
                                        Manufacturer_Land_Rover,Manufacturer_Land_Rover_Rover,Manufacturer_Lexus,Manufacturer_Mahindra,Manufacturer_Maruti_Suzuki, Manufacturer_Maruti_Suzuki_R, Manufacturer_Maserati,
                                        Manufacturer_Mini,Manufacturer_Mitsubishi,Manufacturer_Nissan,Manufacturer_Porsche, Manufacturer_Premier,Manufacturer_Renault,Manufacturer_Skoda,Manufacturer_Tata,Manufacturer_Toyota,
                                        Manufacturer_Volkswagen,Manufacturer_Volvo,Fuel_Type_Petrol,Fuel_Type_Diesel,Fuel_Type_Hybrid,Gear_Type_Automatic, Gear_Type_CVT,Gear_Type_DCT, Gear_Type_Manual,Drivetrain_AWD,Drivetrain_FWD,Drivetrain_RWD]])
        output = round(prediction[0],2) #Taking output as rounding off to 2 decimal places
        if output < 0: #there might be case where output is less than 0 so giving warning as
            st.warning("Price of car having such inputs can not be estimated !!")

        else: #otherwise show the estimated aprroximated price
            st.success("The price of such car would be roughly around â‚¹{} ".format(output))

        st.snow() #animated snow throughout the screen

if __name__ == '__main__': #calling main function
    main()


#space invader (ship and bullets)
import math
import pygame
import random
from pygame import mixer

#initializing pygame
pygame.init()

#change number of enemies
num_of_enemies = 50
#change player speed
step = 1.9

# score
score_value = 0
font = pygame.font.Font("assets//Sportive-Regular.ttf", 32)
font2 = pygame.font.Font("assets//font2.otf", 100)

#font size
TextX = 10
TextY = 10

#creating game window
screen_w = 800
screen_h = 600
screen = pygame.display.set_mode((screen_w,screen_h))

#change title
pygame.display.set_caption("Space Invaders")

#change icon
icon = pygame.image.load("assets//icon.png") #define icon
pygame.display.set_icon(icon)             #set the icon

#rocket icon from Flaticon by Freepik
#add player
PlayerImg = pygame.image.load("assets//rocket.png") #define player

#Load background image
bg = pygame.image.load("assets//bck.jpg")
#Load background music
mixer.music.load("assets//bck_music.mp3")
mixer.music.play(-1)

PlayerX = 370
PlayerY = 480
dead_or_alive = "alive"

#Load bullet image
bulletIMG = pygame.image.load("assets//bullet_24.png")

Bullet_X = PlayerX
Bullet_Y = PlayerY + 15
Bullet_speed = 0.5
bullet_state = "ready"
bullet_sound = mixer.Sound("assets//laser1.wav")
death_sound = mixer.Sound("assets//die.wav")

#ready means bullet is invisible
#fire means bullets are firing

enemy1 = pygame.image.load("assets//enemy1.png") #import enemy image
enemy2 = pygame.image.load("assets//enemy2.png") #import enemy image
enemy3 = pygame.image.load("assets//enemy3.png") #import enemy image

enemyimgs = [enemy1,enemy2,enemy3]
enemyIMG = []
enemy_states = []
enemy_X = []
enemy_Y =[]
enemy_X_change = []
enemy_Y_change = []

for i in range(num_of_enemies):
    enemyIMG.append(random.choice(enemyimgs))
    enemy_states.append("show")
    enemy_X.append(random.randint(40,screen_w))
    enemy_Y.append(random.randint(40,150))
    enemy_X_change.append(0.7)
    enemy_Y_change.append(random.randint(14,24))
stepX = 0
stepY = 0

def game_over(x,y):
    screen.fill((255,255,255,0.5)) #change background color - RGB
    game_o = font2.render("GAME OVER",True, (0, 0, 0))
    screen.blit(game_o, (x, y))

def show_score(x,y):
    score = font.render("Score : " + str(score_value),True, (255, 255, 255))
    screen.blit(score, (x, y))

def fire_bullet(x,y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletIMG, (x+32, y+10))
    screen.blit(bulletIMG, (x-16, y+10))

def player(x,y):
    screen.blit(PlayerImg,(x,y))

def enemy(Img, x,y):
    screen.blit(Img,(x,y))

def isCollision(x_e, y_e, x_b, y_b):
    distance = math.sqrt(math.pow(x_e-x_b,2) + math.pow(y_e-y_b,2))
    if distance < 20:
        return True
    else:
        return False
#closing window - add quit event
running = True

while running:

    #screen.fill((255,155,10)) #change background color - RGB
    #INSIDE OF THE GAME LOOP
    screen.blit(bg, (0, 0))

    for event in pygame.event.get():      #get all user events
        try:
            if event.type == pygame.QUIT:     # pressing the close button = Pygame.Quit
                running = False               #quit the window
                pygame.display.quit()
                pygame.quit()
                break
            #get keyboard input
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    stepY = -step
                if event.key == pygame.K_DOWN:
                    stepY = step
                if event.key == pygame.K_RIGHT:
                    stepX = step
                if event.key == pygame.K_LEFT:
                    stepX = -step
                if event.key == pygame.K_SPACE:
                    if bullet_state == "ready":
                        fire_bullet(Bullet_X, Bullet_Y)
            if event.type == pygame.KEYUP:
                if (event.key == pygame.K_UP or event.key == pygame.K_DOWN):
                    stepY = 0
                if (event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT):
                    stepX = 0
                if (event.key == pygame.K_SPACE):
                    bullet_state = "ready"

        except Exception as e:
            print(e)

    #anything that you want to stay inside thescreen need to be inside the while loop

    try:
        PlayerX += stepX
        PlayerY += stepY

        #keep the spaceship inside the screen
        if (PlayerX <= 0):             #left side
            PlayerX = 0
        elif (PlayerX >= screen_w-70): #right side
            PlayerX = screen_w-70

        if (PlayerY >= screen_h-70):   #bottom side
            PlayerY = screen_h-70

        if (PlayerY <= 10):            #up side
            PlayerY = 10

        #show player
        if dead_or_alive == "alive":
            player(PlayerX,PlayerY) #call it after fill because order matters
        else:
            game_over((screen_w/2)-120, (screen_h/2)-40)

        #collision
        for i in range(num_of_enemies):
            enemy_X[i] += enemy_X_change[i]
            if enemy_X[i] >= screen_w-70 or enemy_X[i] <= 30 :
                enemy_X_change[i] = -enemy_X_change[i]
                enemy_Y[i] += 20

            if enemy_states[i] == 'show':
                enemy(enemyIMG[i], enemy_X[i],enemy_Y[i])
            collision = isCollision(enemy_X[i], enemy_Y[i], Bullet_X, Bullet_Y)
            if collision:
                death_sound.play()
                Bullet_Y = PlayerY
                Bullet_X = PlayerX
                #bullet_state = "ready"
                enemy_states[i] = 'hide'
                enemy_Y[i] = 0
                enemy_X[i] = 0
                score_value += 400
            collision_p = isCollision(enemy_X[i], enemy_Y[i], PlayerX, PlayerY)
            if collision_p:
                death_sound.play()
                dead_or_alive = "dead"
                PlayerX = 370
                PlayerY = 480
                for j in range(num_of_enemies):
                    enemy_states[j] = 'hide'
        #making bullet ready for firing again
        if Bullet_Y <= 0:
            Bullet_Y = PlayerY + 15
            bullet_state == "ready"
            Bullet_X = PlayerX
        #bullet movement
        if bullet_state == "fire" :
            bullet_sound.play()
            fire_bullet(Bullet_X,Bullet_Y)
            Bullet_Y -= 40

        #show scare
        show_score(TextX, TextY)
        pygame.display.update()   #to update screen
    except Exception as e:
        print(e)


"""
Utility functions for integrating ODEs.

Author: Spencer M. Richards
        Autonomous Systems Lab (ASL), Stanford
        (GitHub: spenrich)
"""

from functools import partial

import jax
import jax.numpy as jnp
from jax.flatten_util import ravel_pytree

import numpy as np

@partial(jax.jit, static_argnums=(0,))
def rk38_step(func, h, x, t, *args):
    """Do a single step of the RK-38 integration scheme."""
    # RK38 Butcher tableau
    s = 4
    A = jnp.array([
        [0,    0, 0, 0],
        [1/3,  0, 0, 0],
        [-1/3, 1, 0, 0],
        [1,   -1, 1, 0],
    ])
    b = jnp.array([1/8, 3/8, 3/8, 1/8])
    c = jnp.array([0,   1/3, 2/3, 1])

    def scan_fun(carry, cut):
        i, ai, bi, ci = cut
        x, t, h, K, *args = carry
        ti = t + h*ci
        xi = x + h*(K.T @ ai)
        ki = func(xi, ti, *args)
        K = K.at[i].set(ki)
        carry = (x, t, h, K, *args)
        return carry, ki

    init_carry = (x, t, h, jnp.squeeze(jnp.zeros((s, x.size))), *args)
    carry, K = jax.lax.scan(scan_fun, init_carry, (jnp.arange(s), A, b, c))
    xf = x + h*(K.T @ b)
    return xf

@partial(jax.jit, static_argnums=(0,))
def _odeint_ckpt(func, x0, ts, *args):

    def scan_fun(carry, t1):
        x0, t0, *args = carry
        x1 = rk38_step(func, t1 - t0, x0, t0, *args)
        carry = (x1, t1, *args)
        return carry, x1

    ts = jnp.atleast_1d(ts)
    init_carry = (x0, ts[0], *args)  # dummy state at same time as `t0`
    carry, xs = jax.lax.scan(scan_fun, init_carry, ts)
    return xs

@partial(jax.jit, static_argnums=(0,))
def odeint_ckpt(func, x0, ts, *args):
    """Integrate an ODE forward in time."""
    flat_x0, unravel = ravel_pytree(x0)

    def flat_func(flat_x, t, *args):
        x = unravel(flat_x)
        dx = func(x, t, *args)
        flat_dx, _ = ravel_pytree(dx)
        return flat_dx

    # Solve in flat form
    flat_xs = _odeint_ckpt(flat_func, flat_x0, ts, *args)
    xs = jax.vmap(unravel)(flat_xs)
    return xs

@partial(jax.jit, static_argnums=(0, 2, 3, 4))
def odeint_fixed_step(func, x0, t0, t1, step_size, *args):
    """Integrate an ODE forward in time with a fixed step and end time."""
    # Use `numpy` for purely static operations on static arguments
    # (see: https://github.com/google/jax/issues/5208)
    num_steps = int(np.maximum(np.abs((t1 - t0)/step_size), 1))

    ts = jnp.linspace(t0, t1, num_steps + 1)
    xs = odeint_ckpt(func, x0, ts, *args)
    return xs, ts


class converter:
    def __init__(self) -> None:
        self.basicLen = 4
        self.underLine = 0
        self.lowOct = 0
        self.highOct = 0
        self.pound = 0
        self.map = {'1':'C', '2':'D', '3':'E', '4':'F', '5':'G', '6':'A', '7':'B'}

    def init(self):
        self.underLine = 0
        self.lowOct = 0
        self.highOct = 0

    def clearMark(self):
        self.lowOct = 0
        self.highOct = 0
        self.pound = 0

    def markAdd(self, c):
        if c == ',':
            self.lowOct += 1
        elif c == '\'':
            self.highOct += 1
        elif c == '(':
            self.underLine += 1
        elif c == ')':
            self.underLine -= 1
        elif c == '#':
            self.pound += 1

    def convert(self, data):
        ans = ""
        for each in data:
            if each == '-' or each == '0':
                ans += 'P4'
            elif each.isdigit():
                tone = 4 + self.highOct - self.lowOct
                if tone != 4:
                    ans += "O" + str(tone)
                ans += self.map[each]
                if self.pound:
                    ans += '#'
                if self.underLine != 0:
                    num = 4
                    for i in range(self.underLine):
                        num *= 2
                    ans += str(num)
                if tone != 4:
                    ans += "O4"

                self.clearMark()
            elif each == '|':
                ans += ' '
            else:
                self.markAdd(each)
        return ans

if __name__ == "__main__":
    worker = converter()
    while True:
        data = input()
        worker.init()
        qbCode = worker.convert(data)
        print(qbCode)


#!/usr/bin/env python3

#!/usr/bin/env python3

import json
from pathlib import Path
from itertools import chain
from sklearn.metrics import f1_score, precision_score, recall_score
import numpy as np
import random

def load_json(path: Path):
    with path.open() as f:
        return json.load(f)

def restruct_gold(g):
    out = {}
    for i in g:
        out[i["tatbestand"]] = i["begründung"]
    return out

files = list(
    zip(
        map(load_json, sorted(Path("computed/structure").glob("*.json"))),
        map(load_json, sorted(Path("computed/references").glob("*.json"))),
        map(restruct_gold, map(load_json, sorted(Path("gold").glob("*.json")))),
        map(lambda n: n.stem, sorted(Path("computed/structure").glob("*.json"))),
    )
)

random.seed(0)
files = random.choices(files, k=3)

METHODS = [
    {
        "name": "Jaccard-Index",
        "internal_name": "jaccard",
    },
    {
        "name": "Wortembedding",
        "internal_name": "word_embedding",
    },
    {
        "name": "Satzembedding",
        "internal_name": "sent_embedding",
    },
    {
        "name": "Levenshtein",
        "internal_name": "levenshtein",
    },
]

BEST_THRESH = {
    "word_embedding": [],
    "sent_embedding": [],
    "jaccard": [],
    "levenshtein": [],
}

for struct, refs, gold, id in files:
    print(id, struct["slug"])
    begr_sents = list(
        chain.from_iterable(
            map(
                lambda s: s["sentences"],
                chain.from_iterable(struct["tatbestand"].values()),
            )
        )
    )

    for metric in BEST_THRESH.keys():
        possible_thresholds = set()
        for sent in begr_sents:
            for k, v in gold.items():
                if k not in refs:
                    continue

                for i in refs[k][metric]:
                    if any(map(lambda j: i["text"] == j, v)):
                        if metric == "relation":
                            print(i)
                        possible_thresholds.add(i["score"])

            if sent not in refs:
                continue
        if metric == "relation":
            print(possible_thresholds)

        best_f1 = 0
        best_thresh = 0

        for threshold in possible_thresholds:
            method = []
            is_gold = []

            for sent in begr_sents:
                metric_r = refs[sent][metric] if sent in refs else []
                results = list(filter(lambda i: i["score"] > threshold, metric_r))

                if sent in gold:
                    for g in gold[sent]:
                        is_gold.append(True),
                        method.append(any(map(lambda i: i["text"] == g, results)))
                for r in results:
                    if sent in gold and not any(
                        map(lambda j: r["text"] == j, gold[sent])
                    ):
                        is_gold.append(False)
                        method.append(True)

            f1 = f1_score(is_gold, method, zero_division=0)
            if f1 > best_f1:
                best_f1 = f1
                best_thresh = threshold

        BEST_THRESH[metric].append(best_thresh)

table = r"""\begin{tabular}{ll} \toprule
    Methode & Grenzwert \\ \midrule
"""
for method in METHODS:
    metric = method["internal_name"]
    threshold = str(round(np.mean(BEST_THRESH[metric]), 3))

    table += (
        " " * 4 + method["name"] + " & "
        r"\(" + str(threshold).replace(".", "{,}") + r"\)" + r" \\" + "\n"
    )
table += r"\end{tabular}"

with (Path("plots") / f"thresholds.tex").open("w") as f:
    f.write(table)


from __future__ import print_function

import os
import sys
import glob

from numpy.distutils.core import setup
from numpy.distutils.extension import Extension
import numpy

#from pycurrents.setup_helper import write_hg_status
#write_hg_status()  #  give dir argument if/when we switch to "lib"

all_opt = "--all"
install_all = False
if all_opt in sys.argv:
    print("Installing all scripts")
    install_all = True
    sys.argv.remove(all_opt)
else:
    print("Installing only user scripts; use '--all' option for all scripts")

print("Possibly modified setup argument list is:\n  ", ' '.join(sys.argv[1:]))

ext_modules = []

packages = ['uhdas',
            'uhdas.uhdas',
            'uhdas.serial',
            'uhdas.system',
            ]

package_data = dict()

user_scripts = ['scripts/tk_terminal.py',
                'scripts/showlast.py',
                'scripts/hgsummary.py',
                'scripts/repo_status.py',
                ]

if install_all:
    script_files = glob.glob('scripts/*.py')
    scripts = []
    for fname in script_files:
        with open(fname, 'rt') as f:
            topline = f.readline()
        if "#!/usr/bin/env" in topline:
            scripts.append(fname)
else:
    scripts = user_scripts

print("Installing these scripts:\n  ", "\n   ".join(scripts))

setup(
      name = 'uhdas',
      packages=packages,
      package_dir={'uhdas':''},
      package_data=package_data,
      ext_modules = ext_modules,
      scripts=scripts,
)


##FROM
## https://www.kaggle.com/kentaroyoshioka47/cnn-with-batchnormalization-in-keras-94
##
##

# -*- coding: utf-8 -*-
import argparse
import math
import sys
import time
import copy

import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation, BatchNormalization, regularizers
from keras.layers.noise import GaussianNoise
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.utils.np_utils import to_categorical
K.set_image_dim_ordering('th')
print(K.image_data_format())

## required for efficient GPU use
import tensorflow as tf
from keras.backend import tensorflow_backend
config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))
session = tf.Session(config=config)
tensorflow_backend.set_session(session)
## required for efficient GPU use

import os
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import numpy as np # linear algebra

# define path to save model
model_path = './fm_cnn_BN.h5'
# prepare callbacks
callbacks = [
    EarlyStopping(
        monitor='val_acc',
        patience=10,
        mode='max',
        verbose=1),
    ModelCheckpoint(model_path,
        monitor='val_acc',
        save_best_only=True,
        mode='max',
        verbose=0)
]

# get data
test  = pd.read_csv('./fashion-mnist_test.csv')
train = pd.read_csv('./fashion-mnist_train.csv')
print('train shape: {}'.format(train.shape))
print('test shape: {}'.format(test.shape))

#reshape data
y_train_CNN = train.ix[:,0].values.astype('int32') # only labels i.e targets digits
X_train_CNN = np.array(train.iloc[:,1:].values).reshape(train.shape[0], 1, 28, 28).astype(np.uint8)# reshape to be [samples][pixels][width][height]
print('train shape after reshape: {}'.format(X_train_CNN.shape))

y_test_CNN = test.ix[:,0].values.astype('int32') # only labels i.e targets digits
X_test_CNN = np.array(test.iloc[:,1:].values).reshape((test.shape[0], 1, 28, 28)).astype(np.uint8)
print('test shape after reshape: {}'.format(X_test_CNN.shape))

# one hot encode outputs
y_train_CNN = to_categorical(y_train_CNN)
y_test_CNN = to_categorical(y_test_CNN)
num_classes = y_train_CNN.shape[1]

# normalize inputs from 0-255 to 0-1
X_train_CNN = X_train_CNN / 255
X_test_CNN = X_test_CNN / 255

#size of parameters
batch_size = 128
num_classes = 10
epochs = 100
filter_pixel=3
noise = 1
droprate=0.25

# input image dimensions
img_rows, img_cols = 28, 28

input_shape = (1, img_rows, img_cols)

#Start Neural Network
model = Sequential()
#convolution 1st layer
model.add(Conv2D(64, kernel_size=(filter_pixel, filter_pixel), padding="same",
                 activation='relu',
                 input_shape=input_shape)) #0
model.add(BatchNormalization())
model.add(Dropout(droprate))#3
#model.add(MaxPooling2D())

#convolution 2nd layer
model.add(Conv2D(64, kernel_size=(filter_pixel, filter_pixel), activation='relu',border_mode="same"))#1
model.add(BatchNormalization())
model.add(MaxPooling2D())
model.add(Dropout(droprate))#3

#convolution 3rd layer
model.add(Conv2D(64, kernel_size=(filter_pixel, filter_pixel), activation='relu',border_mode="same"))#1
model.add(BatchNormalization())
model.add(MaxPooling2D())
model.add(Dropout(droprate))#3

#Fully connected 1st layer
model.add(Flatten()) #7
model.add(Dense(500,use_bias=False)) #13
model.add(BatchNormalization())
model.add(Activation('relu')) #14
model.add(Dropout(droprate))      #15

#Fully connected final layer
model.add(Dense(10)) #8
model.add(Activation('softmax')) #9

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.RMSprop(),
              metrics=['accuracy'])

model.summary()

#Save Model=ON
history = model.fit(X_train_CNN, y_train_CNN,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(X_test_CNN, y_test_CNN),shuffle=True,callbacks=callbacks)

score = model.evaluate(X_test_CNN, y_test_CNN, verbose=0)

#print loss and accuracy
print('Test loss:', score[0])
print('Test accuracy:', score[1])