Beispiel #1
0
    def setInstance(self, instance):
        self.currentInstance = instance

        # Loads the theme in the instance (if any)
        config.ICON = utils.loadImage("favicon.ico", self.currentInstance)
        config.LOGO = utils.loadImage("logo.png", self.currentInstance)
        config.BACKGROUND = utils.loadImage("background.png", self.currentInstance)
        config.BLOG_BACKGROUND = utils.getFile("blogbackground.png", self.currentInstance)
        config.BLOG = utils.getFile("blog.html", self.currentInstance)

        # Sets the theme.
        self.setWindowIcon(QIcon(config.ICON))
        self.createImages()
        self.logo.setPixmap(config.LOGO.scaled(self.logo.size(), Qt.KeepAspectRatio))
        with open(config.BLOG, "r", encoding="utf-8") as file:
            content = file.read()
        self.theInternet.setHtml(content.replace("&background&", urllib.parse.quote(config.BLOG_BACKGROUND.replace("\\", "/"))))
        for index in range(len(self.guiElements)):
            self.guiElements[index].raise_()

        # Finishing touches. The logo needs raising because it isnt on the guielements list.
        self.logo.raise_()
        self.instanceConfig = utils.loadInstanceSettings(self, self.currentInstance)
        try:
            self.pres.update(details="In launcher", large_image="pymcllogo512", state="Selected modpack: " + self.currentInstance)
        except:
            pass
Beispiel #2
0
    def __init__(self, imgFolder, mode, loc, ident, colorKey = None):
        pygame.sprite.Sprite.__init__(self)

        self.identity = ident

        ## might have been smarter to just make the mode == fileName
        # that way instead of an if statement could just have
        # load "mode.<ext>"
        if mode == "textButton": ## red Box
            self.image, self.rect = loadImage(imgFolder, "redButton.png", colorKey)
        elif mode == "expandButton": ## horizontal expandButton
            self.image,self.rect = loadImage(imgFolder, "arrow_buttonHorizontal.gif", colorKey)
        elif mode == "unExpandButton": ## vertical expandButton
            self.image,self.rect = loadImage(imgFolder, "arrow_buttonVertical.gif", colorKey)
        elif mode == "addToGroceryListButton": ## shopping cart button
            self.image,self.rect = loadImage(imgFolder, "shoppingCart.png", colorKey)
        elif mode == "removeFromGroceryListButton": ##
            self.image,self.rect = loadImage(imgFolder, "shoppingCartAdded.png", colorKey)
        elif mode == "backButton":
            self.image,self.rect = loadImage(imgFolder, "backButton.png", colorKey)
        elif mode == "checkBox":
            self.image,self.rect = loadImage(imgFolder, "checkBox.png", colorKey)
        elif mode =="writeToDesktop":
            self.image,self.rect = loadImage(imgFolder, "writeToDesktop.jpg", colorKey)
        elif mode == "delete":
            self.image,self.rect = loadImage(imgFolder, "deleteButton.png", colorKey)
        elif mode == "deleted":
            self.image,self.rect = loadImage(imgFolder, "isDeletedButton.png", colorKey)
            
            
        self.rect.topleft = loc
        self.active = True
Beispiel #3
0
 def __init__(self):
     super().__init__()
     try:
         self.currentInstance = os.listdir(config.MC_DIR + "/instances")[0]
     except:
         self.currentInstance = ""
     self.loggedIn = False  # Tells the launcher if the user is logged in.
     utils.areYouThere(config.MC_DIR + "/instances")
     screen_resolution = app.desktop().screenGeometry()  # Gets primary monitor resolution.
     self.title = config.NAME + " " + config.VER
     config.ICON = utils.loadImage("favicon.ico", self.currentInstance)
     self.setWindowIcon(QIcon(config.ICON))
     config.LOGO = utils.loadImage("logo.png", self.currentInstance)
     config.BACKGROUND = utils.loadImage("background.png", self.currentInstance)
     config.BLOG_BACKGROUND = utils.getFile("blogbackground.png", self.currentInstance)
     config.BLOG = utils.getFile("blog.html", self.currentInstance)
     self.left = (screen_resolution.width() / 2) - 427
     self.top = (screen_resolution.height() / 2) - 240
     self.launcherConfig = utils.loadSettings(self)
     self.instanceConfig = utils.loadInstanceSettings(self, self.currentInstance)
     try:
         self.pres = pypresence.Presence("548208354196062228")  # Go ahead and use this if you want, provided you are modifying the launcher. Not that I can really stop you.
         self.pres.connect()
         self.pres.update(details="In launcher", large_image="pymcllogo512", state="Selected modpack: " + self.currentInstance)
     except:
         self.pres = None
     self.checkAlive(threadingEvent)
     self.update = utils.checkOnline()
     self.initUI()
Beispiel #4
0
 def __init__(self, _engine, _buttons):
     super(Menu, self).__init__(_engine)
     self.image = utils.loadImage('gfx/menu.jpg')
     self.logo = utils.loadImage('gfx/logo.png', alpha = True)
     self._resx, self._resy = self._engine.getResolution()
     self._background = pygame.transform.smoothscale(self.image, (self._resx, self._resy))
     self._background.blit(self.logo, (self._resx / 2 - self.logo.get_size()[0] / 2, 100)) # rysuje wyśrodkowane logo
     self.surface = self._background.copy()
     self._focus = 0
     self._buttons = _buttons
     self._updated = []
Beispiel #5
0
 def loadini (self,path, seed):
     random.seed(seed)
     Config = configparser.ConfigParser()
     Config.read(path)
     sections = Config.sections()
     name = Config.get('info', 'name' , fallback=None)
     if name != None:
         self.modname.append(name)
         self.author[self.modname[-1]] = Config.get('info', 'author' , fallback="")
         self.description[self.modname[-1]] = Config.get('info', 'description' , fallback="")
         for line in sections:
             if line != "info":
                 self.tile_typ[self.modname[-1] + "_" +line] = int(Config.get(line, 'typ'))
                 self.tile_path[self.modname[-1] + "_" +line] = os.path.join(main_dir,Config.get(line, 'path') )
                 self.tile_way[self.modname[-1] + "_" +line] = float(Config.get(line, 'way' , fallback=1) )
                 self.tile_size[self.modname[-1] + "_" +line] = int(Config.get(line, 'tilesize',fallback=10))
                 self.tile_colorkey[self.modname[-1] + "_" +line] = Config.get(line, 'colorkey' , fallback=None)
                 self.tile_ani_speed[self.modname[-1] + "_" +line] = int(Config.get(line, 'speed' , fallback=0))
                 self.tile_ani_tiles[self.modname[-1] + "_" +line] = int(Config.get(line, 'tiles',fallback=1))
                 self.tile_get_stock[self.modname[-1] + "_" +line] = Config.get(line, 'stock',fallback=None)
                 if self.tile_get_stock[self.modname[-1] + "_" +line] != None:
                     split = self.tile_get_stock[self.modname[-1] + "_" +line].split(",")
                     for z in split:
                         if z in self.tile_stocks:
                             self.tile_stocks[z] += [self.modname[-1] + "_" +line]
                         else:
                             self.tile_stocks[z] = [self.modname[-1] + "_" +line]
                 if self.tile_typ[self.modname[-1] + "_" +line] < 2:
                     self.tile_from[self.modname[-1] + "_" +line] = int(Config.get(line, 'from',fallback=0))
                     self.tile_to[self.modname[-1] + "_" +line] = int(Config.get(line, 'to',fallback=255))
                     self.tile_random[self.modname[-1] + "_" +line] = int(Config.get(line, 'much', fallback=100))
                     for x in range(self.tile_from[self.modname[-1] + "_" +line],self.tile_to[self.modname[-1] + "_" +line]+1):
                         if random.randrange(0,100) < self.tile_random[self.modname[-1] + "_" +line]:
                                 self.tile_types_world[x][self.tile_typ[self.modname[-1] + "_" +line]] = self.modname[-1] + "_" +line
                 else:                       
                     build = Config.get(line, 'build',fallback=None)
                     if build != None:
                         self.tile_pathbig[self.modname[-1] + "_" +line] =os.path.join(main_dir, Config.get(line, 'pathbig', fallback=None))
                         self.tile_build.append(self.modname[-1] + "_" +line)
                         build = build.split(",")
                         for z in build:
                             if self.modname[-1] + "_" +line in self.tile_onbuild:
                                 self.tile_onbuild[self.modname[-1] + "_" +line] += [self.modname[-1] + "_" +z]
                             else:
                                 self.tile_onbuild[self.modname[-1] + "_" +line] = [self.modname[-1] + "_" +z]
     
     for name in self.tile_path:
         self.tile_org[name] = utils.loadImage(self.tile_path[name] ,self.tile_ani_tiles[name], self.tile_size[name] , self.tile_colorkey[name])
     
     for name in self.tile_pathbig:
         self.tile_orgbig[name] = utils.loadImage(self.tile_pathbig[name] ,1, 75 )
