from keras.metrics import BinaryCrossentropy
from keras.losses import MeanSquaredError
from keras.optimizers import adam_v2
from keras.layers import Dense, Flatten, Conv1D, Conv2D, Input, Conv1DTranspose, Conv2DTranspose, Concatenate, MaxPool1D, Dropout, Reshape, Lambda, InputLayer, LeakyReLU, BatchNormalization
from keras.models import Model, load_model
import keras
from tensorflow.keras import backend as K
import tensorflow as tf
from PIL.Image import FLIP_LEFT_RIGHT
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
import os
# import mlflow
import time
import sys
from skimage import measure

from tensorflow.python.ops.array_ops import batch_gather

class GAN(object):
    def __init__(self, porosity, alpha, lr, num_epochs, batch_size, cutoff):
        self.porosity = porosity
        self.alpha = alpha
        self.lr = lr
        self.num_epochs = num_epochs
        self.batch_size = batch_size
        self.cutoff = cutoff

    def config(self):
        physical_devices = tf.config.list_physical_devices('GPU')
        tf.config.experimental.set_memory_growth(physical_devices[0], True)
        if len(physical_devices) == 0:
            print("Erro: Nenhuma GPU disponível")
        os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

    def load_data(self, score_filename, verbose=False):

        data = np.loadtxt(score_filename, delimiter=',')
        X = data[:, 1:-1]
        self.size = int(np.sqrt(X.shape[1]))
        X = X.reshape((X.shape[0], self.size, self.size, 1))

        y = data[:, -1]
        y = y.reshape((y.shape[0], 1))

        scaler = MinMaxScaler()
        y = scaler.fit_transform(y).round(10)
        idxs_good = np.where(y > cutoff)[0]
        idxs_bad = np.where(y <= cutoff)[0]
        if verbose:
            print(f"Good = %.2f %%" %
                    (100*len(idxs_good)/(len(idxs_good)+len(idxs_bad))))

        y = np.zeros(y.shape)
        y[idxs_good] = 1.0

        X_good = X[idxs_good]
        self.data = X_good

        # set shapes
        self.input_G = 128
        self.output_G = self.input_D = X_good.shape[1:]
        self.output_D = 1

    def setup_G(self):
        size = int(self.size/2)
        in_G = Input(shape=(self.input_G,))

        # foundation for 8x8 image
        n_nodes = 128 * size * size
        out_G = Dense(n_nodes, activation=LeakyReLU(alpha=0.2))(in_G)
        out_G = LeakyReLU(alpha=0.2)(out_G)
        out_G = Reshape((size, size, 128))(out_G)
        # upsample to 16x16
        out_G = Conv2DTranspose(128, (4, 4), strides=(
            2, 2), padding='same', activation=LeakyReLU(alpha=0.2))(out_G)
        out_G = LeakyReLU(alpha=0.2)(out_G)
        out_G = Conv2D(1, (size, size), activation='sigmoid',
                       padding='same')(out_G)

        out_density = Lambda(lambda x: x)(out_G)

        model = Model(name='Generator', inputs=in_G,
                      outputs=[out_G, out_density])

        return model

    def style_loss(self):
        def custom_loss(y_true, y_pred):
            size = y_pred.shape[1]*y_pred.shape[2]
            y_pred = K.round(y_pred)
            por_true = K.sum(K.sum(K.sum(y_true, axis=1), axis=1), axis=1)/size
            por_pred = K.sum(K.sum(K.sum(y_pred, axis=1), axis=1), axis=1)/size
            mse = (por_true-por_pred)**2
            return mse
        return custom_loss

    def setup_D(self):
        in_D = Input(shape=self.input_D)
        out_D = Conv2D(64, (3, 3), strides=(2, 2), padding='same',
                       activation=LeakyReLU(alpha=0.2))(in_D)
        out_D = Dropout(0.4)(out_D)
        out_D = Conv2D(64, (3, 3), strides=(2, 2), padding='same',
                       activation=LeakyReLU(alpha=0.2))(out_D)
        out_D = Dropout(0.4)(out_D)
        out_D = Flatten()(out_D)
        out_D = Dense(1, activation='sigmoid')(out_D)

        # compile model
        opt = adam_v2.Adam(learning_rate=0.0002, beta_1=0.5)

        in_density = Input(shape=self.input_D)
        out_density = Lambda(lambda x: x)(in_density)

        optimizer = adam_v2.Adam(learning_rate=self.lr, beta_1=0.5)
        model = Model(
            name='Discriminator',
            inputs=[in_D, in_density],
            outputs=[out_D, out_density])

        model.compile(
            loss=['binary_crossentropy', self.style_loss()],
            loss_weights=[1.0, alpha],
            optimizer=optimizer,
            metrics=['accuracy'],
            run_eagerly=True
            )
        return model

    def setup_GAN(self, G_model, D_model):
        optimizer = adam_v2.Adam(learning_rate=self.lr, beta_1=0.5)
        D_model.trainable = False
        in_G = G_model.input
        out_GAN = D_model(G_model(in_G))
        model = Model(name='GAN', inputs=in_G, outputs=out_GAN)
        model.compile(
            loss=['binary_crossentropy', self.style_loss()],
            loss_weights=[1.0, self.alpha],
            optimizer=optimizer,
            metrics=['accuracy'],
            run_eagerly=True
            )
        return model

    def generate_fake_samples(self, n_samples):
        # generate points in latent space
        X_input = self.generate_input_G(n_samples)
        # predict outputs
        X, _ = self.G_model.predict(X_input)
        # create 'fake' class labels (0)
        y = np.zeros((n_samples, 1))
        return X, y

    def generate_input_G(self, n_samples):
        # generate points in the latent space
        X_input = np.random.randn(self.input_G * n_samples)
        # reshape into a batch of inputs for the network
        X_input = X_input.reshape(n_samples, self.input_G)
        return X_input

    def generate_real_samples(self, n_samples):
        # choose random instances
        ix = np.random.randint(0, self.data.shape[0], n_samples)
        # retrieve selected images
        X = self.data[ix]
        # generate 'real' class labels (1)
        y = np.ones((n_samples, 1))
        return X, y

    def summarize_performance(self, epoch, n_samples=100):
        # prepare real samples
        X_real, y_real = self.generate_real_samples(n_samples)
        # evaluate discriminator on real examples
        _, _, _, acc_real, _ = self.D_model.evaluate(
            x=[X_real, X_real], y=[y_real, self.porosity*np.ones(X_real.shape)], verbose=0)
        # prepare fake examples
        X_fake, y_fake = self.generate_fake_samples(n_samples)
        # evaluate discriminator on fake examples
        _, _, _, acc_fake, _ = self.D_model.evaluate(
            x=[X_fake, X_fake], y=[y_fake, self.porosity*np.ones(X_fake.shape)], verbose=0)
        # summarize discriminator performance
        return acc_real, acc_fake

    def train(self, tmp_models_dir, tol_porosity, plot=False, verbose_loss=False, verbose_acc=False):
        # remove previous tmp models
        for file in os.listdir(tmp_models_dir):
            os.remove(tmp_models_dir+file)

        # setup G and D
        self.G_model = gan.setup_G()
        self.D_model = gan.setup_D()
        self.GAN_model = gan.setup_GAN(self.G_model, self.D_model)

        batch_per_epoch = int(self.data.shape[0] / self.batch_size)
        half_batch = int(self.batch_size/2)

        G_losses = []
        D_losses = []

        # mlflow.keras.autolog()

        for i in range(self.num_epochs):
            G_losses_epoch = []
            D_losses_epoch = []
            for j in range(batch_per_epoch):
                X_real, y_real = self.generate_real_samples(half_batch)
                X_fake, y_fake = self.generate_fake_samples(half_batch)

                X, y = np.vstack((X_real, X_fake)), np.vstack((y_real, y_fake))

                if not verbose_loss:
                    D_loss = self.D_model.train_on_batch(
                        x=[X, X], y=[y, porosity*np.ones(X.shape)])
                    D_loss = D_loss[0]
                else:
                    D_loss = self.D_model.train_on_batch(
                        x=[X, X], y=[y, porosity*np.ones(X.shape)], return_dict=True)
                    print(D_loss)
                    D_loss = D_loss['loss']

                D_losses_epoch.append(D_loss)

                X_GAN = self.generate_input_G(self.batch_size)
                y_GAN = np.ones((self.batch_size, 1))

                if not verbose_loss:
                    G_loss = self.GAN_model.train_on_batch(
                        x=X_GAN, y=[y_GAN, porosity*np.ones(X.shape)])
                    G_loss = G_loss[0]
                else:
                    G_loss = self.GAN_model.train_on_batch(
                        x=X_GAN, y=[y_GAN, porosity*np.ones(X.shape)], return_dict=True)
                    print(G_loss)
                    G_loss = G_loss['loss']

                G_loss = self.GAN_model.train_on_batch(
                    x=X_GAN, y=[y_GAN, porosity*np.ones(X.shape)])
                G_loss = G_loss[0]
                G_losses_epoch.append(G_loss)

                if verbose_loss:
                    print('>%d, %d/%d, D_loss=%.3f, G_loss=%.3f' %
                          (i+1, j+1, batch_per_epoch,  D_loss, G_loss))

            G_losses.append(np.array(G_losses_epoch).mean())
            D_losses.append(np.array(D_losses_epoch).mean())

            if (i+1) % 10 == 0:
                acc_real, acc_fake = self.summarize_performance(i+1)
                # get porosity match ratio
                X_test = self.generate_input_G(1000)
                geoms, _ = self.G_model.predict(X_test)
                geoms = np.array(geoms)
                por_match, _ = self.porosity_match(geoms, tol_porosity)
                # save models
                self.G_model.save(tmp_models_dir+f'epoch_{i+1}_por_{np.round(por_match,2)}_acc_{np.round(acc_fake,2)}.h5')

                if verbose_acc:
                    print('>Epoch: %i Accuracy real: %.0f%%, fake: %.0f%%' %
                          (i+1, acc_real*100, acc_fake*100))

        self.D_model.save('D.h5')

        G_losses = np.array(G_losses)
        D_losses = np.array(D_losses)

        if plot:
            fig = plt.figure()
            fig.set_size_inches((10, 8))
            plt.plot(list(range(1, num_epochs+1)), D_losses, label='D Loss')
            plt.title('Loss')
            plt.ylabel('Loss')
            plt.xlabel('Epoch')
            plt.plot(list(range(1, num_epochs+1)), G_losses, label='G Loss')
            plt.legend()
            plt.show()

    def select_model(self, tmp_models_dir, models_dir, epoch):
        G_files = os.listdir(tmp_models_dir)
        for i in range(len(G_files)):
            G_file = G_files[i]
            epoch_model = int(G_file.split('_')[1])
            if epoch_model == epoch:
                G_model = load_model(tmp_models_dir+G_file)
                break

        G_file = G_file.split('/')[-1][:-3]+f'_batch_{self.batch_size}_lr_{self.lr}_alpha_{self.alpha}.h5'
        G_model.save(models_dir + G_file)

        return G_model

    def porosity_match(self, geoms, tol, plot=False):
        geoms_ = []
        passed = 0

        porosities = []
        for i in range(geoms.shape[0]):
            g = geoms[i, :, :, 0]
            size = g.shape[0]
            g = g.ravel().round()
            p = np.sum(g)/(size*size)
            if p >= self.porosity-tol and p <= self.porosity+tol:
                geoms_.append(g.reshape((size, size)))
                passed += 1
            porosities.append(p)

        if plot:
            sns.histplot(porosities,bins=16)
            plt.show()
        return passed/len(geoms), np.array(geoms_).reshape((passed, size, size, 1))

    def create_unit(self, element, simmetry):
        if simmetry == 'p4':
            unit_size = 2*self.size
            # fold_size = np.random.choice(4,1)[0]
            unit = np.ones((2*self.size,2*self.size))*(-1)
            h,w = element.shape
            for i in range(h):
                for j in range(w):
                    el = element[i,j]

                    j_ = [j,2*w-1-i,2*h-1-j,i]
                    i_ = [i,j,2*w-1-i,2*h-1-j]
                    # (1,7)->(7,14)->(14,8)->(8,1)
                    for (k,l) in list(zip(i_,j_)):
                        unit[k,l]  = el
        return unit

    def check_unit(self, unit, tol):
        labels = measure.label(unit,connectivity=1)
        main_label = 0
        main_label_count = 0
        passed = True

        for label in range(1,len(np.unique(labels))):
            label_count = np.where(labels==label)[0].shape[0]
            if label_count > main_label_count:
                main_label = label
                main_label_count = label_count

        if np.where(labels==0)[0].shape[0]+np.where(labels==main_label)[0].shape[0] >(1.0-tol)*unit.shape[0]*unit.shape[0]:
            for label in range(1,len(np.unique(labels))):
                if label not in [0,main_label]:
                    unit[np.where(labels==label)] = 0.

            if unit[0,:].sum() > 0 and unit[:,0].sum() > 0:
                # check if there is connectivity right-left
                connections_rl = 0
                for i in range(unit.shape[0]):
                    if (unit[i,0] == 1 and unit[i,-1] == 1):
                        connections_rl += 1

                # check if there is connectivity top-bottom
                connections_tb = 0
                for j in range(unit.shape[1]):
                    if (unit[0,j] == 1 and unit[i,-1] == 1):
                        connections_tb += 1

                if connections_rl == 0 or connections_tb == 0:
                    passed = False

            else:
                passed = False

        else:
            passed = False
        return passed, unit[:unit.shape[0]//2,:unit.shape[0]//2]

    def create_arrange(self,unit,rows,cols):
        size = unit.shape[0]
        arrange = np.zeros((rows*size,cols*size))
        for i in range(unit.shape[0]):
            for j in range(unit.shape[1]):
                for row in range(rows):
                    for col in range(cols):
                        arrange[j+row*size,i+col*size] = unit[j,i]

        return arrange
    def generate_arrays(self, epoch, saved_geoms, simmetry, tol_porosiy, tol_unit, tmp_models_dir, models_dir, arrays_dir, start, plot=False, save=False):
        # select model
        G_model = gan.select_model(tmp_models_dir, models_dir, epoch)
        self.D_model = load_model('D.h5',custom_objects={'custom_loss':self.style_loss()})

        # generate geometries
        test_size = saved_geoms*100
        X_test = self.generate_input_G(test_size)
        generated_geoms, _ = G_model.predict(X_test)
        size = generated_geoms.shape[1]
        por_match, geometries = self.porosity_match(generated_geoms, tol_porosity)

        size = geometries.shape[1]
        geometries_ = []

        for i in range(geometries.shape[0]):
            geom = geometries[i].reshape((size, size)).round()
            unit = self.create_unit(geom,simmetry)
            passed, geom_ = self.check_unit(unit,tol_unit)
            if passed:
                geometries_.append(geom_)

        geometries = np.array(geometries_)
        # Get scores
        scores = self.D_model.predict([geometries, geometries])[0].ravel()
        top_idxs = np.argsort(-scores)[:saved_geoms]

        p = start+1
        for top_idx in top_idxs:
            geom = geometries[top_idx]
            unit = self.create_unit(geom.reshape((size, size)), simmetry)
            arrange = self.create_arrange(unit,3,3)
            if plot:
                plt.imshow(arrange, cmap="Greys")
                print("Score: %.2f Porosity: %.2f"%(scores[top_idx],geom.ravel().sum()/(size*size)))
                plt.show()
            if save:
                filename = arrays_dir + "%05d_porosity_%.4f.txt" % (p, geom.ravel().sum()/(size*size))
                np.savetxt(filename, geom.ravel(), delimiter='/n', fmt='%s')
            p += 1

if __name__ == "__main__":
    dimension = sys.argv[1]
    simmetry = sys.argv[2]
    score = sys.argv[3]
    saved_geoms = int(sys.argv[4])
    save = False
    plot = False

    try:
        data = sys.argv[5]
        if data == '-s': save = True
        elif data == '-p': plot = True
    except:
        pass

    try:
        data = sys.argv[6]
        if data == '-s': save = True
        elif data == '-p': plot = True
    except:
        pass

    # mlflow.set_experiment(experiment_name='GAN_%s'%score)
    if os.getcwd().split('\\')[2] == 'lucas':
        score_filename = 'E:/Lucas GAN/Dados/4- Mechanical_scores/RTGA/%sD/%s/%s.csv' % (
            dimension, simmetry, score)
        models_dir = 'E:/Lucas GAN/Dados/5- GAN_models/%sD/%s/%s/' % (dimension, simmetry, score)
        arrays_dir = 'E:/Lucas GAN/Dados/1- Arranged_geometries/GAN/%s/%s/' % (simmetry,score)
        tmp_models_dir = 'C:/Users/lucas/OneDrive/Documentos/GitHub/INT/Manufatura Aditiva/Simulacao-GAN/Pipeline/3- Machine_learning/GAN/tmp_models/'
    else:
        score_filename = 'D:/Lucas GAN/Dados/4- Mechanical_scores/RTGA/%sD/%s/%s.csv' % (
            dimension, simmetry, score)
        models_dir = 'D:/Lucas GAN/Dados/5- GAN_models/%sD/%s/' % (dimension, simmetry)
        arrays_dir = 'D:/Lucas GAN/Dados/1- Arranged_geometries/GAN/%s/%s/' % (simmetry,score)
        tmp_models_dir = 'C:/Users/lucas/Documentos/GitHub/INT/Manufatura Aditiva/Simulacao-GAN/Pipeline/3- Machine_learning/GAN/tmp_models/'

    geom_epoch_dirs = 'C:/Users/lucas/OneDrive/Documentos/GitHub/INT/Manufatura Aditiva/Simulacao-GAN/Pipeline/3- Machine_learning/Analyse/data/%sD/geom_epoch/%s/%s/' %(dimension,simmetry,score)
    start = len(os.listdir(arrays_dir))

    porosity = 0.5
    tol_porosity = 0.02
    tol_unit = 0.02

    alpha = 1e-2
    lr = 1e-4
    num_epochs = 250  # 250-300
    batch_size = 64
    cutoff = 0.82 # hs: 0.63 iso: 0.82

    epoch = 400

    # config GAN
    gan = GAN(porosity, alpha, lr, num_epochs, batch_size, cutoff)
    gan.config()
    data = gan.load_data(score_filename,verbose=False)

    # train
    start_time = time.time()
    # gan.train(tmp_models_dir, tol_porosity, plot=True, verbose_loss=False, verbose_acc=False)

    # get time
    end_time = time.time()
    run_time = end_time-start_time

    # generate arrays
    gan.generate_arrays(epoch, saved_geoms, simmetry, tol_porosity, tol_unit,
                        tmp_models_dir, models_dir, arrays_dir, start, plot=plot, save=save)

    # with mlflow.start_run() as run:
    #     mlflow.log_param('alpha',alpha)
    #     mlflow.log_param('lr',lr)
    #     mlflow.log_param('num_epochs',num_epochs)
    #     mlflow.log_param('batch_size',batch_size)
    #     mlflow.log_param('cutoff',cutoff)
    #     mlflow.log_param('run_time',run_time)
    #     mlflow.log_metric('G_loss',G_loss)
    #     mlflow.log_metric('D_loss',D_loss)


from edgetpu.detection.engine import DetectionEngine
from imutils.video import VideoStream
from PIL import Image
import argparse
import imutils
import time
import cv2
import random
import numpy as np

def dialogBox(title, text, width=200, height=130):
    img = np.zeros((height, width, 3), np.uint8)
    img[:,0:width] = (100, 100, 200)
    cv2.putText(img, text, (0, height//2), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (10,10,10), 2)
    cv2.imshow(title, img)
    cv2.waitKey(0)

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", default="mobilenet_ssd_v2/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite", help="path to TensorFlow Lite object detection model")
ap.add_argument("-l", "--labels", default="mobilenet_ssd_v2/coco_labels.txt", help="path to labels file")
ap.add_argument("-c", "--confidence", type=float, default=0.35, help="minimum probability to filter weak detections")
ap.add_argument("-w", "--width", type=int, default=700, help="width of frame")
args = vars(ap.parse_args())

print("[INFO] parsing class labels...")
labels = {}

for row in open(args["labels"]):
        # unpack the row and update the labels dictionary
        (classID, label) = row.strip().split(maxsplit=1)
        labels[int(classID)] = label.strip()

print("[INFO] loading Coral model...")
model = DetectionEngine(args["model"])

print("[INFO] starting video stream...")

try:
        vs = VideoStream(src=0)
        testVar = imutils.resize(vs.start().read(), width=args["width"])
except Exception as e:
        dialogBox("Error", str(e), width=1000)
        quit()
else:
    vs = vs.start()

def updateThreshold(x):
        args["confidence"] = x/100

def updateSize(x):
    args["width"] = x if x > 100 else 100

cv2.namedWindow("Controls", cv2.WINDOW_NORMAL)
cv2.createTrackbar("Threshold", 'Controls', int(args['confidence']*100), 100,  updateThreshold)
cv2.createTrackbar("Size", 'Controls', int(args['width']),  1000,  updateSize)

def drawFrame():
        frame = vs.read()
        frame = imutils.resize(frame, width=args["width"])
        frame = cv2.flip(frame, 1)
        orig = frame.copy()

        # prepare the frame for object detection by converting (1) it
        # from BGR to RGB channel ordering and then (2) from a NumPy
        # array to PIL image format
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame = Image.fromarray(frame)

        #start = time.time()
        results = model.DetectWithImage(frame, threshold=args["confidence"],
                keep_aspect_ratio=True, relative_coord=False)
        #end = time.time()

        # loop over the results
        for r in results:
                # extract the bounding box and box and predicted class label
                box = r.bounding_box.flatten().astype("int")
                (startX, startY, endX, endY) = box
                label = labels[r.label_id]

                # draw the bounding box and label on the image
                colour = (0, 255*r.score, 255*(1-r.score))
                cv2.rectangle(orig, (startX, startY), (endX, endY), colour, 2)
                y = startY - 15 if startY - 15 > 15 else startY + 15
                text = f"{label}: {int(r.score * 100)}%"
                cv2.putText(orig, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, colour, 2)

        thresh = args['confidence']
        cv2.putText(orig, f"{int(thresh*100)}% Threshold", (args["width"]-130, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255*thresh, 255*(1-thresh)), 2)

        #update the window
        cv2.imshow("Image Recognition", orig)

def close():
        # do a bit of cleanup
        cv2.destroyAllWindows()
        vs.stop()
        dialogBox("Quitting", "Goodbye!")

#draw loop
global looping
looping = True

while looping:
        drawFrame()

        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
                print("[INFO] quitting")
                looping = False
                close()


import torch
from torch import nn
from main_code.model.layer.MoGLayer import MoGLayer
from main_code.model.discrim import DISCRIM_RGB

def gen_noise(noise_dim):
    return torch.rand(noise_dim)

class GENERATOR_RGB(nn.Module):
    def __init__(self, noise_dim, features_dim):
        super(GENERATOR_RGB, self).__init__()
        assert features_dim == noise_dim, "<X>: Currently, noise and features dimension expect to be same."
        self.noise_dim = noise_dim

        # From equation z = MEANi + (STDi * EP) | EP ~ N(0,1)
        self.MoGLayer = MoGLayer(noise_dim=noise_dim)

        self.dense01 = nn.Sequential(
            nn.Linear(in_features=features_dim, out_features=features_dim)
            , nn.Tanh()
        )

        self.batchNorm01 = nn.BatchNorm1d(num_features=features_dim)

        self.dense02 = nn.Sequential(
            nn.Linear(in_features=features_dim, out_features=512 * 4 * 4)
            , nn.ReLU()
        )

        self.conv2dT01 = nn.Sequential(
            # From the paper, they use kern_size = 5, padding = 0
            nn.BatchNorm2d(num_features=512, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.conv2dT02 = nn.Sequential(
            nn.BatchNorm2d(num_features=256, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.conv2dT03 = nn.Sequential(
            nn.BatchNorm2d(num_features=128, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.conv2dT04 = nn.Sequential(
            nn.BatchNorm2d(num_features=64, momentum=0.8)
            , nn.ConvTranspose2d(in_channels=64, out_channels=1, kernel_size=4, padding=1, stride=2)
            , nn.ReLU()
        )

        self.tanh = nn.Tanh()

    """
    Expected tensor to have shape (N,C,...)
    """
    def forward(self, eeg_features):
        noise_input = gen_noise(self.noise_dim)
        x = self.MoGLayer(noise_input)
        x = self.dense01(x)
        x = x * eeg_features  # Multiply noise with eeg signal here
        # print(x.shape)  # Expected to be 2 dimension

        # if len(x.shape) >= 2:
        x = self.batchNorm01(x)  # This layer allowed one batch when the model in eval mode.
        x = self.dense02(x)

        x = x.reshape([x.shape[0], 512, 4, 4])
        # x = x.unsqueeze(0) # Try to run the code with out this line first
        x = self.conv2dT01(x)
        x = self.conv2dT02(x)
        x = self.conv2dT03(x)
        x = self.conv2dT04(x)
        x = self.tanh(x)
        return x

    def set_dev(self, dev):
        self.MoGLayer.set_dev(dev)


import pygame as pg
import sys
import random
import time
pg.init()#初始化
#设置窗口
game_window = pg.display.set_mode((600,500))
#设置窗口标题
pg.display.set_caption('jieqiu')
#设置窗口颜色
window_color = (0,255,255)
#设置球体颜色 接球板颜色
ball_color = (255,255,0)
rect_color = (255,0,0)
#初始化球的位置
ball_x = random.randint(10,590)
ball_y = 10
move_x = 1#用来表示球每次移动的多少位置
move_y = 1
score = 0#记分板
font = pg.font.Font(None,70)#字体 大小
point =1#计分
count = 0
while True:
    game_window.fill(window_color)
    #是窗口不断更新 不要退出
    for event in pg.event.get():
        if event.type ==pg.QUIT:
            sys.exit()
    #获取鼠标的位置
    mouse_x,mouse_y = pg.mouse.get_pos()
    #创建一个球 三个参数，在窗口里面画，颜色，(位置x,y),半径
    pg.draw.circle(game_window,ball_color,(ball_x,ball_y),10)
    #画一个矩形接球 在窗口里面，颜色，（位置x跟随鼠标移动，y只能在最下面，宽度，高度）
    pg.draw.rect(game_window,rect_color,(mouse_x,490,100,10))
    my_text = font.render(str(score),False,(255,255,255))#记分字体 抗拒值 字体颜色
    game_window.blit(my_text,(500,30))
    ball_x += move_x #让球动起来 每次移动
    ball_y += move_y
    if ball_x <= 10 or ball_x>=590:#球的位置左右检测
        move_x = -move_x
    if ball_y <=10:#球的位置到达最上端
        move_y = -move_y
    elif mouse_x-10 <ball_x <mouse_x+110 and ball_y>=480:
        move_y = -move_y
        score +=point
        count += 1
        if count == 3:
            count = 0
            point += point
            if mouse_x>0:
                move_x += 1
            else:
                move_x -= 1
            move_y -= 1
    elif ball_y >= 490 and (ball_x<=mouse_x-10 or ball_x>=mouse_x+100+10):
        break

    pg.display.update()
    time.sleep(0.005)#刷新速度


from itertools import combinations
n, c  = map(int,input().split())
array =  []

for i in range(n):
  array.append(int(input()))
array.sort()
data = list(combinations(array,c))
count = []
max_d = 0
for k in data:
  for i in range(c-1):
    for j in range(i+1,c):
      count.append(k[j]-k[i])
  max_d = max(max_d, min(count))
  count = []
print(max_d)

#### 답

n, c  = map(int,input().split())
array =  []

for i in range(n):
  array.append(int(input()))
array.sort()

start = array[1] - array[0]
end = array[-1] - array[0]
result = 0

while start <= end:
  mid = (start+end)//2
  value = array[0]
  count = 1
  for i in range(1,n):
    if array[i] >= value + mid:
      value = array[i]
      count += 1
  if count >= c:
    start = mid +1
    result = mid
  else:
    end = mid -1

print(result)


num= int(input("Enter a number to check: "))
n= num
flag= 0
while (num!=0):
    digit= int(num%10)
    if(digit==0 or digit==1):
        num= num/10
        continue
    else:
        flag= flag+1
        break
if (flag==0):
    print (n, "is a binary number")
else:
    print (n, "is not a binary number")


from tkinter import Y
import turtle
import random
import time
from Model import Game
from Model import Master
from Model import Monster
import os.path
import os

wn = turtle.Screen()
wn.title("OH NO, Zojoooo!")
#wn.bgpic('oh no zojooooo\slike\svet2.gif')
wn.bgcolor("blue")
wn.setup(width=800, height=600)
wn.tracer(0)

wn.cv._rootwindow.resizable(False, False)

# dodajanje slik
wn.addshape('oh no zojooooo\slike\zojo.gif')
wn.addshape('oh no zojooooo\slike\zojoback.gif')
wn.addshape('oh no zojooooo\slike\Zojoright.gif')
wn.addshape('oh no zojooooo\slike\leftZojo.gif')
wn.addshape('oh no zojooooo\slike\hisa.gif')
wn.addshape('oh no zojooooo\slike\golem.gif')
wn.addshape('oh no zojooooo\slike\inventory.gif')
wn.addshape('oh no zojooooo\slike\woodensword.gif')
wn.addshape('oh no zojooooo\slike\heal_potion.gif')
wn.addshape('oh no zojooooo\slike\stats.gif')
wn.addshape('oh no zojooooo\slike\srcek.gif')
wn.addshape('oh no zojooooo\slike\WEAPONS.gif')
wn.addshape('oh no zojooooo\slike\ITEMS.gif')
wn.addshape('oh no zojooooo\slike\monster_interface.gif')
wn.addshape('oh no zojooooo\slike\svet1.gif')
wn.addshape('oh no zojooooo\slike\prozorno_ozadje.gif')
wn.addshape('oh no zojooooo\slike\menu.gif')
wn.addshape('oh no zojooooo\slike\svet2.gif')
wn.addshape('oh no zojooooo\slike\zacetna_hisa.gif')
wn.addshape('oh no zojooooo\slike\chest.gif')
wn.addshape('oh no zojooooo\slike\chest_inventory.gif')
#Spremenljivke

mode = "zacetek"
curent_mode = ""
inventory_on = False
menu_True = False

atk_button_pressed = False
def_button_pressed = False
spd_button_pressed = False
dge_button_pressed = False

min = 1
atk_spremenljivka = False
def_spremenljivka = False
spd_spremenljivka = False

game = Game()
master = Master()

new_load1 = "NEW GAME"
new_load2 = "NEW GAME"
new_load3 = "NEW GAME"

hp_value = 100
number_of_hearts = 3

wooden_sword_value = False

have_wooden_sword = True
# Zacetna stran

pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 150)
pen.write("OH NO, Zojoooo!", align="center", font=("gameovercre", 35, "normal"))

# Start gumb
start = turtle.Turtle()
start.hideturtle()
start.speed(0)
start.pencolor("black")
start.color("black")

start_x = -100
start_y = -50
start_length = 200
start_width = 100

def start_button():
    start.penup()
    start.fillcolor("white")
    start.begin_fill()
    start.goto(start_x, start_y)
    start.goto(start_x + start_length, start_y)
    start.goto(start_x + start_length, start_y + start_width)
    start.goto(start_x, start_y + start_width)
    start.goto(start_x, start_y)
    start.end_fill()
    start.goto(start_x + 35, start_y + 25)
    start.write("START", font=("gameovercre", 30, "normal"))
start_button()

def start_click(x,y):
    global mode
    global new_load1
    global new_load2
    global new_load3
    if start_x <= x <= start_x + start_length:
        if start_y <= y <= start_y + start_width:
            if mode == "zacetek":
                file_exists = os.path.exists("mastergame.json")
                if not file_exists:
                    master.save_game("mastergame.json")
                pen.clear()
                start.clear()
                mode = "load_data"
                master.load_game("mastergame.json")
                if master.game1 == 1:
                    new_load1 = "LOAD GAME 1"
                if master.game2 == 1:
                    new_load2 = "LOAD GAME 2"
                if master.game3 == 1:
                    new_load3 = "LOAD GAME 3"
                load_data_room()

wn.onclick(start_click)

# load data

def load_data_room():
    global new_load1
    new_save_1 = turtle.Turtle()
    new_save_1.hideturtle()
    new_save_1.speed(0)
    new_save_1.pencolor("black")
    new_save_1.color("black")

    new_save_1_x = -150
    new_save_1_y = 100
    new_save_1_length = 300
    new_save_1_width = 100

    def new_save_1_press():
        new_save_1.penup()
        new_save_1.fillcolor("white")
        new_save_1.begin_fill()
        new_save_1.goto(new_save_1_x, new_save_1_y)
        new_save_1.goto(new_save_1_x + new_save_1_length, new_save_1_y)
        new_save_1.goto(new_save_1_x + new_save_1_length, new_save_1_y + new_save_1_width)
        new_save_1.goto(new_save_1_x, new_save_1_y + new_save_1_width)
        new_save_1.goto(new_save_1_x, new_save_1_y)
        new_save_1.end_fill()
        new_save_1.goto(new_save_1_x + 25, new_save_1_y + 25)
        new_save_1.write(new_load1, font=("gameovercre", 30, "normal"))
    new_save_1_press()

    new_save_2 = turtle.Turtle()
    new_save_2.hideturtle()
    new_save_2.speed(0)
    new_save_2.pencolor("black")
    new_save_2.color("black")

    new_save_2_x = -150
    new_save_2_y = -50
    new_save_2_length = 300
    new_save_2_width = 100

    def new_save_2_press():
        new_save_2.penup()
        new_save_2.fillcolor("white")
        new_save_2.begin_fill()
        new_save_2.goto(new_save_2_x, new_save_2_y)
        new_save_2.goto(new_save_2_x + new_save_2_length, new_save_2_y)
        new_save_2.goto(new_save_2_x + new_save_2_length, new_save_2_y + new_save_2_width)
        new_save_2.goto(new_save_2_x, new_save_2_y + new_save_2_width)
        new_save_2.goto(new_save_2_x, new_save_2_y)
        new_save_2.end_fill()
        new_save_2.goto(new_save_2_x + 25, new_save_2_y + 25)
        new_save_2.write(new_load2, font=("gameovercre", 30, "normal"))
    new_save_2_press()

    new_save_3 = turtle.Turtle()
    new_save_3.hideturtle()
    new_save_3.speed(0)
    new_save_3.pencolor("black")
    new_save_3.color("black")

    new_save_3_x = -150
    new_save_3_y = -200
    new_save_3_length = 300
    new_save_3_width = 100

    def new_save_3_press():
        new_save_3.penup()
        new_save_3.fillcolor("white")
        new_save_3.begin_fill()
        new_save_3.goto(new_save_3_x, new_save_3_y)
        new_save_3.goto(new_save_3_x + new_save_3_length, new_save_3_y)
        new_save_3.goto(new_save_3_x + new_save_3_length, new_save_3_y + new_save_3_width)
        new_save_3.goto(new_save_3_x, new_save_3_y + new_save_3_width)
        new_save_3.goto(new_save_3_x, new_save_3_y)
        new_save_3.end_fill()
        new_save_3.goto(new_save_3_x + 25, new_save_3_y + 25)
        new_save_3.write(new_load3, font=("gameovercre", 30, "normal"))
    new_save_3_press()

    def load_click(x,y):
        global mode
        if new_save_1_x <= x <= new_save_1_x + new_save_1_length:
            if new_save_1_y <= y <= new_save_1_y + new_save_1_width:
                if mode == "load_data":
                    game.set_game_n(1)
                    master.set_game_1(1)
                    new_save_1.clear()
                    new_save_2.clear()
                    new_save_3.clear()
                    file_exists1 = os.path.exists("game1.json")
                    if not file_exists1:
                        mode = "delitev_moci"
                        soba_delitev_moci()
                    else:
                        game.load_game(f"game{game.game_n}.json")
                        load_data()

        if new_save_2_x <= x <= new_save_2_x + new_save_2_length:
            if new_save_2_y <= y <= new_save_2_y + new_save_2_width:
                if mode == "load_data":
                    game.set_game_n(2)
                    master.set_game_2(1)
                    new_save_1.clear()
                    new_save_2.clear()
                    new_save_3.clear()
                    file_exists2 = os.path.exists("game2.json")
                    if not file_exists2:
                        mode = "delitev_moci"
                        soba_delitev_moci()
                    else:
                        game.load_game(f"game{game.game_n}.json")
                        load_data()

        if new_save_3_x <= x <= new_save_3_x + new_save_3_length:
            if new_save_3_y <= y <= new_save_3_y + new_save_3_width:
                if mode == "load_data":
                    game.set_game_n(3)
                    master.set_game_3(1)
                    new_save_1.clear()
                    new_save_2.clear()
                    new_save_3.clear()
                    file_exists3 = os.path.exists("game3.json")
                    if not file_exists3:
                        mode = "delitev_moci"
                        soba_delitev_moci()
                    else:
                        game.load_game(f"game{game.game_n}.json")
                        load_data()

    wn.onclick(load_click)

def load_data():
    global mode
    global inventory_on
    global atk_value
    global def_value
    global spd_value
    global dge_value
    global hp_value

    mode = game.mode
    atk_value = game.atk
    def_value = game.defense
    spd_value = game.spd
    dge_value = game.dge
    y = game.y
    x = game.x
    hp_value = game.hp
    #monsters = game.monsters

    make_fight_weapons()
    make_fight_items()
    make_chest()
    make_chest_inventory()
    naredi_igralca()
    make_inventory()
    inventory_on = True
    make_wooden_sword()
    make_heal_potion()
    user_interface_on()
    make_menu()

    if mode == "svet":
        svet()
    if mode == "svet_desno":
        svet_desno()
    if mode == "zacetna_hisa":
        zacetna_hisa()
    if mode == "svet_levo":
        svet_levo()
    igralec.setx(x)
    igralec.sety(y)

# Soba za delitev moci
def soba_delitev_moci():
    wn.bgcolor("black")
    roll_stat = turtle.Turtle()
    roll_stat.speed(0)
    roll_stat.color("white")
    roll_stat.penup()
    roll_stat.hideturtle()
    roll_stat.goto(0, 190)
    roll_stat.write("Roll for stats", align="center", font=("gameovercre", 35, "normal"))

    atk = turtle.Turtle()
    atk.speed(0)
    atk.color("white")
    atk.penup()
    atk.hideturtle()
    atk.goto(-230, 100)
    atk.write("ATK", align="center", font=("gameovercre", 30, "normal"))

    defense = turtle.Turtle()
    defense.speed(0)
    defense.color("white")
    defense.penup()
    defense.hideturtle()
    defense.goto(-75, 100)
    defense.write("DEF", align="center", font=("gameovercre", 30, "normal"))

    spd = turtle.Turtle()
    spd.speed(0)
    spd.color("white")
    spd.penup()
    spd.hideturtle()
    spd.goto(75, 100)
    spd.write("SPD", align="center", font=("gameovercre", 30, "normal"))

    dge = turtle.Turtle()
    dge.speed(0)
    dge.color("white")
    dge.penup()
    dge.hideturtle()
    dge.goto(230, 100)
    dge.write("DGE", align="center", font=("gameovercre", 30, "normal"))

# atk-kocka
    atk_kocka = turtle.Turtle()
    atk_kocka.hideturtle()
    atk_kocka.speed(0)
    atk_kocka.pencolor("black")
    atk_kocka.color("black")

    atk_kocka_x = -280
    atk_kocka_y = -50
    atk_kocka_length = 100
    atk_kocka_width = 100

    atk_kocka.penup()
    atk_kocka.fillcolor("white")
    atk_kocka.begin_fill()
    atk_kocka.goto(atk_kocka_x, atk_kocka_y)
    atk_kocka.goto(atk_kocka_x + atk_kocka_length, atk_kocka_y)
    atk_kocka.goto(atk_kocka_x + atk_kocka_length, atk_kocka_y + atk_kocka_width)
    atk_kocka.goto(atk_kocka_x, atk_kocka_y + atk_kocka_width)
    atk_kocka.goto(atk_kocka_x, atk_kocka_y)
    atk_kocka.end_fill()
    atk_kocka.goto(atk_kocka_x + 35, atk_kocka_y + 22)

# atk-gumb za metanje kocke
    atk_button = turtle.Turtle()
    atk_button.hideturtle()
    atk_button.speed(0)
    atk_button.pencolor("black")
    atk_button.color("black")

    atk_button_x = -280
    atk_button_y = -200
    atk_button_length = 100
    atk_button_width = 100

    def atk_button_press():
        atk_button.penup()
        atk_button.fillcolor("white")
        atk_button.begin_fill()
        atk_button.goto(atk_button_x, atk_button_y)
        atk_button.goto(atk_button_x + atk_button_length, atk_button_y)
        atk_button.goto(atk_button_x + atk_button_length, atk_button_y + atk_button_width)
        atk_button.goto(atk_button_x, atk_button_y + atk_button_width)
        atk_button.goto(atk_button_x, atk_button_y)
        atk_button.end_fill()
        atk_button.goto(atk_button_x + 17, atk_button_y + 32)
        atk_button.write("ROLL", font=("gameovercre", 20, "normal"))
    atk_button_press()

    def atk_click(x,y):
        global mode
        global atk_button_pressed
        global def_button_pressed
        global spd_button_pressed
        global dge_button_pressed
        if atk_button_x <= x <= atk_button_x + atk_button_length:
            if atk_button_y <= y <= atk_button_y + atk_button_width:
                if mode == "delitev_moci":
                    atk_button.clear()
                    mode = "def_kocka"
                    atk_button_pressed = True
        if def_button_x <= x <= def_button_x + def_button_length:
            if def_button_y <= y <= def_button_y + def_button_width:
                if mode == "def_kocka":
                    def_button.clear()
                    mode = "spd_kocka"
                    def_button_pressed = True
        if spd_button_x <= x <= spd_button_x + spd_button_length:
            if spd_button_y <= y <= spd_button_y + spd_button_width:
                if mode == "spd_kocka":
                    spd_button.clear()
                    mode = "dge_kocka"
                    spd_button_pressed = True
        if dge_button_x <= x <= dge_button_x + dge_button_length:
            if dge_button_y <= y <= dge_button_y + dge_button_width:
                if mode == "dge_kocka":
                    dge_button.clear()
                    mode = "begin"
                    dge_button_pressed = True
                    begin_button_on()

    wn.onclick(atk_click)
# def-kocka

    def_kocka = turtle.Turtle()
    def_kocka.hideturtle()
    def_kocka.speed(0)
    def_kocka.pencolor("black")
    def_kocka.color("black")

    def_kocka_x = -125
    def_kocka_y = -50
    def_kocka_length = 100
    def_kocka_width = 100

    def_kocka.penup()
    def_kocka.fillcolor("white")
    def_kocka.begin_fill()
    def_kocka.goto(def_kocka_x, def_kocka_y)
    def_kocka.goto(def_kocka_x + def_kocka_length, def_kocka_y)
    def_kocka.goto(def_kocka_x + def_kocka_length, def_kocka_y + def_kocka_width)
    def_kocka.goto(def_kocka_x, def_kocka_y + def_kocka_width)
    def_kocka.goto(def_kocka_x, def_kocka_y)
    def_kocka.end_fill()
    def_kocka.goto(def_kocka_x + 35, def_kocka_y + 22)

# def-gumb za metanje kocke

    def_button = turtle.Turtle()
    def_button.hideturtle()
    def_button.speed(0)
    def_button.pencolor("black")
    def_button.color("black")

    def_button_x = -125
    def_button_y = -200
    def_button_length = 100
    def_button_width = 100

    def def_button_press():
        def_button.penup()
        def_button.fillcolor("white")
        def_button.begin_fill()
        def_button.goto(def_button_x, def_button_y)
        def_button.goto(def_button_x + def_button_length, def_button_y)
        def_button.goto(def_button_x + def_button_length, def_button_y + def_button_width)
        def_button.goto(def_button_x, def_button_y + def_button_width)
        def_button.goto(def_button_x, def_button_y)
        def_button.end_fill()
        def_button.goto(def_button_x + 17, def_button_y + 32)
        def_button.write("ROLL", font=("gameovercre", 20, "normal"))
    def_button_press()

# spd-kocka

    spd_kocka = turtle.Turtle()
    spd_kocka.hideturtle()
    spd_kocka.speed(0)
    spd_kocka.pencolor("black")
    spd_kocka.color("black")

    spd_kocka_x = 25
    spd_kocka_y = -50
    spd_kocka_length = 100
    spd_kocka_width = 100

    spd_kocka.penup()
    spd_kocka.fillcolor("white")
    spd_kocka.begin_fill()
    spd_kocka.goto(spd_kocka_x, spd_kocka_y)
    spd_kocka.goto(spd_kocka_x + spd_kocka_length, spd_kocka_y)
    spd_kocka.goto(spd_kocka_x + spd_kocka_length, spd_kocka_y + spd_kocka_width)
    spd_kocka.goto(spd_kocka_x, spd_kocka_y + spd_kocka_width)
    spd_kocka.goto(spd_kocka_x, spd_kocka_y)
    spd_kocka.end_fill()
    spd_kocka.goto(spd_kocka_x + 35, spd_kocka_y + 22)

# spd-gumb za metanje kocke

    spd_button = turtle.Turtle()
    spd_button.hideturtle()
    spd_button.speed(0)
    spd_button.pencolor("black")
    spd_button.color("black")

    spd_button_x = 25
    spd_button_y = -200
    spd_button_length = 100
    spd_button_width = 100

    def spd_button_press():
        spd_button.penup()
        spd_button.fillcolor("white")
        spd_button.begin_fill()
        spd_button.goto(spd_button_x, spd_button_y)
        spd_button.goto(spd_button_x + spd_button_length, spd_button_y)
        spd_button.goto(spd_button_x + spd_button_length, spd_button_y + spd_button_width)
        spd_button.goto(spd_button_x, spd_button_y + spd_button_width)
        spd_button.goto(spd_button_x, spd_button_y)
        spd_button.end_fill()
        spd_button.goto(spd_button_x + 17, spd_button_y + 32)
        spd_button.write("ROLL", font=("gameovercre", 20, "normal"))
    spd_button_press()

# dge kocka
    dge_kocka = turtle.Turtle()
    dge_kocka.hideturtle()
    dge_kocka.speed(0)
    dge_kocka.pencolor("black")
    dge_kocka.color("black")

    dge_kocka_x = 180
    dge_kocka_y = -50
    dge_kocka_length = 100
    dge_kocka_width = 100

    dge_kocka.penup()
    dge_kocka.fillcolor("white")
    dge_kocka.begin_fill()
    dge_kocka.goto(dge_kocka_x, dge_kocka_y)
    dge_kocka.goto(dge_kocka_x + dge_kocka_length, dge_kocka_y)
    dge_kocka.goto(dge_kocka_x + dge_kocka_length, dge_kocka_y + dge_kocka_width)
    dge_kocka.goto(dge_kocka_x, dge_kocka_y + dge_kocka_width)
    dge_kocka.goto(dge_kocka_x, dge_kocka_y)
    dge_kocka.end_fill()
    dge_kocka.goto(dge_kocka_x + 35, dge_kocka_y + 22)

# dge-gumb za metanje kocke

    dge_button = turtle.Turtle()
    dge_button.hideturtle()
    dge_button.speed(0)
    dge_button.pencolor("black")
    dge_button.color("black")

    dge_button_x = 180
    dge_button_y = -200
    dge_button_length = 100
    dge_button_width = 100

    def dge_button_press():
        dge_button.penup()
        dge_button.fillcolor("white")
        dge_button.begin_fill()
        dge_button.goto(dge_button_x, dge_button_y)
        dge_button.goto(dge_button_x + dge_button_length, dge_button_y)
        dge_button.goto(dge_button_x + dge_button_length, dge_button_y + dge_button_width)
        dge_button.goto(dge_button_x, dge_button_y + dge_button_width)
        dge_button.goto(dge_button_x, dge_button_y)
        dge_button.end_fill()
        dge_button.goto(dge_button_x + 17, dge_button_y + 32)
        dge_button.write("ROLL", font=("gameovercre", 20, "normal"))
    dge_button_press()

# begin
    def begin_button_on():
        begin_button = turtle.Turtle()
        begin_button.hideturtle()
        begin_button.speed(0)
        begin_button.pencolor("black")
        begin_button.color("black")

        begin_button_x = -100
        begin_button_y = -200
        begin_button_length = 200
        begin_button_width = 100

        def begin_button_press():
            begin_button.penup()
            begin_button.fillcolor("white")
            begin_button.begin_fill()
            begin_button.goto(begin_button_x, begin_button_y)
            begin_button.goto(begin_button_x + begin_button_length, begin_button_y)
            begin_button.goto(begin_button_x + begin_button_length, begin_button_y + begin_button_width)
            begin_button.goto(begin_button_x, begin_button_y + begin_button_width)
            begin_button.goto(begin_button_x, begin_button_y)
            begin_button.end_fill()
            begin_button.goto(begin_button_x + 40, begin_button_y + 28)
            begin_button.write("BEGIN", font=("gameovercre", 30, "normal"))
        begin_button_press()

        def begin_click(x,y):
            global inventory_on
            global mode
            if begin_button_x <= x <= begin_button_x + begin_button_length:
                if begin_button_y <= y <= begin_button_y + begin_button_width:
                    if mode == "begin":
                        begin_button.clear()
                        mode = "svet"
                        atk_kocka.clear()
                        def_kocka.clear()
                        dge_kocka.clear()
                        spd_kocka.clear()
                        roll_stat.clear()
                        atk.clear()
                        defense.clear()
                        spd.clear()
                        dge.clear()
                        atk_kocka_value.clear()
                        def_kocka_value.clear()
                        spd_kocka_value.clear()
                        dge_kocka_value.clear()
                        make_fight_weapons()
                        make_fight_items()
                        make_chest()
                        make_chest_inventory()
                        svet()
                        naredi_igralca()
                        make_inventory()
                        inventory_on = True
                        make_wooden_sword()
                        make_heal_potion()
                        user_interface_on()
                        make_menu()
        wn.onclick(begin_click)

# igralceva statistika

def user_interface_on():
    global user_interface
    global ui_hp

    user_interface = turtle.Turtle()
    user_interface.speed(0)
    user_interface.shape('oh no zojooooo\slike\stats.gif')
    user_interface.penup()
    user_interface.goto(-245,258)

    ui_atk = turtle.Turtle()
    ui_atk.hideturtle()
    ui_atk.speed(0)
    ui_atk.pencolor("black")
    ui_atk.color("#FEDA41")
    ui_atk.penup()
    ui_atk.goto(-382, 256)
    ui_atk.write( "{}".format(atk_value), font=("gameovercre", 16, "normal"))

    ui_def = turtle.Turtle()
    ui_def.hideturtle()
    ui_def.speed(0)
    ui_def.pencolor("black")
    ui_def.color("#FEDA41")
    ui_def.penup()
    ui_def.goto(-330, 256)
    ui_def.write( "{}".format(def_value), font=("gameovercre", 16, "normal"))

    ui_spd = turtle.Turtle()
    ui_spd.hideturtle()
    ui_spd.speed(0)
    ui_spd.pencolor("black")
    ui_spd.color("#FEDA41")
    ui_spd.penup()
    ui_spd.goto(-282, 256)
    ui_spd.write( "{}".format(spd_value), font=("gameovercre", 16, "normal"))

    ui_dge = turtle.Turtle()
    ui_dge.hideturtle()
    ui_dge.speed(0)
    ui_dge.pencolor("black")
    ui_dge.color("#FEDA41")
    ui_dge.penup()
    ui_dge.goto(-232, 256)
    ui_dge.write( "{}".format(dge_value), font=("gameovercre", 16, "normal"))

    global ui_srcek1
    ui_srcek1 = turtle.Turtle()
    ui_srcek1.speed(0)
    ui_srcek1.shape('oh no zojooooo\slike\srcek.gif')
    ui_srcek1.penup()
    ui_srcek1.goto(-375, 240)

    global ui_srcek2
    ui_srcek2 = turtle.Turtle()
    ui_srcek2.speed(0)
    ui_srcek2.shape('oh no zojooooo\slike\srcek.gif')
    ui_srcek2.penup()
    ui_srcek2.goto(-345, 240)

    global ui_srcek3
    ui_srcek3 = turtle.Turtle()
    ui_srcek3.speed(0)
    ui_srcek3.shape('oh no zojooooo\slike\srcek.gif')
    ui_srcek3.penup()
    ui_srcek3.goto(-315, 240)

    ui_hp = turtle.Turtle()
    ui_hp.hideturtle()
    ui_hp.speed(0)
    ui_hp.pencolor("black")
    ui_hp.color("#FEDA41")
    ui_hp.penup()
    ui_hp.goto(-149, 273)
    ui_hp.write( "{}".format(hp_value), font=("gameovercre", 17, "normal"))

# Inventory

def make_inventory():
    global inventory
    inventory = turtle.Turtle()
    inventory.speed(0)
    inventory.shape('oh no zojooooo\slike\inventory.gif')
    inventory.penup()
    inventory.goto(1000, 1000)

def open_inventory():
    global mode
    global curent_mode
    global inventory
    if inventory_on == True:
        if mode != "weapons" and mode != "items":
            inventory.setx(0)
            inventory.sety(0)
            curent_mode = mode
            mode = "weapons"
            move_wooden_sword()
            inventory_button_on()

        elif mode == "weapons" or mode == "items":
            inventory.setx(1050)
            inventory.sety(1050)
            mode = curent_mode
            move_wooden_sword()
            delete_inventory_buttons()
            move_heal_potion()

# orozje

def make_wooden_sword():
    global wooden_sword
    wooden_sword = turtle.Turtle()
    wooden_sword.speed(0)
    wooden_sword.shape('oh no zojooooo\slike\woodensword.gif')
    wooden_sword.penup()
    wooden_sword.goto(1000,1000)

def move_wooden_sword():
    if inventory_on == True:
        if mode == "weapons":
            wooden_sword.setx(-225)
            wooden_sword.sety(-75)
        elif mode != "weapons":
            wooden_sword.setx(1000)
            wooden_sword.sety(1000)
    elif mode == "fight_weapons":
        wooden_sword.setx(-345)
        wooden_sword.sety(-135)
    elif mode != "fight_weapons":
        wooden_sword.setx(1005)
        wooden_sword.sety(1000)

# items

def make_heal_potion():
    global heal_potion
    heal_potion = turtle.Turtle()
    heal_potion.speed(0)
    heal_potion.shape('oh no zojooooo\slike\heal_potion.gif')
    heal_potion.penup()
    heal_potion.goto(1000,1000)

def move_heal_potion():
    if inventory_on == True:
        if mode == "items":
            heal_potion.setx(-225)
            heal_potion.sety(-75)
        elif mode != "items":
            heal_potion.setx(1000)
            heal_potion.sety(1000)

# gumb za inventory iteme

def inventory_button_on():
    global intventory_items_button
    global intventory_items_button_x
    global intventory_items_button_y
    global intventory_items_button_length
    global intventory_items_button_width
    intventory_items_button = turtle.Turtle()
    intventory_items_button.hideturtle()
    intventory_items_button.speed(0)
    intventory_items_button.pencolor("black")
    intventory_items_button.color("black")

    intventory_items_button_x = 20
    intventory_items_button_y = 19
    intventory_items_button_length = 215
    intventory_items_button_width = 56

    def intventory_items_button_press():
        intventory_items_button.penup()
        intventory_items_button.fillcolor("#FFFB83")
        intventory_items_button.begin_fill()
        intventory_items_button.goto(intventory_items_button_x, intventory_items_button_y)
        intventory_items_button.goto(intventory_items_button_x + intventory_items_button_length, intventory_items_button_y)
        intventory_items_button.goto(intventory_items_button_x + intventory_items_button_length, intventory_items_button_y + intventory_items_button_width)
        intventory_items_button.goto(intventory_items_button_x, intventory_items_button_y + intventory_items_button_width)
        intventory_items_button.goto(intventory_items_button_x, intventory_items_button_y)
        intventory_items_button.end_fill()
        intventory_items_button.goto(intventory_items_button_x + 55, intventory_items_button_y + 3)
        intventory_items_button.write("ITEMS", font=("gameovercre", 30, "normal"))
    intventory_items_button_press()

# gumb za inventory orozja

    global intventory_weapons_button
    global intventory_weapons_button_x
    global intventory_weapons_button_y
    global intventory_weapons_button_length
    global intventory_weapons_button_width
    intventory_weapons_button = turtle.Turtle()
    intventory_weapons_button.hideturtle()
    intventory_weapons_button.speed(0)
    intventory_weapons_button.pencolor("black")
    intventory_weapons_button.color("black")

    intventory_weapons_button_x = -240
    intventory_weapons_button_y = 19
    intventory_weapons_button_length = 215
    intventory_weapons_button_width = 56

    def intventory_weapons_button_press():
        intventory_weapons_button.penup()
        intventory_weapons_button.fillcolor("#FFFB83")
        intventory_weapons_button.begin_fill()
        intventory_weapons_button.goto(intventory_weapons_button_x, intventory_weapons_button_y)
        intventory_weapons_button.goto(intventory_weapons_button_x + intventory_weapons_button_length, intventory_weapons_button_y)
        intventory_weapons_button.goto(intventory_weapons_button_x + intventory_weapons_button_length, intventory_weapons_button_y + intventory_weapons_button_width)
        intventory_weapons_button.goto(intventory_weapons_button_x, intventory_weapons_button_y + intventory_weapons_button_width)
        intventory_weapons_button.goto(intventory_weapons_button_x, intventory_weapons_button_y)
        intventory_weapons_button.end_fill()
        intventory_weapons_button.goto(intventory_weapons_button_x + 20, intventory_weapons_button_y + 3)
        intventory_weapons_button.write("WEAPONS", font=("gameovercre", 30, "normal"))
    intventory_weapons_button_press()

    def intventory_items_click(x,y):
        global mode
        global inventory_on
        if mode == "weapons":
            if intventory_items_button_x <= x <= intventory_items_button_x + intventory_items_button_length:
                if intventory_items_button_y <= y <= intventory_items_button_y + intventory_items_button_width:
                    mode = "items"
                    move_heal_potion()
                    move_wooden_sword()
        if mode == "items":
            if intventory_weapons_button_x <= x <= intventory_weapons_button_x + intventory_weapons_button_length:
                if intventory_weapons_button_y <= y <= intventory_weapons_button_y + intventory_items_button_width:
                    mode = "weapons"
                    move_wooden_sword()
                    move_heal_potion()

    wn.onclick(intventory_items_click)

def delete_inventory_buttons():
    if mode != "inventory":
        intventory_items_button.clear()
        intventory_weapons_button.clear()

# svet

def svet():
    wn.bgpic("oh no zojooooo\slike\svet1.gif")
    game.set_mode(mode)
    move_chest()
    draw_monsters()

# zacetna hisa
def zacetna_hisa():
    wn.bgpic('oh no zojooooo\slike\zacetna_hisa.gif')
    game.set_mode(mode)
    igralec.setx(0)
    igralec.sety(-220)
    move_chest()

# chest
def make_chest():
    global chest
    chest = turtle.Turtle()
    chest.speed(0)
    chest.shape('oh no zojooooo\slike\chest.gif')
    chest.penup()
    chest.goto(1000, 1000)

def move_chest():
    if mode == "zacetna_hisa":
        chest.setx(0)
        chest.sety(100)
    if mode == "svet":
        chest.setx(1000)
        chest.sety(1000)

def make_chest_inventory():
    global chest_inventory
    chest_inventory = turtle.Turtle()
    chest_inventory.speed(0)
    chest_inventory.shape('oh no zojooooo\slike\chest_inventory.gif')
    chest_inventory.penup()
    chest_inventory.goto(1000, 1000)

def move_chest_inventory():
    if mode == "zacetna_hisa":
        chest_inventory.setx(0)
        chest_inventory.sety(200)
    if mode == "chest_inventory":
        chest_inventory.setx(1000)
        chest_inventory.sety(1000)

#monster
"""def monster_funkcija():
    global monster
    monster = turtle.Turtle()
    monster.speed(0)
    monster.shape('oh no zojooooo\slike\golem.gif')
    monster.penup()
    monster.goto(250, 0)
    monster.hideturtle()

def monster_premik():
    if mode == "svet_desno":
        monster.setx(250)
        monster.sety(0)
        monster.showturtle()
    if mode == "svet":
        monster.setx(1000)
        monster.sety(1000)
    if mode == "fight_screen_monster":
        monster.setx(1000)
        monster.sety(1000)
    if golem_hp_value <= 0:
        monster.setx(1000)
        monster.sety(1000)"""

# monster interface
def move_monster_interface():
    if mode == "svet_desno":
        monster_interface.setx(1000)
        monster_interface.sety(1000)
        golem_atk.clear()
        golem_def.clear()
        golem_spd.clear()
        golem_dge.clear()
        golem_hp.clear()

def make_monster_interface():
    global monster_interface
    global golem_atk
    global golem_def
    global golem_spd
    global golem_dge
    global golem_hp

    monster_interface = turtle.Turtle()
    monster_interface.speed(0)
    monster_interface.shape('oh no zojooooo\slike\monster_interface.gif')
    monster_interface.penup()
    monster_interface.goto(242, 270)

    golem_atk = turtle.Turtle()
    golem_atk.hideturtle()
    golem_atk.speed(0)
    golem_atk.pencolor("black")
    golem_atk.color("#BC1212")
    golem_atk.penup()
    golem_atk.goto(212, 256)
    golem_atk.write( m.monster_atk , font=("gameovercre", 16, "normal"))

    golem_def = turtle.Turtle()
    golem_def.hideturtle()
    golem_def.speed(0)
    golem_def.pencolor("black")
    golem_def.color("#BC1212")
    golem_def.penup()
    golem_def.goto(262, 256)
    golem_def.write( m.monster_def , font=("gameovercre", 16, "normal"))

    golem_spd = turtle.Turtle()
    golem_spd.hideturtle()
    golem_spd.speed(0)
    golem_spd.pencolor("black")
    golem_spd.color("#BC1212")
    golem_spd.penup()
    golem_spd.goto(312, 256)
    golem_spd.write( m.monster_spd, font=("gameovercre", 16, "normal"))

    golem_dge = turtle.Turtle()
    golem_dge.hideturtle()
    golem_dge.speed(0)
    golem_dge.pencolor("black")
    golem_dge.color("#BC1212")
    golem_dge.penup()
    golem_dge.goto(362, 256)
    golem_dge.write( m.monster_dge , font=("gameovercre", 16, "normal"))

    golem_hp = turtle.Turtle()
    golem_hp.hideturtle()
    golem_hp.speed(0)
    golem_hp.pencolor("black")
    golem_hp.color("#BC1212")
    golem_hp.penup()
    golem_hp.goto(149, 273)
    golem_hp.write( "{}".format(m.monster_hp), font=("gameovercre", 17, "normal"))

# svet desno
def svet_desno():
    wn.bgpic('oh no zojooooo\slike\svet2.gif')
    game.set_mode(mode)
    draw_monsters()

def draw_monsters():
    for m in game.monsters:
        if m.svet == mode:
            m.monster.showturtle()
        else:
            m.monster.hideturtle()
        if m.alive == False:
                m.monster.hideturtle()

#svet levo
def svet_levo():
    wn.bgcolor("green")
    wn.bgpic('oh no zojooooo\slike\prozorno_ozadje.gif')
    game.set_mode(mode)

# monster fight screen

def fight_screen_monster():
    global mode
    wn.bgpic('oh no zojooooo\slike\prozorno_ozadje.gif')
    wn.bgcolor("#c9c9c9")
    igralec_premik()
    fight_button_on()
    mode = "start_fight"

# premik gumbov

def delete_button():
    if mode == "svet_desno":
        fight_button.clear()
        dont_fight_button.clear()
        items_button.clear()

# fight gumb

def fight_button_on():
    global fight_button
    global fight_button_x
    global fight_button_y
    global fight_button_length
    global fight_button_width
    fight_button = turtle.Turtle()
    fight_button.hideturtle()
    fight_button.speed(0)
    fight_button.pencolor("black")
    fight_button.color("black")

    fight_button_x = -220
    fight_button_y = -200
    fight_button_length = 130
    fight_button_width = 80

    def fight_button_press():
        fight_button.penup()
        fight_button.fillcolor("white")
        fight_button.begin_fill()
        fight_button.goto(fight_button_x, fight_button_y)
        fight_button.goto(fight_button_x + fight_button_length, fight_button_y)
        fight_button.goto(fight_button_x + fight_button_length, fight_button_y + fight_button_width)
        fight_button.goto(fight_button_x, fight_button_y + fight_button_width)
        fight_button.goto(fight_button_x, fight_button_y)
        fight_button.end_fill()
        fight_button.goto(fight_button_x + 30, fight_button_y + 23)
        fight_button.write("FIGHT", font=("gameovercre", 20, "normal"))
    fight_button_press()

# items gumb

    global items_button
    global items_button_x
    global items_button_y
    global items_button_length
    global items_button_width
    items_button = turtle.Turtle()
    items_button.hideturtle()
    items_button.speed(0)
    items_button.pencolor("black")
    items_button.color("black")

    items_button_x = -65
    items_button_y = -200
    items_button_length = 130
    items_button_width = 80

    def items_button_press():
        items_button.penup()
        items_button.fillcolor("white")
        items_button.begin_fill()
        items_button.goto(items_button_x, items_button_y)
        items_button.goto(items_button_x + items_button_length, items_button_y)
        items_button.goto(items_button_x + items_button_length, items_button_y + items_button_width)
        items_button.goto(items_button_x, items_button_y + items_button_width)
        items_button.goto(items_button_x, items_button_y)
        items_button.end_fill()
        items_button.goto(items_button_x + 27, items_button_y + 23)
        items_button.write("ITEMS", font=("gameovercre", 20, "normal"))
    items_button_press()

# dont fight gumb
    global dont_fight_button
    global dont_fight_button_x
    global dont_fight_button_y
    global dont_fight_button_length
    global dont_fight_button_width
    dont_fight_button = turtle.Turtle()
    dont_fight_button.hideturtle()
    dont_fight_button.speed(0)
    dont_fight_button.pencolor("black")
    dont_fight_button.color("black")

    dont_fight_button_x = 90
    dont_fight_button_y = -200
    dont_fight_button_length = 130
    dont_fight_button_width = 80

    def dont_fight_button_press():
        dont_fight_button.penup()
        dont_fight_button.fillcolor("white")
        dont_fight_button.begin_fill()
        dont_fight_button.goto(dont_fight_button_x, dont_fight_button_y)
        dont_fight_button.goto(dont_fight_button_x + dont_fight_button_length, dont_fight_button_y)
        dont_fight_button.goto(dont_fight_button_x + dont_fight_button_length, dont_fight_button_y + dont_fight_button_width)
        dont_fight_button.goto(dont_fight_button_x, dont_fight_button_y + dont_fight_button_width)
        dont_fight_button.goto(dont_fight_button_x, dont_fight_button_y)
        dont_fight_button.end_fill()
        dont_fight_button.goto(dont_fight_button_x + 20, dont_fight_button_y + 10)
        dont_fight_button.write(" DON'T\n FIGHT", font=("gameovercre", 20, "normal"))
    dont_fight_button_press()

# run gumb
    if mode == "in_fight":
        global run_button
        global run_button_x
        global run_button_y
        global run_button_length
        global run_button_width
        run_button = turtle.Turtle()
        run_button.hideturtle()
        run_button.speed(0)
        run_button.pencolor("black")
        run_button.color("black")

        run_button_x = 90
        run_button_y = -200
        run_button_length = 130
        run_button_width = 80

        def run_button_press():
            run_button.penup()
            run_button.fillcolor("white")
            run_button.begin_fill()
            run_button.goto(run_button_x, run_button_y)
            run_button.goto(run_button_x + run_button_length, run_button_y)
            run_button.goto(run_button_x + run_button_length, run_button_y + run_button_width)
            run_button.goto(run_button_x, run_button_y + run_button_width)
            run_button.goto(run_button_x, run_button_y)
            run_button.end_fill()
            run_button.goto(run_button_x + 40, run_button_y + 23)
            run_button.write("RUN", font=("gameovercre", 20, "normal"))
        run_button_press()

# detektor pritiska  fight gumbov
    def fight_click(x,y):
        global mode
        global inventory_on
        if mode == "start_fight":
            if fight_button_x <= x <= fight_button_x + fight_button_length:
                if fight_button_y <= y <= fight_button_y + fight_button_width:
                    move_fight_weapons()
                    fight_back_button_on()
                    fight_button.clear()
                    items_button.clear()
                    dont_fight_button.clear()
                    mode = "fight_weapons"
                    move_wooden_sword()

        if mode == "start_fight":
            if items_button_x <= x <= items_button_x + items_button_length:
                if items_button_y <= y <= items_button_y + items_button_width:
                    move_fight_items()
                    fight_back_button_on()
                    fight_button.clear()
                    items_button.clear()
                    dont_fight_button.clear()
                    mode = "fight_items"
        if mode == "in_fight":
            if run_button_x <= x <= run_button_x + run_button_length:
                if run_button_y <= y <= run_button_y + run_button_width:
                    print("hi")
        if mode == "start_fight":
            if dont_fight_button_x <= x <= dont_fight_button_x + dont_fight_button_length:
                if dont_fight_button_y <= y <= dont_fight_button_y + dont_fight_button_width:
                    mode = "svet_desno"
                    move_monster_interface()
                    svet_desno()
                    delete_button()
                    igralec_premik()
                    inventory_on = True

    wn.onclick(fight_click)

# weapons

def make_fight_weapons():
    global fight_weapons
    fight_weapons = turtle.Turtle()
    fight_weapons.speed(0)
    fight_weapons.shape('oh no zojooooo\slike\WEAPONS.gif')
    fight_weapons.penup()
    fight_weapons.goto(1000,1000)

def move_fight_weapons():
    if mode != "fight_weapons":
        fight_weapons.setx(0)
        fight_weapons.sety(-183)
    if mode == "fight_weapons":
        fight_weapons.setx(1000)
        fight_weapons.sety(1000)
    if mode == "svet_desno":
        fight_weapons.setx(1000)
        fight_weapons.sety(1000)

def make_fight_items():
    global fight_items
    fight_items = turtle.Turtle()
    fight_items.speed(0)
    fight_items.shape('oh no zojooooo\slike\ITEMS.gif')
    fight_items.penup()
    fight_items.goto(1000,-1803)

def move_fight_items():
    if mode != "fight_items":
        fight_items.setx(0)
        fight_items.sety(-183)
    if mode == "fight_items":
        fight_items.setx(1000)
        fight_items.sety(1000)

#back button

def fight_back_button_on():
    global fight_back_button
    global fight_back_button_x
    global fight_back_button_y
    global fight_back_button_length
    global fight_back_button_width

    fight_back_button = turtle.Turtle()
    fight_back_button.hideturtle()
    fight_back_button.speed(0)
    fight_back_button.pencolor("black")
    fight_back_button.color("black")

    fight_back_button_x = 207
    fight_back_button_y = -272
    fight_back_button_length = 130
    fight_back_button_width = 80

    def fight_back_button_press():
        fight_back_button.penup()
        fight_back_button.fillcolor("#FEDA41")
        fight_back_button.begin_fill()
        fight_back_button.goto(fight_back_button_x, fight_back_button_y)
        fight_back_button.goto(fight_back_button_x + fight_back_button_length, fight_back_button_y)
        fight_back_button.goto(fight_back_button_x + fight_back_button_length, fight_back_button_y + fight_back_button_width)
        fight_back_button.goto(fight_back_button_x, fight_back_button_y + fight_back_button_width)
        fight_back_button.goto(fight_back_button_x, fight_back_button_y)
        fight_back_button.end_fill()
        fight_back_button.goto(fight_back_button_x + 30, fight_back_button_y + 23)
        fight_back_button.write("BACK", font=("gameovercre", 20, "normal"))
    fight_back_button_press()

    def back_button_click(x,y):
        global mode
        global wooden_sword_value
        if mode == "fight_weapons":
            if fight_back_button_x <= x <= fight_back_button_x + fight_back_button_length:
                if fight_back_button_y <= y <= fight_back_button_y + fight_back_button_width:
                    move_fight_weapons()
                    fight_back_button.clear()
                    mode = "start_fight"
                    fight_button_on()
                    move_wooden_sword()
            if have_wooden_sword == True:
                if -390 < x < -320:
                    if -180 < y < -100:
                        wooden_sword_value = True
                        fight()
        if mode == "fight_items":
            if fight_back_button_x <= x <= fight_back_button_x + fight_back_button_length:
                if fight_back_button_y <= y <= fight_back_button_y + fight_back_button_width:
                    move_fight_items()
                    fight_back_button.clear()
                    mode = "start_fight"
                    fight_button_on()
    wn.onclick(back_button_click)

# rolling dice

def roll_d4(times_rolled):
    dice = 0
    while times_rolled > 0:
        dice += int(random.uniform(1,5))
        times_rolled -= 1
    return dice

# fight

def fight():
    global monster_attacked
    global player_attacked
    if spd_value >= m.monster_spd:
        player_attacked = True
        player_attack()
    else:
        monster_attacked = True
        monster_attack()

monster_attacked = False
player_attacked = False

def player_attack():
    global wooden_sword_value
    global monster_attacked
    if wooden_sword_value == True:
        damage =  roll_d4(3) + (atk_value // 2)
        print(damage)
    if int(random.uniform(1,101)) < m.monster_dge :
        print("u missed")
    else:
        m.monster_hp = m.monster_hp -(damage - m.monster_def // 2)
        golem_hp.clear()
        golem_hp.write( "{}".format(m.monster_hp), font=("gameovercre", 17, "normal"))
    if monster_attacked == True:
        check_hp()
    else:
        monster_attack()

def monster_attack():
    global hp_value
    damage =  roll_d4(1) + (m.monster_atk)
    print(damage)
    if int(random.uniform(1,101)) < m.monster_dge :
        print("it missed")
    else:
        hp_value = hp_value -(damage - def_value // 2)
        ui_hp.clear()
        ui_hp.write( "{}".format(hp_value), font=("gameovercre", 17, "normal"))
    if player_attacked == True:
        check_hp()
    else:
        player_attack()

def check_hp():
    global mode
    global inventory_on
    global hp_value
    global number_of_hearts
    if hp_value <= 0:
        print("you lost")
        fight_back_button.clear()
        mode = "svet_desno"
        delete_button()
        move_fight_weapons()
        move_wooden_sword()
        move_monster_interface()
        svet_desno()
        igralec_premik()
        inventory_on = True
        ui_hp.clear()
        hp_value = 100
        ui_hp.write( "{}".format(hp_value), font=("gameovercre", 17, "normal"))
        if number_of_hearts == 3:
            ui_srcek3.setx(1000)
            number_of_hearts = 2
        elif number_of_hearts == 2:
            ui_srcek2.setx(1000)
            number_of_hearts = 1
        elif number_of_hearts == 1:
            ui_srcek1.setx(1000)
            number_of_hearts = 0
        elif number_of_hearts == 0:
            print("game over")

    elif m.monster_hp <= 0:
        print("you win")
        fight_back_button.clear()
        fight_button_on()
        m.set_alive(False)
        mode = "svet_desno"
        move_fight_weapons()
        move_wooden_sword()
        move_monster_interface()
        svet_desno()
        delete_button()
        igralec_premik()
        draw_monsters()
        inventory_on = True
    else:
        move_fight_weapons()
        fight_back_button.clear()
        mode = "start_fight"
        move_wooden_sword()
        fight_button_on()

# premikanje igralca

def igralec_premik():
    if mode == "fight_screen_monster":
        igralec.setx(1000)
        igralec.sety(1000)
    if mode == "svet_desno":
        igralec.setx(150)
        igralec.sety(0)

# Igralec #naredi_igralca()
def naredi_igralca():
    global igralec
    igralec = turtle.Turtle()
    igralec.speed(0)
    igralec.shape('oh no zojooooo\slike\zojo.gif')
    igralec.penup()
    igralec.goto(0,-200)

# hoja igralca
    collisions = {
        "svet" : [(65, 300, 400, 50),(-400,-80,-364, -237),(-392, -219,391, -291),(362, -80, 400, -300),(-396, 297,-311, 20),(-330, 295,-100, 201)],
        "zacetna_hisa" : [(1000,1000,1000,1000)],
        "svet_desno" : [(-395, 293,-378, 5),(-394, 294,-136, 103),(-169, 290,44, 169),(55, 176,389, 93),(-397, -83,-385, -286),(-383, -209,-199, -290),(-227, -133,-167, -289),(-163, -55,23, -169),(29, -131,389, -287),(379, -50,400, -300)],
        "svet_levo" : [(1000,1000,1000,1000)],
        'start_fight' : [(-400,300,400,-300)],
        'fight_screen_monster' : [(-400,300,400,-300)]
    }

    def can_move(mode, x, y):
        ovire = collisions[mode]
        for xmin , ymax , xmax, ymin in ovire:
            if (xmin < x < xmax and ymin < y < ymax):
                return False
        return True

    def detection(mode, x, y):
        global object_detection
        ovire = game.objects[mode]
        hit = False
        object_detection = ""
        for xmin , ymax , xmax, ymin, object_name in ovire:
            if (xmin < x < xmax and ymin < y < ymax):
                hit = True
                object_detection = object_name
        return object_detection and hit

    def fight_detection(x,y):
        global m
        for m in game.monsters:
            if m.fight_monster(x,y, mode):
                return m
        return None

    def igralec_up():
        global x
        global y
        global mode
        global inventory_on
        x = igralec.xcor()
        y = igralec.ycor()
        if can_move(mode, x, y+5):
            y += 5
            x += 0
            igralec.sety(y)
            igralec.setx(x)
            igralec.shape('oh no zojooooo\slike\zojoback.gif')
        if detection(mode, x, y+5):
            if object_detection == "zacetna_hisa":
                mode = "zacetna_hisa"
                time.sleep(0.1)
                zacetna_hisa()
            if object_detection == "chest":
                print("hi")
                move_chest_inventory()
                open_inventory()
        if fight_detection(x,y+5):
            mode = "fight_screen_monster"
            fight_screen_monster()
            make_monster_interface()
            inventory_on = False

    def igralec_down():
        global x
        global y
        global mode
        global inventory_on
        x = igralec.xcor()
        y = igralec.ycor()
        if can_move(mode, x, y-5):
            y -= 5
            x += 0
            igralec.sety(y)
            igralec.setx(x)
            igralec.shape('oh no zojooooo\slike\zojo.gif')
        if detection(mode, x, y-5):
            if object_detection == "svet":
                time.sleep(0.1)
                igralec.setx(270)
                igralec.sety(41)
                mode = "svet"
                svet()
        if fight_detection(x,y-5):
            mode = "fight_screen_monster"
            fight_screen_monster()
            make_monster_interface()
            inventory_on = False

    def igralec_right():
        global x
        global y
        global mode
        global inventory_on
        x = igralec.xcor()
        y = igralec.ycor()
        if can_move(mode, x+5, y):
            y -= 0
            x += 5
            igralec.sety(y)
            igralec.setx(x)
            igralec.shape('oh no zojooooo\slike\Zojoright.gif')
        if detection(mode, x+5, y):
            if object_detection == "svet_desno":
                mode = "svet_desno"
                svet_desno()
                igralec.goto(-390,igralec.ycor())
            if object_detection == "svet":
                igralec.goto(-390,igralec.ycor())
                mode = "svet"
                svet()
        if fight_detection(x+5,y):
            mode = "fight_screen_monster"
            fight_screen_monster()
            make_monster_interface()
            inventory_on = False

    def igralec_left():
        global x
        global y
        global mode
        global inventory_on
        x = igralec.xcor()
        y = igralec.ycor()
        if can_move(mode, x-5, y):
            y -= 0
            x -= 5
            igralec.sety(y)
            igralec.setx(x)
            igralec.shape('oh no zojooooo\slike\leftZojo.gif')
        if detection(mode, x-5, y):
            if object_detection == "svet_levo":
                mode = "svet_levo"
                svet_levo()
                igralec.goto(390,igralec.ycor())
            if object_detection == "svet":
                mode = "svet"
                svet()
                igralec.goto(390,igralec.ycor())
        if fight_detection(x-5,y):
            mode = "fight_screen_monster"
            fight_screen_monster()
            make_monster_interface()
            inventory_on = False

# Tipkovnica
    wn.listen()
    wn.onkeypress(igralec_up, "w")
    wn.onkeypress(igralec_down, "s")
    wn.onkeypress(igralec_right, "d")
    wn.onkeypress(igralec_left, "a")
    wn.onkeypress(igralec_up, "W")
    wn.onkeypress(igralec_down, "S")
    wn.onkeypress(igralec_right, "D")
    wn.onkeypress(igralec_left, "A")

    wn.onkeypress(open_inventory, "e")
    wn.onkeypress(open_inventory, "E")

    wn.onkeypress(menu_on, "Escape")

# menu

def make_menu():
    global menu
    menu = turtle.Turtle()
    menu.speed(0)
    menu.shape('oh no zojooooo\slike\menu.gif')
    menu.penup()
    menu.goto(1000,1000)
def menu_on():
    global curent_mode
    global mode
    global inventory_on
    global menu_True
    if inventory_on == True:
        if menu_True == False:
            curent_mode = mode
            mode = ("menu")
            menu.setx(0)
            menu.sety(0)
            save_and_quit_on()
            menu_True = True
            ui_hp.clear()
        elif menu_True == True:
            mode = curent_mode
            menu_True = False
            menu.setx(1000)
            menu.sety(1000)
            save_and_quit.clear()
            ui_hp.write( "{}".format(hp_value), font=("gameovercre", 17, "normal"))

def save_and_quit_on():
    global save_and_quit
    global save_and_quit_x
    global save_and_quit_y
    global save_and_quit_length
    global save_and_quit_width
    save_and_quit = turtle.Turtle()
    save_and_quit.hideturtle()
    save_and_quit.speed(0)
    save_and_quit.pencolor("black")
    save_and_quit.color("black")

    save_and_quit_x = -150
    save_and_quit_y = -100
    save_and_quit_length = 300
    save_and_quit_width = 80

    def save_and_quit_press():
        save_and_quit.penup()
        save_and_quit.fillcolor("#FEDA41")
        save_and_quit.begin_fill()
        save_and_quit.goto(save_and_quit_x, save_and_quit_y)
        save_and_quit.goto(save_and_quit_x + save_and_quit_length, save_and_quit_y)
        save_and_quit.goto(save_and_quit_x + save_and_quit_length, save_and_quit_y + save_and_quit_width)
        save_and_quit.goto(save_and_quit_x, save_and_quit_y + save_and_quit_width)
        save_and_quit.goto(save_and_quit_x, save_and_quit_y)
        save_and_quit.end_fill()
        save_and_quit.goto(save_and_quit_x + 50, save_and_quit_y + 23)
        save_and_quit.write("SAVE AND QUIT", font=("gameovercre", 20, "normal"))
    save_and_quit_press()

    def menu_button_click(x,y):
        global mode
        if mode == "menu":
            if save_and_quit_x <= x <= save_and_quit_x + save_and_quit_length:
                if save_and_quit_y <= y <= save_and_quit_y + save_and_quit_width:
                    save_game()
                    quit_game()

    wn.onclick(menu_button_click)

# save

def save_game():
    game.set_x(x)
    game.set_y(y)
    game.set_hp(hp_value)
    game.save_game(f"game{game.game_n}.json")
    master.save_game("mastergame.json")

# quit game

def quit_game():
    global running
    running = False

# from turtle import *
# import turtle as tur
# def position(event):
#     a, b = (event.x - 400), 0-(event.y - 300)
#     print('{}, {}'.format(a, b))

# ws = tur.getcanvas()
# ws.bind('<Motion>', position)
# tur.done()

# loop igre

running = True
while running:
    wn.update()

# vrtenje atk kocke

    if mode == "delitev_moci" and atk_button_pressed == False:
        atk_kocka_value = turtle.Turtle()
        atk_kocka_value.hideturtle()
        atk_kocka_value.speed(0)
        atk_kocka_value.pencolor("black")
        atk_kocka_value.color("black")
        atk_kocka_value.penup()
        atk_kocka_value.goto(-245, -28)
        atk_value = int(random.uniform(1,10))
        atk_kocka_value.write( "{}".format(atk_value), font=("gameovercre", 40, "normal"))
        time.sleep(0.1)
        atk_kocka_value.clear()

    if mode == "def_kocka" and atk_button_pressed == True:
        atk_kocka_value.write( "{}".format(atk_value), font=("gameovercre", 40, "normal"))
        atk_button_pressed == False
        game.set_atk(atk_value)
        if atk_value < 4 and atk_spremenljivka == False:
            min += (5 - atk_value)
            atk_spremenljivka = True

# vrtenje def kocke

    if mode == "def_kocka" and def_button_pressed == False:
        def_kocka_value = turtle.Turtle()
        def_kocka_value.hideturtle()
        def_kocka_value.speed(0)
        def_kocka_value.pencolor("black")
        def_kocka_value.color("black")
        def_kocka_value.penup()
        def_kocka_value.goto(-90, -28)
        def_value = int(random.uniform(min,10))
        def_kocka_value.write( "{}".format(def_value), font=("gameovercre", 40, "normal"))
        time.sleep(0.1)
        def_kocka_value.clear()

    if mode == "spd_kocka" and def_button_pressed == True:
        def_kocka_value.write( "{}".format(def_value), font=("gameovercre", 40, "normal"))
        def_button_pressed == False
        game.set_def(def_value)
        if def_value < 4 and def_spremenljivka == False:
            min += (5 - def_value)
            def_spremenljivka = True
# vrtenje spd kocke

    if mode == "spd_kocka" and spd_button_pressed == False:
        spd_kocka_value = turtle.Turtle()
        spd_kocka_value.hideturtle()
        spd_kocka_value.speed(0)
        spd_kocka_value.pencolor("black")
        spd_kocka_value.color("black")
        spd_kocka_value.penup()
        spd_kocka_value.goto(60, -28)
        spd_value = int(random.uniform(min,10))
        spd_kocka_value.write( "{}".format(spd_value), font=("gameovercre", 40, "normal"))
        time.sleep(0.1)
        spd_kocka_value.clear()

    if mode == "dge_kocka" and spd_button_pressed == True:
        spd_kocka_value.write( "{}".format(spd_value), font=("gameovercre", 40, "normal"))
        spd_button_pressed == False
        game.set_spd(spd_value)
        if spd_value < 4 and spd_spremenljivka == False:
            min += (5 - spd_value)
            spd_spremenljivka = True
#vrtenje dge kocke
    if mode == "dge_kocka" and dge_button_pressed == False:
        dge_kocka_value = turtle.Turtle()
        dge_kocka_value.hideturtle()
        dge_kocka_value.speed(0)
        dge_kocka_value.pencolor("black")
        dge_kocka_value.color("black")
        dge_kocka_value.penup()
        dge_kocka_value.goto(215, -28)
        dge_value = int(random.uniform(min,10))
        dge_kocka_value.write( "{}".format(dge_value), font=("gameovercre", 40, "normal"))
        time.sleep(0.1)
        dge_kocka_value.clear()

    if mode == "begin" and dge_button_pressed == True:
        dge_kocka_value.write( "{}".format(dge_value), font=("gameovercre", 40, "normal"))
        dge_button_pressed = False
        game.set_dge(dge_value)


from safetensors import safe_open
from diffusers import StableDiffusionPipeline
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
from diffusers.models import AutoencoderKL
import os

def mix_pipeline_safetensors():
    pipeline_1_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Chilloutmix-Ni"
    pipeline_2_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/uberRealisticPornMerge_urpmv12"

    #Return a CheckpointMergerPipeline class that allows you to merge checkpoints.
    #The checkpoint passed here is ignored. But still pass one of the checkpoints you plan to
    #merge for convenience
    # pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger")

    #There are multiple possible scenarios:
    #The pipeline with the merged checkpoints is returned in all the scenarios

    #Compatible checkpoints a.k.a matched model_index.json files. Ignores the meta attributes in model_index.json during comparision.( attrs with _ as prefix )
    # merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","CompVis/stable-diffusion-v1-2"], interp = "sigmoid", alpha = 0.4)

    #Incompatible checkpoints in model_index.json but merge might be possible. Use force = True to ignore model_index.json compatibility
    # merged_pipe_1 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion"], force = True, interp = "sigmoid", alpha = 0.4)

    #Three checkpoint merging. Only "add_difference" method actually works on all three checkpoints. Using any other options will ignore the 3rd checkpoint.
    # merged_pipe_2 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion","prompthero/openjourney"], force = True, interp = "add_difference", alpha = 0.4)

    # prompt = "An astronaut riding a horse on Mars"

    # image = merged_pipe(prompt).images[0]

    pipe = DiffusionPipeline.from_pretrained(pipeline_2_path, custom_pipeline="checkpoint_merger")
    merged_pipe = pipe.merge([pipeline_2_path, pipeline_1_path], interp="sigmoid", alpha=0.7)

def is_int(d):
    try:
        d = int(d)
        return True
    except Exception as e:
        return False

def add_lora(lora_path, pipe, lora_weight=0.5):
    tensors = {}
    with safe_open(lora_path, framework="pt", device="cpu") as f:
        for key in f.keys():
            tensors[key] = f.get_tensor(key).to('cuda')

    for k_lora, v_lora in tensors.items():
        if k_lora.startswith('lora_te'):
            model = pipe.text_encoder
            # continue
        elif k_lora.startswith('lora_unet'):
            model = pipe.unet
        else:
            print(k_lora)

        # down 跳过
        if '.lora_down.' in k_lora:
            print('lora_down')
            continue
        if '.alpha' in k_lora:
            print('alpha')
            continue
        print('lora_up')

        k_lora_name = k_lora.split('.')[0]
        attr_name_list = k_lora_name.split('_')
        cur_attr = model
        latest_attr_name = ''
        for idx in range(2, len(attr_name_list)):
            attr_name = attr_name_list[idx]
            if is_int(attr_name):
                cur_attr = cur_attr[int(attr_name)]
                latest_attr_name = ''
            else:
                try:
                    if latest_attr_name != '':
                        cur_attr = cur_attr.__getattr__(f"{latest_attr_name}_{attr_name}")
                    else:
                        cur_attr = cur_attr.__getattr__(attr_name)
                    latest_attr_name = ''
                except Exception as e:
                    if latest_attr_name != '':
                        latest_attr_name = f"{latest_attr_name}_{attr_name}"
                    else:
                        latest_attr_name = attr_name

        w = cur_attr.weight
        up_w = v_lora
        down_w = tensors[k_lora.replace('.lora_up.', '.lora_down.')]
        print(down_w.shape, up_w.shape, w.shape)
        try:
            alpha_key = k_lora_name + '.alpha'
            alpha_w = tensors[alpha_key]
            wight = alpha_w / up_w.shape[1]
            print(alpha_w, wight)
        except Exception as e:
            wight = 1

        einsum_a = f"ijabcdefg"
        einsum_b = f"jkabcdefg"
        einsum_res = f"ikabcdefg"
        length_shape = len(up_w.shape)
        einsum_str = f"{einsum_a[:length_shape]},{einsum_b[:length_shape]}->{einsum_res[:length_shape]}"
        d_w = torch.einsum(einsum_str, up_w, down_w)
        # print(d_w.shape, wight)

        # wight = 1
        cur_attr.weight.data = cur_attr.weight.data + d_w * wight * lora_weight
        print('================================= add')
    return pipe

def test_model():

    output_dir = '/share/wangqixun/workspace/tmp/tmp_6'
    os.makedirs(output_dir, exist_ok=True)

    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Chilloutmix-Ni"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/abyssorangemix2SFW_abyssorangemix2Sfw"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Midnight_Mixer_Melt"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/URPM_CM_mix"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/uberRealisticPornMerge_urpmv12"
    model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/perfectWorld_perfectWorldBakedVAE"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Midnight_Mixer_Melt"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/cheeseDaddys_35"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/abyssorangemix3AOM3_aom3a3"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/gf2_v20"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/neverendingDreamNED_bakedVae"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/Anything-v4.5-vae-fp16-diffuser"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/abyssorangemix2SFW_abyssorangemix2Sfw"
    # model_id = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/wlop_1"

    pipe = StableDiffusionPipeline.from_pretrained(
        model_id,
        torch_dtype=torch.float32,
        custom_pipeline="lpw_stable_diffusion",
    )
    pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
    # pipe.vae = AutoencoderKL.from_pretrained('/share/wangqixun/workspace/github_project/diffusers/checkpoint/stabilityai/sd-vae-ft-mse')
    pipe = pipe.to(torch.float16)
    pipe = pipe.to('cuda')
    pipe.safety_checker = None

    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/LORADilraba_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.7)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/galGadotLora_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.65)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/taiwanDollLikeness_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/koreanDollLikeness_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/fashionGirl_v35.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.66)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/gakkiAragakiYui_v2.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.65)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/asiafacemixLora300_asiafacemixPruned.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/nudify_v11.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.6)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/hipoly3DModelLora_v10.safetensors"
    # pipe = add_lora(lora_path, pipe, 0.5)
    # lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/makotoShinkaiSubstyles_offset.safetensors"
    # pipe = add_lora(lora_path, pipe, 1.0)
    lora_path = "/share/wangqixun/workspace/github_project/diffusers/checkpoint/jiyeon_V30.safetensors"
    pipe = add_lora(lora_path, pipe, 0.3)

    # hiqcgbody, hiqcgface
    text = 'jiyeon2, photorealistic,realistic, solo, photorealistic, best quality, ultra high res, round hat with ribbon, short curly blonde hair, big blue eyes, sitting in a field of wildflowers, beautiful, masterpiece, best quality, extremely detailed face, perfect lighting, close up photo, best quality, ultra high res, photorealistic, ultra detailed, masterpiece, best quality, (naked: 1.5),'
    neg_text = '(worst quality:2), (low quality:2), (normal quality:2), lowres, normal quality, ((monochrome)), ((grayscale)), skin spots, acnes, skin blemishes, age spot, glans,watermark,nsfw,'
    batch_size = 2
    input_size = (512, 640)
    latents = torch.randn([batch_size, 4, input_size[1] // 8, input_size[0] // 8], device=pipe.device, dtype=torch.float16)

    for idx_img in range(0, 9, 1):
        imgs = pipe(
            text,
            latents=None,
            negative_prompt=neg_text,
            height=input_size[1],
            width=input_size[0],
            num_inference_steps=50,
            # guidance_scale=8,
            num_images_per_prompt=batch_size,
        ).images
        # imgs[0].save(f'/share/wangqixun/workspace/tmp/{idx_img:03d}.jpg')
        for idx in range(len(imgs)):
            imgs[idx].save(f'{output_dir}/{idx_img:03d}_{idx:03d}.jpg')

def merge_imgs_to_video():
    imgs_dir = '/share/wangqixun/workspace/tmp_5'
    output_video_file = '/share/wangqixun/workspace/tmp_video_1/005.mp4'
    from redpy.utils_redpy import write_video_file
    from moviepy.editor import ImageSequenceClip
    from glob import glob
    import os

    imgs = sorted(list(glob(f"{imgs_dir}/*.jpg")))
    video_clip = ImageSequenceClip(imgs, fps=1)
    os.makedirs(os.path.dirname(output_video_file), exist_ok=True)
    write_video_file(video_clip, output_video_file)

if __name__ == '__main__':
    # mix_pipeline_safetensors()
    # merge_imgs_to_video()
    pass


# Made by artor1as
"""
    Input: list with different int numbers (negative, zero, positive)
    Output: list with replaced number
    (left: negative numbers, middle: zero numbers, right: positive)
    Extra condition: use only one cycle to replace numbers
"""

def list_replace(lst=None):
    if lst is None:
        lst = []
    neg_lst = []
    pos_lst = []
    zero_lst = []
    for i in lst:
        if i < 0:
            neg_lst.append(i)
        elif i == 0:
            zero_lst.append(i)
        else:
            pos_lst.append(i)
    return neg_lst+zero_lst+pos_lst

if __name__ == '__main__':
    data_lst = []
    while True:
        num = input("Enter number (type \'exit\' to exit cycle): ")
        if num == "exit":
            break
        try:
            data_lst.append(int(num))
        except ValueError:
            print("Enter valid number")
            continue
    print(list_replace(data_lst))