Beispiel #6
0
 def __init__(self, _engine, _buttons):
     super(Menu, self).__init__(_engine)
     self.image = utils.loadImage('data/gfx/menu.jpg')
     self.logo = utils.loadImage('data/gfx/logo.png', alpha=True)
     self._resx, self._resy = self._engine.getResolution()
     self._background = pygame.transform.smoothscale(
         self.image, (self._resx, self._resy))
     self._background.blit(self.logo,
                           (self._resx / 2 - self.logo.get_size()[0] / 2,
                            100))  # rysuje wyśrodkowane logo
     self.surface = self._background.copy()
     self._focus = 0
     self._buttons = _buttons
     self._updated = []
    def __init__(self, director):
		escena.Escena.__init__(self, director)
		pygame.mixer.music.load("../musica/divano.mp3")
		pygame.mixer.music.play(-1, 0.0)
		self.menu = utils.loadImage('../graficos/menu/foto.png', True, (480, 400))
		self.espadita = utils.loadImage("../graficos/menu/espadita.png", True)
		self.r_espadita = self.espadita.get_rect()
		self.r_espadita.centerx = 310
		self.r_espadita.centery = 290
		
		self.texto_comenzar, self.r_texto_comenzar = utils.text("Comenzar", 490, 290)
		self.texto_salir, self.r_texto_salir = utils.text("Salir", 490, 490)
		
		self.option = 1 # Opción del menú que está seleccionada.
    def loadExtractedVOIFileButtonOnButtonClick(self, event):
        """
        Callback for load extracted VOI button.
        :param event
        :return:
        """
        # Load file
        iFile = utils.ShowOpenDialog(self, os.curdir, wildcard="*.nii")

        if iFile is not None:
            # Load image
            voi_mat = utils.loadImage(iFile)[0]

            # Value distribution
            fs_voi_nos = np.sort(np.unique(voi_mat))

            # Construct VOI list
            df = self.fs_lut.loc[self.fs_lut["FS VOI No."].isin(fs_voi_nos), :]
            voi_list = df["FS VOI name"].values.tolist()

            # Omit currently selected VOIs
            [
                voi_list.pop(voi_list.index(v))
                for v in self.voiset_table["FS VOI name"].values
            ]

            # Update VOI list
            self.currentNIfTIFile = iFile
            self.updateFSVOIList(voi_list)
Beispiel #9
0
	def __init__(self, _engine, _hero, _freeobjs):
		"""_engine - obiekt silnika, _hero - bohater, _freeobjs - wolne obiekty na planie(nie przypisane do żadnej warstwy, panelu)"""

		super(ChestItems, self).__init__()
		self.images = {
			'cell': utils.loadImage('data/gfx/cell.png', alpha = True),
		}

		self._updated = []
		self._engine = _engine
		self._hero = _hero
		self.screenUpdated()
		self.surface = pygame.Surface((192, 192))
		self.surface.fill((1, 5, 4))
		self.surface.set_colorkey((1, 5, 4))
		self._cells = pygame.sprite.Group()
		pygame.draw.rect(self.surface, (0, 0, 0), (0, 7, 192, 2))
		for y in xrange(2):
			for x in xrange(3):
				cell = Cell((x, y), _freeobjs)
				cell.rect.center = (cell.rect.centerx + 8*x, cell.rect.centery + 16 + y*8)
				self._cells.add(cell)

		self._cells.draw(self.surface)
		pygame.draw.rect(self.surface, (0, 0, 0), (120, 20, 64, 64))
		self._chest = None # wskaźnik na otwartą skrzynkę
		self.opened = None # pozycja otwartej skrzynkę
Beispiel #10
0
 def __init__(self, _image='unknown'):
     super(Item, self).__init__()
     self.image = utils.loadImage(_image, alpha=True)
     self.rect = self.image.get_rect()
     self._detached = False
     self._attached = None  # obiekt do którego przypięty jest przedmiot(skrzynia, pole, komórka w ekwipunku)
     self.stats = defaultdict(lambda: 0)
def mergeFSVOI(in_file, out_file, voidef):
    """
    Merge Freesurfer VOI on NIfTI image.
    :param in_file: Input NIfTI file. (e.g., aparc+aseg.nii)
    :param out_file: Output NIfTI file. 
    :param voidef: VOI definition table.
    :return:
    """
    # Load image
    in_mat, in_aff = utils.loadImage(in_file)[:2]

    # Load VOI definition
    u_voidef = voidef[["user VOI No.",
                       "user VOI name"]].drop_duplicates(["user VOI name"])

    # Merge VOIs
    out_mat = np.zeros_like(in_mat)
    for u_voi_no, u_voi in zip(u_voidef["user VOI No."],
                               u_voidef["user VOI name"]):
        fs_voi_list = voidef.loc[voidef["user VOI name"] == u_voi,
                                 "FS VOI No."].values
        mask = gen_merged_mask(in_mat, fs_voi_list)
        out_mat[mask] = u_voi_no

    # Save VOI map
    utils.array2NIfTI(out_mat, in_aff, out_file)

    # Save LUT for user-defined VOI
    out_lut_file = utils.addPrefix(out_file, "lut_")
    io_voi.save_userLUT(voidef, out_lut_file)

    return out_mat
def generateDatasets(dataset_name, n_train, n_valid, n_test):
    img = utils.loadImage(dataset_path + original_image)
    basepath = dataset_path + dataset_name + '/'
    basepath_img = basepath + 'img/'
    #training set
    print("Generating: training dataset")
    img_list, points_list = augmentImage(img,
                                         n_train,
                                         max_zoom=max_zoom,
                                         interval=interval)

    img_paths = []
    for i in range(len(img_list)):
        image = img_list[i]
        path = basepath_img + 'train_{0:04d}.png'.format(i)
        cv2.imwrite(path, image)
        img_paths.append(path)
    dataset = {
        'path': img_paths,
        'y': points_list,
    }
    ds.saveDataset(basepath + train_file, dataset)

    # validation set
    print("Generating: validation dataset")
    img_list, points_list = augmentImage(img,
                                         n_valid,
                                         max_zoom=max_zoom,
                                         interval=interval)
    img_paths = []
    for i in range(len(img_list)):
        image = img_list[i]
        path = basepath_img + 'valid_{0:04d}.png'.format(i)
        cv2.imwrite(path, image)
        img_paths.append(path)
    dataset = {
        'path': img_paths,
        'y': points_list,
    }
    ds.saveDataset(basepath + vaid_file, dataset)

    # test set
    print("Generating: test dataset")
    img_list, points_list = augmentImage(img,
                                         n_test,
                                         max_zoom=max_zoom,
                                         interval=interval)
    img_paths = []
    for i in range(len(img_list)):
        image = img_list[i]
        path = basepath_img + 'test_{0:04d}.png'.format(i)
        cv2.imwrite(path, image)
        img_paths.append(path)
    dataset = {
        'path': img_paths,
        'y': points_list,
    }
    ds.saveDataset(basepath + test_file, dataset)

    pass
Beispiel #13
0
 def __init__(self, _map):
     super(BackgroundLayer, self).__init__(_map, None)
     _image = utils.loadImage('data/gfx/tile.png')
     w, h = _map.getSize()
     for i in xrange(0, h / 32):
         for j in xrange(0, w / 32):
             self.surface.blit(_image, (j * 32, i * 32))
Beispiel #14
0
 def __init__(self, _map):
     super(BackgroundLayer, self).__init__(_map, None)
     _image = utils.loadImage('data/gfx/tile.png')
     w, h = _map.getSize()
     for i in xrange(0, h / 32):
         for j in xrange(0, w / 32):
             self.surface.blit(_image, (j * 32, i * 32))
Beispiel #15
0
    def __init__(self, _engine, _hero, _freeobjs):
        """_engine - obiekt silnika, _hero - bohater, _freeobjs - wolne obiekty na planie(nie przypisane do żadnej warstwy, panelu)"""

        super(ChestItems, self).__init__()
        self.images = {
            'cell': utils.loadImage('data/gfx/cell.png', alpha=True),
        }

        self._updated = []
        self._engine = _engine
        self._hero = _hero
        self.screenUpdated()
        self.surface = pygame.Surface((192, 192))
        self.surface.fill((1, 5, 4))
        self.surface.set_colorkey((1, 5, 4))
        self._cells = pygame.sprite.Group()
        pygame.draw.rect(self.surface, (0, 0, 0), (0, 7, 192, 2))
        for y in xrange(2):
            for x in xrange(3):
                cell = Cell((x, y), _freeobjs)
                cell.rect.center = (cell.rect.centerx + 8 * x,
                                    cell.rect.centery + 16 + y * 8)
                self._cells.add(cell)

        self._cells.draw(self.surface)
        pygame.draw.rect(self.surface, (0, 0, 0), (120, 20, 64, 64))
        self._chest = None  # wskaźnik na otwartą skrzynkę
        self.opened = None  # pozycja otwartej skrzynkę
Beispiel #16
0
def datasetGenerator(dataset, batch_size=default_batch_size, augment=False):
    n_dataset = len(dataset)
    paths = dataset['path']
    labels = dataset['y']
    #print(paths)
    #print(labels)
    while 1:
        paths, labels = shuffle(paths, labels)
        for offset in range(0, n_dataset, batch_size):
            batch_paths = paths[offset:offset + batch_size]
            batch_labels = labels[offset:offset + batch_size]
            X = []
            y = []
            for path,label in zip(batch_paths, batch_labels):
                img = utils.loadImage(path)
                if augment:
                    img = augmentImage(img)
                label_flat = np.array(label).flatten() #make it flat
                #print('label: ',label_flat)

                X.append(img)
                y.append(label_flat)

            X = np.array(X)
            y = np.array(y)
            yield shuffle(X,y)
Beispiel #17
0
	def __init__(self, _image = 'unknown'):
		super(Item, self).__init__()
		self.image = utils.loadImage(_image, alpha = True)
		self.rect = self.image.get_rect()
		self._detached = False
		self._attached = None # obiekt do którego przypięty jest przedmiot(skrzynia, pole, komórka w ekwipunku)
		self.stats = defaultdict(lambda: 0)
Beispiel #18
0
	def __init__(self, x, y, surface):
		super(Player, self).__init__()

		self.x = x
		self.y = y

		self.dx = 0
		self.dy = 0

		self.speed = 0.2

		self.surface = surface

		self.image = utils.loadImage("player.png")

		self.width = self.image.get_width()
		self.height = self.image.get_height()

		self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

		arrowKeys = {"up": 		K_UP,
					 "down": 	K_DOWN,
					 "left":	K_LEFT,
					 "right":	K_RIGHT}

		wasdKeys = {"up":		K_w,
					"down": 	K_s,
					"left":		K_a,
					"right":	K_d}

		self.chosenKeys = wasdKeys

		self.life = 100
Beispiel #19
0
	def __init__(self, _engine, _editor):
		super(EditorMenu, self).__init__()
		self.images = {
			'save': utils.loadImage('data/gfx/save.png', alpha = True),
			'cancel': utils.loadImage('data/gfx/cancel.png', alpha = True),
		}

		self._engine = _engine
		self._editor = _editor
		self.screenUpdated()
		self.surface = pygame.Surface((192, 32))
		self.surface.fill((1, 5, 4))
		self.surface.set_colorkey((1, 5, 4))
		self._save = pygame.Rect(60, 0, 32, 32)
		self.surface.blit(self.images['save'], self._save)
		self._clear = pygame.Rect(100, 0, 32, 32)
		self.surface.blit(self.images['cancel'], self._clear)
Beispiel #20
0
 def __init__(self, player):
     pygame.sprite.Sprite.__init__(self)
     self.dir = 1 #-1 left, 1 right
     self.image, self.rect = loadImage('mega.png')
     self.player = player
     self.bounds = (10, 8, 52, 56)
     self.char = self.image.subsurface(self.bounds)
     self.char_rect = self.char.get_rect()
Beispiel #21
0
 def __init__(self, player):
     pygame.sprite.Sprite.__init__(self)
     self.dir = 1  #-1 left, 1 right
     self.image, self.rect = loadImage('mega.png')
     self.player = player
     self.bounds = (10, 8, 52, 56)
     self.char = self.image.subsurface(self.bounds)
     self.char_rect = self.char.get_rect()
Beispiel #22
0
    def __init__(self, _engine, _editor):
        super(EditorMenu, self).__init__()
        self.images = {
            'save': utils.loadImage('data/gfx/save.png', alpha=True),
            'cancel': utils.loadImage('data/gfx/cancel.png', alpha=True),
        }

        self._engine = _engine
        self._editor = _editor
        self.screenUpdated()
        self.surface = pygame.Surface((192, 32))
        self.surface.fill((1, 5, 4))
        self.surface.set_colorkey((1, 5, 4))
        self._save = pygame.Rect(60, 0, 32, 32)
        self.surface.blit(self.images['save'], self._save)
        self._clear = pygame.Rect(100, 0, 32, 32)
        self.surface.blit(self.images['cancel'], self._clear)
Beispiel #23
0
        def __init__(self,
                     _grid,
                     _logic,
                     _image='data/gfx/field.png',
                     _showModifiers=False):
            """_grid - pozycja na siatce, _logic - logika pola, _image - scieżka do obrazka, _showModifiers - czy rysować reprezentacje modyfikatora."""

            super(Field.Sprite, self).__init__()
            self.image = utils.loadImage(_image)
            self.modifiers = {
                MODIFIER_HERO:
                utils.loadImage('data/gfx/hero/sign.png', alpha=True),
                MODIFIER_SPIDER:
                utils.loadImage('data/gfx/spider/sign.png', alpha=True),
                MODIFIER_SKELETON:
                utils.loadImage('data/gfx/skeleton/sign.png', alpha=True),
                MODIFIER_MAGE:
                utils.loadImage('data/gfx/mage/sign.png', alpha=True),
                MODIFIER_TROLL:
                utils.loadImage('data/gfx/troll/sign.png', alpha=True),
                MODIFIER_BLOCKED:
                None,
                MODIFIER_ITEM:
                utils.loadImage('data/gfx/sack.png', alpha=True),
            }

            self._logic = _logic
            self._grid = _grid
            self._showModifiers = _showModifiers
            self._refresh = True
            self.rect = self.image.get_rect()
            self.rect.center = _grid[0] * 32 + 16, _grid[1] * 32 + 16
Beispiel #24
0
 def __init__(self, parent=None):
     super().__init__(parent)
     screen_resolution = app.desktop().screenGeometry()
     self.title = config.NAME + " " + config.VER + " Modpack Exporter"
     config.ICON = utils.loadImage("favicon.ico", "")
     self.setWindowIcon(QIcon(config.ICON))
     self.left = screen_resolution.width() / 2 - 450
     self.top = screen_resolution.height() / 2 - 220
     self.initUI()
    def readGroundLevel(self):
        with open(self.controller.getGround(), "rb") as level_file:
            data = pickle.load(level_file)
            image = loadImage(data["tileset"])
            tiles = data["tiles"]
            width = data["map_width"]
            height = data["map_height"]

            return (image, tiles, width, height)
Beispiel #26
0
 def classInit(const, basepath=None):
     if basepath is None:
         basepath = os.getcwd()
     eatpath = os.path.join(basepath, constants.resourcespath, const["eatshape"])
     Mesenchymal.eat = utils.loadImage(eatpath)
     Mesenchymal.eat = utils.scaleToMax(constants.wallconst, Mesenchymal.eat)
     Mesenchymal.degrad_rate = const["zeta"]
     Mesenchymal.safety_factor = const["safety_factor"]
     Mesenchymal.classInitialized = True
Beispiel #27
0
	def __init__(self, _grid, _freeobjs = None, _hero = None):
		"""_grid - pozycja pola na siatce, _modifier - modyfikator."""

		super(Cell, self).__init__()
		self.image = utils.loadImage('data/gfx/cell.png', alpha = True)
		self._freeobjs = _freeobjs
		self._grid = _grid
		self._hero = _hero
		self.rect = self.image.get_rect()
		self.rect.center = _grid[0] * 32 + 16, _grid[1] * 32 + 16
		self._refresh = True
		self._item = None
Beispiel #28
0
    def _loadImage(self):
        """ 载入图片并根据屏幕窗口调整大小 """
        # 跑步状态
        self._runningImageDays = utils.loadImages(Settings.dinoRunningPath, 1, 2, -1, Settings.defaultColorKey,
                                                  Settings.initialWindowSize[0] * Settings.screenDinoRate)
        self._runningImageNights = utils.invertSurfaces(self._runningImageDays)

        # 俯冲状态
        self._divingImageDays = utils.loadImages(Settings.dinoDivingPath, 1, 2, -1, Settings.defaultColorKey,
                                                 Settings.initialWindowSize[0] * Settings.screenDivingDinoRate)
        self._divingImageNights = utils.invertSurfaces(self._divingImageDays)

        # 跳跃状态
        self._jumpingImageDay = utils.loadImage(Settings.dinoJumpingPath, Settings.defaultColorKey,
                                                Settings.initialWindowSize[0] * Settings.screenDinoRate)
        self._jumpingImageNight = utils.invertSurface(self._jumpingImageDay)

        # 死亡状态
        self._dyingImageDay = utils.loadImage(Settings.dinoDyingPath, Settings.defaultColorKey,
                                              Settings.initialWindowSize[0] * Settings.screenDinoRate)
        self._dyingImageNight = utils.invertSurface(self._dyingImageDay)
Beispiel #29
0
    def initDrawing(self):
        # draw the save button

        self.saveIcon, self.imageList = utils.loadImage(
            filename=settings.SRC_DIR + "/icons/save.png",
            size=(20, 20),
            imageList=self.imageList,
            root=self.root,
            background=toHex(self.cs.background))
        self.saveIcon.bind("<Button-1>", self.handleSavePress)

        return
Beispiel #30
0
    def _update(self, map):
        if not self._map:
            self._play = False
            return

        for mine in map.mines:
            _id = mine.position.x, mine.position.y
            if not self._mineLayer.get(_id):
                _mine = ObjectsLayer.Sprite(utils.loadImage('data/gfx/bomb.png', alpha = True))
                self._mineLayer.add(_id, _mine)
                self._mineLayer.move(_id, _id)

        for _id, player in enumerate(map.playersPositions):
            if not self._heroLayer.get(_id):
                self._heroLayer.add(_id, ObjectsLayer.Sprite(utils.loadImage('data/gfx/hero/n.png', alpha = True)))

            _hero = self._heroLayer.get(_id)
            _pos = _hero.getPos()
            self._heroLayer.move(_id, (player.x, player.y))
            _newpos = _hero.getPos()
            if _pos[0] > _newpos[0]:
                _hero.changeImage(utils.loadImage('data/gfx/hero/w.png', alpha = True))

            if _pos[0] < _newpos[0]:
                _hero.changeImage(utils.loadImage('data/gfx/hero/e.png', alpha = True))

            if _pos[1] > _newpos[1]:
                _hero.changeImage(utils.loadImage('data/gfx/hero/n.png', alpha = True))

            if _pos[1] < _newpos[1]:
                _hero.changeImage(utils.loadImage('data/gfx/hero/s.png', alpha = True))

            if _id == self._playerID:
                _, _, w, h = self._map.getRectangle()
                self._map.setShift((w / 2 - _newpos[0], h / 2 - _newpos[1]))
Beispiel #31
0
    def __init__(self, _grid, _modifier):
        """_grid - pozycja pola na siatce, _modifier - modyfikator."""

        super(Modifier, self).__init__()
        self.images = {
            MODIFIER_HERO:
            utils.loadImage('data/gfx/hero/sign.png', alpha=True),
            MODIFIER_SPIDER:
            utils.loadImage('data/gfx/spider/sign.png', alpha=True),
            MODIFIER_SKELETON:
            utils.loadImage('data/gfx/skeleton/sign.png', alpha=True),
            MODIFIER_MAGE:
            utils.loadImage('data/gfx/mage/sign.png', alpha=True),
            MODIFIER_TROLL:
            utils.loadImage('data/gfx/troll/sign.png', alpha=True),
            MODIFIER_ITEM:
            utils.loadImage('data/gfx/sack.png', alpha=True),
        }

        self._grid = _grid
        self._pos = _grid[0] * 32 + 16, _grid[1] * 32 + 16
        self._modifier = _modifier
        self.image = self.images[_modifier]
        self.rect = self.image.get_rect()
        self.rect.center = _grid[0] * 32 + 16, _grid[1] * 32 + 16
Beispiel #32
0
    def _update(self, map):
        if not self._map:
            self._play = False
            return

        for mine in map.mines:
            _id = mine.position.x, mine.position.y
            if not self._mineLayer.get(_id):
                _mine = ObjectsLayer.Sprite(utils.loadImage('gfx/bomb.png', alpha = True))
                self._mineLayer.add(_id, _mine)
                self._mineLayer.move(_id, _id)

        for _id, player in enumerate(map.playersPositions):
            if not self._heroLayer.get(_id):
                self._heroLayer.add(_id, ObjectsLayer.Sprite(utils.loadImage('gfx/hero/n.png', alpha = True)))

            _hero = self._heroLayer.get(_id)
            _pos = _hero.getPos()
            self._heroLayer.move(_id, (player.x, player.y))
            _newpos = _hero.getPos()
            if _pos[0] > _newpos[0]:
                _hero.changeImage(utils.loadImage('gfx/hero/w.png', alpha = True))

            if _pos[0] < _newpos[0]:
                _hero.changeImage(utils.loadImage('gfx/hero/e.png', alpha = True))

            if _pos[1] > _newpos[1]:
                _hero.changeImage(utils.loadImage('gfx/hero/n.png', alpha = True))

            if _pos[1] < _newpos[1]:
                _hero.changeImage(utils.loadImage('gfx/hero/s.png', alpha = True))

            if _id == self._playerID:
                _, _, w, h = self._map.getRectangle()
                self._map.setShift((w / 2 - _newpos[0], h / 2 - _newpos[1]))
Beispiel #33
0
	def __init__(self, _engine, _hero, _inventory, _freeobjs):
		"""_engine - obiekt silnika, _inventory - ekwipunek  bohatera, _hero - bohater, _freeobjs - wolne obiekty na scenie(nie przypisane do żadnej warstwy)"""

		super(Inventory, self).__init__()
		self.images = {
			'cell': utils.loadImage('data/gfx/cell.png', alpha = True),
		}

		self._updated = []
		self._engine = _engine
		self._hero = _hero
		self._inventory = _inventory
		self.screenUpdated()
		self.surface = pygame.Surface((192, 192))
		self.surface.fill((1, 5, 4))
		self.surface.set_colorkey((1, 5, 4))
		self._cells = pygame.sprite.Group()
		for y in xrange(2, 5):
			for x in xrange(5):
				cell = Cell((x, y), _freeobjs, self._hero)
				cell.rect.center = (cell.rect.centerx + 8*x, cell.rect.centery + y*8)
				self._cells.add(cell)

		for (_cell, _item) in zip(self._cells, _inventory):
			_item.attach(_cell)

		_cell = LeftHandCell((0, 0), _freeobjs, self._hero) # lewa ręka
		_cell.rect.center = (_cell.rect.centerx, _cell.rect.centery)
		self._cells.add(_cell)

		_cell = ArmorCell((1, 0), _freeobjs, self._hero) # pancerz
		_cell.rect.center = (_cell.rect.centerx + 8, _cell.rect.centery)
		self._cells.add(_cell)

		_cell = RightHandCell((2, 0), _freeobjs, self._hero) #prawa ręka
		_cell.rect.center = (_cell.rect.centerx + 16, _cell.rect.centery)
		self._cells.add(_cell)

		_cell = StrengthCell((0, 1), self._hero) # Siła
		_cell.rect.center = (_cell.rect.centerx, _cell.rect.centery + 8)
		self._cells.add(_cell)

		_cell = IntelligenceCell((1, 1), self._hero) # Inteligencja
		_cell.rect.center = (_cell.rect.centerx + 8, _cell.rect.centery + 8)
		self._cells.add(_cell)

		_cell = AgilityCell((2, 1), self._hero) # Zręczność
		_cell.rect.center = (_cell.rect.centerx + 16, _cell.rect.centery + 8)
		self._cells.add(_cell)

		self._cells.draw(self.surface)
		pygame.draw.rect(self.surface, (0, 0, 0), (120, 4, 64, 64))
Beispiel #34
0
def loadtypes(tilesize):
    types = {}
    imgs_org = {}
    imgs = {}
    img_ani_pos = {}
    img_ani_speed = {}
    img_ani_tiles = {}
    img_ani_tile_pos = {}
    Config = configparser.ConfigParser()
    Config.read(os.path.join(main_dir, "basic.ini"))
    sections = Config.sections()
    modname = Config.get("info", "name")
    path = Config.get("info", "path")
    mouse = Config.get("info", "mouse")
    imgs_org["path"] = utils.loadImage(os.path.join(main_dir, path))
    imgs["path"] = utils.imagetransformscale(imgs_org["path"], tilesize)
    imgs_org["mouse"] = utils.loadImage(os.path.join(main_dir, mouse), colorkey="-1")
    imgs["mouse"] = utils.imagetransformscale(imgs_org["mouse"], tilesize)
    types["mouse"] = ""
    types["path"] = ""
    img_ani_speed["mouse"] = 0
    img_ani_tiles["mouse"] = 0
    img_ani_speed["path"] = 0
    img_ani_tiles["path"] = 0
    for line in sections:
        if line != "info":
            imgpath = os.path.join(main_dir, Config.get(line, "img"))
            types[modname + "_" + line] = float(Config.get(line, "path", fallback=1))
            tilesizeimg = int(Config.get(line, "tilesize"))
            colorkey = Config.get(line, "colorkey", fallback=None)
            img_ani_speed[modname + "_" + line] = int(Config.get(line, "speed", fallback=0))
            img_ani_tiles[modname + "_" + line] = int(Config.get(line, "tiles", fallback=1))
            imgs_org[modname + "_" + line] = utils.loadImage(
                imgpath, img_ani_tiles[modname + "_" + line], tilesizeimg, colorkey=colorkey
            )
            print(imgs_org[modname + "_" + line])
            imgs[modname + "_" + line] = utils.imagetransformscale(imgs_org[modname + "_" + line], tilesize)
    return types, imgs, imgs_org, img_ani_speed, img_ani_tiles
Beispiel #35
0
	def __init__(self, _engine):
		super(Editor, self).__init__(_engine)
		self.side = utils.loadImage('data/gfx/side.png')
		self._background = pygame.Surface((self._resx, self._resy))
		self._background.blit(self.side, (self._resx - 232, self._resy - 1500))
		self.surface = self._background.copy()
		self._level = utils.loadLevel('data/level.dat') or [[[Field((x, y)) for x in xrange(MAP_SIZE)] for y in xrange(MAP_SIZE)]]
		self._map = Map(_engine, self, self._level, True)
		self._cursor = Cursor(_engine, self._map)
		self._minimap = Minimap(_engine, self._map)
		self._tiles = TilesGrid(_engine, self, self._map)
		self._menu = EditorMenu(_engine, self)
		self._submodules = (self._map, self._minimap, self._tiles, self._menu, self._cursor)
		self._refresh = True
Beispiel #36
0
def text_detect_CRAFT(image_path,
                      craft_config,
                      net_craft,
                      sortbb=True,
                      visual_img=True):
    img = loadImage(image_path)
    bboxes, polys, score_text = craft_text_detect(img, craft_config, net_craft)

    if sortbb:
        polys = sorting_bounding_box(polys)
    if visual_img:
        img = visual(img, polys)

    return img, bboxes, polys, score_text
Beispiel #37
0
def stylize(args):
    device = torch.device("cuda" if args.cuda else "cpu")
    content_image = loadImage(args.content_image, scale=args.content_scale)
    content_transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255))])
    content_image = content_transform(content_image)
    content_image = content_image.unsqueeze(0).to(device)

    with torch.no_grad():
        style_model = transformNet()
        state_dict = torch.load(args.model)
        style_model.load_state_dict(state_dict)
        style_model.to(device)
        generate = style_model(content_image).cpu()
    saveImage(args.generate_image, generate[0])
    print("generate image saved as", args.generate_image)
Beispiel #38
0
    def loadTileSet(self):
        self.TILE_X = 0
        self.TILE_Y = 0
        self.ROW_LEN = None

        for tile in self.tile_ribbon.inner_frame.winfo_children():
            tile.setImage(None)

        loaded_tileset = loadImage(self.controller.getTileSet())
        self.controller.setTileSet(loaded_tileset)

        tileset_width, tileset_height = loaded_tileset.size
        self.controller.setTileSetWidth(tileset_width)
        self.controller.setTileSetHeight(tileset_height)

        self.loadNewTiles()
Beispiel #39
0
def transfer_video(video_path,
                   style_path,
                   save_path,
                   start_frame=None,
                   end_frame=None,
                   loss_fn=losses.mse,
                   **kwargs):
    vid = utils.loadVid(video_path)
    h, w = vid.shape[2:]
    if start_frame is None: start_frame = 0
    if end_frame is None: end_frame = len(vid)
    vid = vid[start_frame:end_frame]

    style_raw = utils.loadImage(style_path)

    eta_tracker = utils.ETATracker(len(vid))
    eta_tracker.start()
    output_frames = []

    for i in range(len(vid)):
        print('frame: {}'.format(i + 1))

        if i == 0:
            output = transfer_image(vid[i],
                                    style_raw,
                                    epochs=8,
                                    coh_loss_fn=losses.none,
                                    **kwargs)
        else:
            kwargs['frame_idx'] = i
            kwargs['prev_frame'] = utils.Img2Tensor(
                output_frames[i - 1]).to(device)
            kwargs['curr_content'] = utils.Img2Tensor(vid[i]).to(device)
            kwargs['prev_content'] = utils.Img2Tensor(vid[i - 1]).to(device)

            output = transfer_image(vid[i],
                                    style_raw,
                                    epochs=8,
                                    coh_loss_fn=loss_fn,
                                    **kwargs)

        output_frames.append(output)

        eta_tracker.timestamp()

    utils.saveVid(save_path, np.array(output_frames))
Beispiel #40
0
 def __init__(self, _engine):
     super(Editor, self).__init__(_engine)
     self.side = utils.loadImage('data/gfx/side.png')
     self._background = pygame.Surface((self._resx, self._resy))
     self._background.blit(self.side, (self._resx - 232, self._resy - 1500))
     self.surface = self._background.copy()
     self._level = utils.loadLevel('data/level.dat') or [[
         [Field((x, y)) for x in xrange(MAP_SIZE)] for y in xrange(MAP_SIZE)
     ]]
     self._map = Map(_engine, self, self._level, True)
     self._cursor = Cursor(_engine, self._map)
     self._minimap = Minimap(_engine, self._map)
     self._tiles = TilesGrid(_engine, self, self._map)
     self._menu = EditorMenu(_engine, self)
     self._submodules = (self._map, self._minimap, self._tiles, self._menu,
                         self._cursor)
     self._refresh = True
Beispiel #41
0
	def __init__(self, _engine, _hero):
		super(StatusBar, self).__init__()
		self._engine = _engine
		self._hero = _hero
		self.screenUpdated()
		self.images = {
			'background': utils.loadImage('data/gfx/healthmanabar.png', alpha = True),
			'mask': utils.loadImage('data/gfx/healthmanamask.png', alpha = True),
			'fireon': utils.loadImage('data/gfx/fireon.png', alpha = True),
			'fireoff': utils.loadImage('data/gfx/fireoff.png', alpha = True),
			'iceon': utils.loadImage('data/gfx/iceon.png', alpha = True),
			'iceoff': utils.loadImage('data/gfx/iceoff.png', alpha = True),
			'healon': utils.loadImage('data/gfx/healon.png', alpha = True),
			'healoff': utils.loadImage('data/gfx/healoff.png', alpha = True),
		}

		self._before = ((0, 0, 0), (0, 0, 0))
		self._life = (0, 0)
		self._mana = (0, 0)
		self._spell = None
Beispiel #42
0
    def __init__(self):
        """
        no gui stuff yet, finishing the core components
        """

        self.ROOT_DIR = os.path.dirname(sys.argv[0])
        self.IMG_DIR = os.path.join(self.ROOT_DIR, "images")
        self.DATA_DIR = os.path.join(self.ROOT_DIR, "database")
        self.dbm = DataBaseManager(self.DATA_DIR)        
        
        pygame.init()
        pygame.font.init()
        
        self.MAIN_SCREEN = pygame.display.set_mode(self.SCREEN_SIZE)
        self.MAIN_SCREEN_RECT = self.MAIN_SCREEN.get_rect()

        self.openingImage,self.openingImageRect = loadImage(self.IMG_DIR, "GrocerySpy.jpg")

        self.MAIN_SCREEN.blit(self.openingImage,
                         (self.MAIN_SCREEN_RECT.centerx - self.openingImageRect.width /2,
                          self.MAIN_SCREEN_RECT.centery - self.openingImageRect.height /2))

        ## make button here
        startButton = Button(self.IMG_DIR, "textButton", (300,475), "menu", -1)
        startButton.addText("Start Here")

        # add that button to the list
        self.buttonGroup = Group(startButton)
        self.windowGroup = Group()

        self.state = "prestart"
        self.stateChanged = False

        # set key repeats for scrolling windows
        pygame.key.set_repeat(20, 20)

        self.groceryList = GroceryList()

        # variable for storing the state of the browseAll window if it is left
        self.toggledRecipeNames = []

        self.controlHeld = False
        self.pasteDelayReset = 1000
        self.pasteDelay = self.pasteDelayReset
Beispiel #43
0
    def __init__(self, _engine, _hero):
        super(StatusBar, self).__init__()
        self._engine = _engine
        self._hero = _hero
        self.screenUpdated()
        self.images = {
            'background': utils.loadImage('data/gfx/healthmanabar.png',
                                          alpha=True),
            'mask': utils.loadImage('data/gfx/healthmanamask.png', alpha=True),
            'fireon': utils.loadImage('data/gfx/fireon.png', alpha=True),
            'fireoff': utils.loadImage('data/gfx/fireoff.png', alpha=True),
            'iceon': utils.loadImage('data/gfx/iceon.png', alpha=True),
            'iceoff': utils.loadImage('data/gfx/iceoff.png', alpha=True),
            'healon': utils.loadImage('data/gfx/healon.png', alpha=True),
            'healoff': utils.loadImage('data/gfx/healoff.png', alpha=True),
        }

        self._before = ((0, 0, 0), (0, 0, 0))
        self._life = (0, 0)
        self._mana = (0, 0)
        self._spell = None
Beispiel #44
0
 def test_recognition_1(self):
     img_name = 'paper-title.jpg'
     img = loadImage(img_name)
     ocr.text_detection_results = ocr.text_detect(img, self.det_net, self.det_args)
     # check that 23 boxes are found in this input image
     self.assertEqual(len(ocr.text_detection_results['bboxes']), 23)
     # get crops from bounding boxes and input image
     bboxes = ocr.text_detection_results['bboxes']
     crops = {}
     for k, v in bboxes.items():
         bbox_coords = v.split(',')
         min_x = (int)(bbox_coords[0])
         min_y = (int)(bbox_coords[1])
         max_x = (int)(bbox_coords[4])
         max_y = (int)(bbox_coords[5])
         crops[k] = img[min_y:max_y, min_x:max_x, :]
     recognition_results = ocr.recognize(crops, self.rec_args, self.rec_net)
     self.assertEqual(len(recognition_results), 23)
     self.assertEqual(recognition_results['crop0']['result'], 'endtoend')
def main(status):

    if status == 'generate':
        generateDatasets(dataset_name, n_train, n_valid, n_test)
        main('train')
    elif status == 'train':
        model_name = md.train(dataset_name, batch_size=512, debug=False)
        main('evaluate')
        pass
    elif status == 'evaluate':
        model = md.loadModel(model_path)
        dataset = ds.loadDataset(dataset_path + dataset_name + '/' + test_file)
        for path, y in zip(dataset['path'], dataset['y']):
            img = utils.loadImage(path)
            p = model.predict(img[None, :, :, :], batch_size=1)
            print(p, y)
            p = p[0]
            y_pred = [[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]]
            img_dbg = drawPoints(img, y_pred, colors)
            utils.showImage(img_dbg)
    pass
Beispiel #46
0
def scan():
    session, inputs, seq_len, input_keep_prob, decoded, log_prob = init()
    need_ocr_images = utils.loadImage(os.path.join(curr_dir, 'test', '1.jpg'),
                                      0)
    ocr_text_groups = []
    for idx, images_group in enumerate(need_ocr_images):
        # if idx != 1: continue
        ocr_texts = []

        # 取最大宽度做为本组的统一输入长度
        widths = [image.shape[1] for image in images_group]
        maxImageWidth = max(widths) + 5

        ocr_inputs = np.zeros(
            [len(images_group), maxImageWidth, ocr.image_height])
        for i, image in enumerate(images_group):
            # image = utils.dropZeroEdges(image)
            # utils.show(utils.dropZeroEdges(image))
            utils.save(image,
                       os.path.join(curr_dir, "test", "%s-%s.png" % (idx, i)))
            image_vec = utils.img2vec(image, ocr.image_height, maxImageWidth)
            ocr_inputs[i, :] = np.transpose(
                image_vec.reshape((ocr.image_height, maxImageWidth)))
            # utils.show(image)
            # return
        ocr_seq_len = np.ones(ocr_inputs.shape[0]) * maxImageWidth

        feed = {inputs: ocr_inputs, seq_len: ocr_seq_len, input_keep_prob: 1.0}
        print("starting ocr inputs %s ..." % idx)
        start = time.time()
        decoded_list = session.run(decoded[0], feed)
        seconds = round(time.time() - start, 2)
        print("filished ocr inputs %s, paid %s seconds" % (idx, seconds))
        detected_list = ocr.decode_sparse_tensor(decoded_list)
        for detect_number in detected_list:
            ocr_texts.append(ocr.list_to_chars(detect_number))

        ocr_text_groups.append(ocr_texts)
        # break
    return ocr_text_groups
Beispiel #47
0
		def __init__(self, _grid, _logic, _image = 'data/gfx/field.png', _showModifiers = False):
			"""_grid - pozycja na siatce, _logic - logika pola, _image - scieżka do obrazka, _showModifiers - czy rysować reprezentacje modyfikatora."""

			super(Field.Sprite, self).__init__()
			self.image = utils.loadImage(_image)
			self.modifiers = {
				MODIFIER_HERO: utils.loadImage('data/gfx/hero/sign.png', alpha = True),
				MODIFIER_SPIDER: utils.loadImage('data/gfx/spider/sign.png', alpha = True),
				MODIFIER_SKELETON: utils.loadImage('data/gfx/skeleton/sign.png', alpha = True),
				MODIFIER_MAGE: utils.loadImage('data/gfx/mage/sign.png', alpha = True),
				MODIFIER_TROLL: utils.loadImage('data/gfx/troll/sign.png', alpha = True),
				MODIFIER_BLOCKED: None,
				MODIFIER_ITEM: utils.loadImage('data/gfx/sack.png', alpha = True),
			}

			self._logic = _logic
			self._grid = _grid
			self._showModifiers = _showModifiers
			self._refresh = True
			self.rect = self.image.get_rect()
			self.rect.center = _grid[0] * 32 + 16, _grid[1] * 32 + 16
Beispiel #48
0
def loadDatasetGenerators(name, batch_size=default_batch_size):  # return generator
    basepath = datasets_path + name + '/'
    train_dataset = loadDataset(basepath + trainfile)
    valid_dataset = loadDataset(basepath + validfile)

    train_size = len(train_dataset['path'])
    valid_size = len(valid_dataset['path'])
    # print(train_dataset.keys())

    sample = utils.loadImage(train_dataset['path'][0])
    sample_shape = sample.shape
    sample_type = type(sample[0][0][0])

    info = {
        'n_train':train_size,
        'n_train_batch': math.ceil(train_size/batch_size),
        'n_valid':valid_size,
        'n_valid_batch': math.ceil(valid_size/batch_size),
        'input_shape': sample_shape,
        'data_type': sample_type
    }

    return datasetGenerator(train_dataset, batch_size), datasetGenerator(valid_dataset, batch_size), info
Beispiel #49
0
 def __init__(self, filename, fieldlimits, border, useWeave):
     self.original = utils.loadImage(filename)
     self.original = utils.scaleToMax(wall, self.original)
     #Note that because self.data is an image it has a member called shape that contains its dimensions.
     self.data = self.original #myFilter(self.original)
     assert len(self.data.shape)==2, "Maze data is not two-dimensional: %s. Are you sure it is grayscale and contains one layer and one canal only?" % str(self.data.shape)
     self.data_grad = utils.getOriginalGradient(filename, maze=-self.data)
     self.border = border
     self.density = densityArray(self.data.shape, fieldlimits)
     self.buildBorders(self.original)
     self.fieldlimits = fieldlimits
     self.walls_only = np.zeros_like(self.data)
     self.buildBorders(self.walls_only)
     self.walls_only_gr = np.gradient(self.walls_only)
     
     self.validgrad = np.ones(self.data.shape, dtype=np.bool_)
     
     self.minidx = 0
     self.maxidx = self.data.shape[0]-1
     
     if useWeave:
         self.getGradients = self.getGradientsCpp
     else:
         self.getGradients = self.getGradientsPython 
Beispiel #50
0
def getNextSingleChannelImageBatch(samples,
                                   species_map,
                                   channel_index,
                                   augment=False):
    for chunk in getDatasetChunk(samples):
        x_batch = np.zeros((stg.BATCH_SIZE, 1, 64, 64), dtype=np.uint8)
        y_batch = np.zeros((stg.BATCH_SIZE, len(species_map.keys())))
        species_ids_batch = np.zeros(stg.BATCH_SIZE)
        glc_ids_batch = np.zeros(stg.BATCH_SIZE)
        current_batch_slot = 0

        for sample in chunk:
            x = loadImage(sample)
            x = x[channel_index]
            if (augment):
                if np.random.random_sample() > 0.5:
                    x = flipImage(x)
                if np.random.random_sample() > 0.5:
                    x = rotateImage(x, 90)
                if np.random.random_sample() > 0.5:
                    x = cropSingleChannelImage(x)
            y = np.zeros(len(species_map.keys()))
            y[species_map[sample[2]]] = 1

            x_batch[current_batch_slot] = x
            y_batch[current_batch_slot] = y
            species_ids_batch[current_batch_slot] = sample[2]
            glc_ids_batch[current_batch_slot] = sample[1]
            current_batch_slot += 1

        x_batch = x_batch[:current_batch_slot]
        y_batch = y_batch[:current_batch_slot]
        species_ids_batch = species_ids_batch[:current_batch_slot]
        glc_ids_batch = glc_ids_batch[:current_batch_slot]

        yield x_batch, y_batch, species_ids_batch, glc_ids_batch
Beispiel #51
0
	def __init__(self, _grid, _modifier):
		"""_grid - pozycja pola na siatce, _modifier - modyfikator."""

		super(Modifier, self).__init__()
		self.images = {
			MODIFIER_HERO: utils.loadImage('data/gfx/hero/sign.png', alpha = True),
			MODIFIER_SPIDER: utils.loadImage('data/gfx/spider/sign.png', alpha = True),
			MODIFIER_SKELETON: utils.loadImage('data/gfx/skeleton/sign.png', alpha = True),
			MODIFIER_MAGE: utils.loadImage('data/gfx/mage/sign.png', alpha = True),
			MODIFIER_TROLL: utils.loadImage('data/gfx/troll/sign.png', alpha = True),
			MODIFIER_ITEM: utils.loadImage('data/gfx/sack.png', alpha = True),
		}

		self._grid = _grid
		self._pos = _grid[0] * 32 + 16, _grid[1] * 32 + 16
		self._modifier = _modifier
		self.image = self.images[_modifier]
		self.rect = self.image.get_rect()
		self.rect.center = _grid[0] * 32 + 16, _grid[1] * 32 + 16
Beispiel #52
0
    def __init__(self, imgFolder, mode, loc, ident, colorKey = None):
        pygame.sprite.Sprite.__init__(self)

        self.identity = ident
        
        if mode == "textButton": ## red Box
            self.image, self.rect = loadImage(imgFolder, "redButton.png", colorKey)
        elif mode == "expandButton": ## horizontal expandButton
            self.image,self.rect = loadImage(imgFolder, "arrow_buttonHorizontal.gif", colorKey)
        elif mode == "unExpandButton": ## vertical expandButton
            self.image,self.rect = loadImage(imgFolder, "arrow_buttonVertical.gif", colorKey)
        elif mode == "addToGroceryListButton": ## shopping cart button
            self.image,self.rect = loadImage(imgFolder, "shoppingCart.png", colorKey)
        elif mode == "removeFromGroceryListButton": ##
            self.image,self.rect = loadImage(imgFolder, "shoppingCartAdded.png", colorKey)
        elif mode == "backButton":
            self.image,self.rect = loadImage(imgFolder, "backButton.png", colorKey)
        elif mode == "checkBox":
            self.image,self.rect = loadImage(imgFolder, "checkBox.png", colorKey)
        
            
            
        self.rect.topleft = loc
        self.active = True
Beispiel #53
0
	def __init__(self, _grid, _freeobjs, _hero):
		super(RightHandCell, self).__init__(_grid, _freeobjs)
		self.image = utils.loadImage('data/gfx/handcell.png', alpha = True)
		self._hero = _hero
Beispiel #54
0
	def __init__(self, _grid, _hero):
		super(StrengthCell, self).__init__(_grid)
		self.image = utils.loadImage('data/gfx/strengthcell.png', alpha = True)
		self._hero = _hero
		self._before = 0
		utils.drawText(self.image, "Sila", 9, (0, 0, 0), (16, 6))
Beispiel #55
0
	def __init__(self, _grid, _hero):
		super(IntelligenceCell, self).__init__(_grid)
		self.image = utils.loadImage('data/gfx/intelligencecell.png', alpha = True)
		self._hero = _hero
		self._before = 0
		utils.drawText(self.image, "Inteligencja", 9, (0, 0, 0), (16, 6))
Beispiel #56
0
import sys
import pygame
import version
sys.path.append('./data')
import engine
from menu import Menu, ResolutionButton, FullscreenButton, ExitButton
from scene import NewGameButton
from editor import EditorButton
import utils

if __name__ == '__main__':
	pygame.init()
	pygame.mixer.init()
	pygame.display.set_caption(version.NAME + ' v' + version.VERSION)
	_engine = engine.Engine(len(sys.argv) > 1 and sys.argv[1] == '--debug') # --debug aby włączyć tryb testowy(pokazuje które części ekranu się odświeżają)
	pygame.display.set_icon(utils.loadImage('data/gfx/cursor/attack.png', alpha = True))
	_engine.addModule(Menu(_engine, (
		NewGameButton(_engine), # Nowa gra
		EditorButton(_engine), # Edytor
		ResolutionButton(_engine), # Rozdzielczosc
		FullscreenButton(_engine), # Pelny ekran/okno
		ExitButton(_engine), # Wyjscie
	)))
	_engine.activateModule('Menu')
	try:
		_engine.run()

	except KeyboardInterrupt:
		pass
Beispiel #57
0
	def __init__(self, _engine, _editor, _map):
		"""_engine - obiekt silnika, _editor - obiekt edytora, _map - obiekt mapy."""

		super(TilesGrid, self).__init__()
		self.images = {
			'hover': utils.loadImage('data/gfx/hover.png', alpha = True),
			'normal': utils.loadImage('data/gfx/normal.png', alpha = True),
		}

		self._engine = _engine
		self._editor = _editor
		self._map = _map
		self._layer = HoverLayer(_map, True)
		self._map.addLayer('ToolHover', 5, self._layer)
		self._clicked = None
		self._hover = None
		self._updated = []
		self.screenUpdated()
		self.surface = pygame.Surface((192, 312))
		self.surface.fill((1, 5, 4))
		self.surface.set_colorkey((1, 5, 4))
		self._tool = Tool(_editor, _map)
		self._toolHover = HoverLayer.Sprite()
		self._layer.add('tool', self._toolHover)
		_tiles = ( # dostępne kafelki
			field.Field,
			wall.WallTopLeft, wall.WallTopRight, wall.WallBottomLeft, wall.WallBottomRight, wall.WallHorizontal, wall.WallVertical,
			stairs.StairsUpNorth, stairs.StairsDownNorth, stairs.StairsUpSouth, stairs.StairsDownSouth, stairs.StairsUpWest, stairs.StairsDownWest, stairs.StairsUpEast, stairs.StairsDownEast,
			trap.TrapMoveArrow, trap.TrapMoveFire, trap.TrapMoveIce, trap.TrapTouchArrow, trap.TrapTouchFire, trap.TrapTouchIce,
			chest.ChestNorth, chest.ChestSouth, chest.ChestWest, chest.ChestEast,
		)

		_modifiers = (field.MODIFIER_HERO, field.MODIFIER_SPIDER, field.MODIFIER_SKELETON, field.MODIFIER_MAGE, field.MODIFIER_TROLL)

		# Kafelki
		utils.drawText(self.surface, "Kafelki", 22, (255, 255, 255), (96, 10))
		self._tiles = pygame.sprite.Group()
		for y in xrange(5):
			for x in xrange(5):
				tile = _tiles[y * 5 + x]
				tile = tile.Sprite((x, y), tile)
				tile.rect.center = tile.rect.centerx + x * 8, tile.rect.centery + y * 8 + 20
				self._tiles.add(tile)

		self._tiles.draw(self.surface)
		for tile in self._tiles:
			self.surface.blit(self.images['hover'], tile.rect.topleft)
			self.surface.blit(self.images['normal'], tile.rect.topleft)

		# Modyfikatory
		utils.drawText(self.surface, "Modyfikatory", 22, (255, 255, 255), (96, 225))
		self._modifiers = pygame.sprite.Group()
		for x in xrange(5):
			modifier = field.Modifier((x, 0), _modifiers[x])
			modifier.rect.center = modifier.rect.centerx + x * 8, modifier.rect.centery + 240
			self._modifiers.add(modifier)

		self._modifiers.draw(self.surface)
		for tile in self._modifiers:
			self.surface.blit(self.images['hover'], tile.rect.topleft)
			self.surface.blit(self.images['normal'], tile.rect.topleft)
Beispiel #58
0
	def __init__(self, _engine):
		super(Scene, self).__init__(_engine)
		self.side = utils.loadImage('data/gfx/side.png')
		self._background = pygame.Surface((self._resx, self._resy))
		self._background.blit(self.side, (self._resx - 232, self._resy - 1500))
		self.surface = self._background.copy()
		self._actual = []
		self._level = utils.loadLevel('data/level.dat')
		self._map = Map(_engine, self, self._level)
		self._minimap = Minimap(_engine, self._map)
		self._cursor = Cursor(_engine, self._map)
		self._creatureLayer = CreatureLayer(self._map, self._cursor) # Warstwa potworów
		self._map.addLayer('Creatures', 2, self._creatureLayer)
		self._map.addLayer('Missiles', 3, MissilesLayer(self._map)) # Warstwa pocisków(strzał, kuli ognia itp.)
		self._shadow = ShadowLayer(self._map)
		self._map.addLayer('Shadow', 5, self._shadow) # Mgła wojny
		self._monsters = []
		self._freeobjects = pygame.sprite.Group() # Wolne obiekty na scenie
		_counter = 0
		_start = 0
		# szukanie bohatera w lochu
		for l, storey in enumerate(self._level):
			for row in storey:
				for cell in row:
					if cell.getModifier() & field.MODIFIER_HERO:
						self._hero = hero.Hero(self._map, cell.getGrid() + (l,))
						self._hero.move((0, 0, 0))
						self._map.switchStorey(l)
						_start = l
						self._creatureLayer.add('hero', self._hero.getSprite(self._creatureLayer, 'hero'))
						break

		# szukanie potworów
		for l, storey in enumerate(self._level):
			for row in storey:
				for cell in row:
					if cell.getModifier() & field.MODIFIER_SPIDER:
						_monster = Spider(self._map, cell.getGrid() + (l,))
						self._monsters.append(('spider', _monster))
						if l == _start:
							self._creatureLayer.add('spider_' + str(_counter), _monster.getSprite(self._creatureLayer, 'spider_' + str(_counter)))
							self._actual.append(('spider_' + str(_counter), _monster))
							_monster.move((0, 0, 0))
							_counter += 1

					elif cell.getModifier() & field.MODIFIER_SKELETON:
						_monster = Skeleton(self._map, cell.getGrid() + (l,))
						self._monsters.append(('skeleton', _monster))
						if l == _start:
							self._creatureLayer.add('skeleton_' + str(_counter), _monster.getSprite(self._creatureLayer, 'skeleton_' + str(_counter)))
							self._actual.append(('skeleton_' + str(_counter), _monster))
							_monster.move((0, 0, 0))
							_counter += 1

					elif cell.getModifier() & field.MODIFIER_MAGE:
						_monster = Mage(self._map, cell.getGrid() + (l,))
						self._monsters.append(('mage', _monster))
						if l == _start:
							self._creatureLayer.add('mage_' + str(_counter), _monster.getSprite(self._creatureLayer, 'mage_' + str(_counter)))
							self._actual.append(('mage_' + str(_counter), _monster))
							_monster.move((0, 0, 0))
							_counter += 1

					elif cell.getModifier() & field.MODIFIER_TROLL:
						_monster = Troll(self._map, cell.getGrid() + (l,))
						self._monsters.append(('troll', _monster))
						if l == _start:
							self._creatureLayer.add('troll_' + str(_counter), _monster.getSprite(self._creatureLayer, 'troll_' + str(_counter)))
							self._actual.append(('troll_' + str(_counter), _monster))
							_monster.move((0, 0, 0))
							_counter += 1

		if not self._hero:
			raise Exception('Brak bohatera w lochu!?')

		self._statusbar = StatusBar(_engine, self._hero) # pasek życia/many itp. / statusu
		self.inventory = Inventory(_engine, self._hero, self._hero.inventory, self._freeobjects)
		self.chestitems = ChestItems(_engine, self._hero, self._freeobjects)
		self._submodules = (self._map, self._minimap, self._statusbar, self.inventory, self.chestitems, self._cursor)
		self._play = True
		self._refresh = True
Beispiel #59
0
	def __init__(self, _grid, _hero):
		super(AgilityCell, self).__init__(_grid)
		self.image = utils.loadImage('data/gfx/agilitycell.png', alpha = True)
		self._hero = _hero
		self._before = 0
		utils.drawText(self.image, "Zrecznosc", 9, (0, 0, 0), (16, 6))
Beispiel #60
0
    def show(self):
        if not self._play:
            self._engine.previousModule()
            return

        try:
            self._last = time.time()
            while self._engine.tick():
                _upd = self._client.update(.5/self._engine.options['fps'])
                if self._play and _upd != True:
                    utils.drawText(self.surface, _upd, 20, (255, 255, 255), (self._resx / 2, self._resy / 2))
                    self._play = False
                    self._engine.show(self.surface)
                    time.sleep(5)
                    self._engine.previousModule()
                    raise SceneQuit()

                if self._client.countdown:
                    if not self._map:
                        self._loadMap(self._client.countdown.mapSize.x, self._client.countdown.mapSize.y)

                    if self._playerID == None:
                        self._playerID = self._client.countdown.playerId

                    self.surface = self._background.copy()
                    utils.drawText(self.surface, 'Gracz %d. >%d<' % (self._client.countdown.playerId, self._client.countdown.number), 30, (255, 255, 255), (self._resx / 2, self._resy / 2))
                    self._engine.show(self.surface)
                    continue

                if self._client.result:
                    utils.drawText(self.surface, 'Gra zakonczona!', 40, (255, 255, 255), (self._resx / 2, self._resy / 2))
                    if len(self._client.result.winners) == 1:
                        utils.drawText(self.surface, 'Wygral gracz %d!' % self._client.result.winners[0], 40, (255, 255, 255), (self._resx / 2, self._resy / 2 + 40))

                    elif len(self._client.result.winners):
                        utils.drawText(self.surface, 'Wygrali gracze %s!' % (', '.join([str(i) for i in self._client.result.winners])), 40, (255, 255, 255), (self._resx / 2, self._resy / 2 + 40))

                    self._play = False
                    self._engine.show(self.surface)
                    time.sleep(10)
                    self._engine.previousModule()
                    raise SceneQuit()

                if self._client.map:
                    if not self._map:
                        self._engine.previousModule()
                        self._play = False
                        raise SceneQuit()

                    for mine in self._client.map.mines:
                        _id = mine.position.x, mine.position.y
                        if not self._mineLayer.get(_id):
                            _mine = ObjectsLayer.Sprite(utils.loadImage('data/gfx/bomb.png', alpha = True))
                            self._mineLayer.add(_id, _mine)
                            self._mineLayer.move(_id, _id)

                    for _id, player in enumerate(self._client.map.playersPositions):
                        if not self._heroLayer.get(_id):
                            self._heroLayer.add(_id, ObjectsLayer.Sprite(utils.loadImage('data/gfx/hero/n.png', alpha = True)))

                        _hero = self._heroLayer.get(_id)
                        _pos = _hero.getPos()
                        self._heroLayer.move(_id, (player.x, player.y))
                        _newpos = _hero.getPos()
                        if _pos[0] > _newpos[0]:
                            _hero.changeImage(utils.loadImage('data/gfx/hero/w.png', alpha = True))

                        if _pos[0] < _newpos[0]:
                            _hero.changeImage(utils.loadImage('data/gfx/hero/e.png', alpha = True))

                        if _pos[1] > _newpos[1]:
                            _hero.changeImage(utils.loadImage('data/gfx/hero/n.png', alpha = True))

                        if _pos[1] < _newpos[1]:
                            _hero.changeImage(utils.loadImage('data/gfx/hero/s.png', alpha = True))

                        if _id == self._playerID:
                            _, _, w, h = self._map.getRectangle()
                            self._map.setShift((w / 2 - _newpos[0], h / 2 - _newpos[1]))

                for event in self._engine.events():
                    if event.type == QUIT:
                        raise engine.EngineQuit()

                    if event.type == KEYDOWN:
                        if event.key == K_ESCAPE:
                            self._engine.previousModule()
                            raise SceneQuit()

                        if event.key in (K_w, K_UP):
                            self._client.sendAction('u')
                            self._last = time.time()

                        elif event.key in (K_s, K_DOWN):
                            self._client.sendAction('d')
                            self._last = time.time()

                        elif event.key in (K_a, K_LEFT):
                            self._client.sendAction('l')
                            self._last = time.time()

                        elif event.key in (K_d, K_RIGHT):
                            self._client.sendAction('r')
                            self._last = time.time()

                        elif event.key in (K_RETURN, K_RCTRL, K_LCTRL):
                            self._client.sendAction('c')
                            self._last = time.time()

                        elif event.key == K_q:
                            self._client.sendAction('e')
                            self._last = time.time()

                if self._last + 1./self._engine.options['fps'] < time.time():
                    self._client.sendAction('m')
                    self._last = time.time()

                self.surface = self._background.copy()
                if not self._map:
                    utils.drawText(self.surface, 'Oczekiwanie na graczy!', 20, (255, 255, 255), (self._resx / 2, self._resy / 2))

                updated = []
                for submodule in self._submodules:
                    updated.extend(submodule.update())
                    submodule.draw(self.surface)

                if self._refresh:
                    self._engine.show(self.surface)
                    self._refresh = False

                else:
                    self._engine.show(self.surface, updated)

        except SceneQuit:
            pass