def addToDataset(self, path, label=None, dataFile='', labelFile=''): """ adds a set of image matches to train_data based on a log file of labelled matches :param path: the path to the matches log :param label: an integer np_array representing the label. When not given defaults to the labels given in the log file :param dataFile: the path to optionally save the data object to :param labelFile: the path to optionally save the label object to :return: None """ imLoader = ImageLoader(path, image_size=self.img_dims) if (self.data.shape[0] == 0): self.data = imLoader.train_set if (label != None): entries = self.data.shape[0] self.labels = np.vstack([label] * entries) else: self.labels = imLoader.label_set else: self.data = np.concatenate((self.data, imLoader.train_set), 0) entries = imLoader.train_set.shape[0] if (label != None): self.labels = np.concatenate( (self.labels, np.vstack([label] * entries)), 0) else: self.labels = np.concatenate((self.labels, imLoader.label_set), 0) imLoader.closeFile() if dataFile != '' and labelFile != '': np.save(open(dataFile, 'wb'), self.data) np.save(open(labelFile, 'wb'), self.labels)
def load_batch(self,path): ''' Loading a image batch ''' batch_loader = ImageLoader() return batch_loader.load_image(path)
def epilepsy_mode(self): root = Tkinter.Tk() root.geometry('+%d+%d' % (100,100)) old_label_image = None loader = ImageLoader("../testImages") loader.start() while True: try: image1 = loader.get() root.geometry('%dx%d' % (image1.size[0],image1.size[1])) tkpi = ImageTk.PhotoImage(image1) root.geometry('%dx%d' % (image1.size[0],image1.size[1])) label_image = Tkinter.Label(root, image=tkpi) label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1]) if old_label_image is not None: old_label_image.destroy() old_label_image = label_image root.update() # time.sleep(1) except Exception, e: print "Something got f****d up:", e pass
def test_images_are_resized(self): loader = ImageLoader() loader.load_from(imageLocation, 1) images = loader.get_images() for image in images: self.assertEqual('(30, 30, 3)', str(image.shape))
def openFile(self): filename = tk.filedialog.askopenfilename() imageLoader = ImageLoader() image = imageLoader.get_image(filename) model = RoadSignModel() model.load('./models/fullset-10epochs.h5') category = model.predict_class(image) print('Category =', self.sign_name(category - 1)) self.category.set(category)
def xtest_TrainModel(self): imageLoader = ImageLoader() imageLoader.load_from('./test-images', 1) model = RoadSignModel(imageLoader) self.assertEqual(False, model.is_trained()) model.train() self.assertEqual(True, model.is_trained())
def test_SaveModel(self): imageLoader = ImageLoader() imageLoader.load_from('./test-images', 1) model = RoadSignModel(imageLoader) os.remove('model.h5') model.train() model.save() self.assertEqual(True, os.path.exists('model.h5'))
def loadAssets(self): """Game class method to load all assets. """ #loading assets (images, sounds) self.imageLoader = ImageLoader(self) self.soundLoader = snd.Sound() try: self.imageLoader.load_assets() self.soundLoader.load() except Exception: traceback.print_exc() self.running = False
def recycle(self, image: ImageInfo): existing_image = self.db.get_by_hash(image.hash) if existing_image: prune_hash = ImageLoader.hash_file(image.path.as_posix()) existing_hash = ImageLoader.hash_file( existing_image.path.as_posix()) if prune_hash == existing_hash: self.logger.info(f"Deleting {image}") self.logger.info(f" Matches {existing_image}") os.remove(image.path) time.sleep(0.1) return self.logger.debug(f"Recycling {image}") self.sort_to(self.recycle_dir, image, False)
def find_better(cls, image1: ImageInfo, image2: ImageInfo): pixels1 = image1.width * image1.height pixels2 = image2.width * image2.height is_hdr1 = ImageLoader.is_hdr(image1.exif) is_hdr2 = ImageLoader.is_hdr(image2.exif) if pixels1 == pixels2 and (is_hdr1 or is_hdr2): if is_hdr1: return image1 else: return image2 elif pixels1 >= pixels2: return image1 else: return image2
def __init__(self, filename_image, viewportSize_imageScaled, matrix=QtGui.QMatrix()): # These variables are needed later to handle rescaling. self.rescale_info = PreFetcher.RescaleInfo() if isinstance(filename_image, QtGui.QPixmap) \ and isinstance(viewportSize_imageScaled, QtGui.QPixmap): self.image = filename_image self.image_scaled = viewportSize_imageScaled self.from_loader = False self.to_rescale = False elif (isinstance(filename_image, QtCore.QString) or \ isinstance(filename_image, str)) \ and isinstance(viewportSize_imageScaled, QtCore.QSize): self.loader = ImageLoader(filename_image, viewportSize_imageScaled, matrix) self.loader.start() self.from_loader = True self.to_rescale = False else: msg = 'Incorrect PreFetcher contructor: ' + \ str(type(filename_image)) + ', ' + \ str(type(viewportSize_imageScaled)) raise InternalException(msg)
def main(): image_loader = ImageLoader(3) images = image_loader.get_next_image_batch() print (len(images)) print (images[0].get_label()) print (images[-1].get_label()) pink = [] tiel = [] for i in images: if (i.get_label() == "cockatiel"): tiel.append(i) elif (i.get_label() == "pink_cockatoo"): pink.append(i) print (len(pink)) print (len(tiel))
def startLoading_(self, sender): self.startLoadingButton.setEnabled_(False) loader = ImageLoader(self.selectedPath, self.setNameTextField.stringValue(), self.groupByColorCheckbox.state() == NSOnState, self) self.worker = ImageLoaderWorker(loader) self.worker.daemon = True self.worker.start()
def __init__(self, input_PIL_img, lib_Lab_vectors, photoLog, cellLog, subimage, progress=0): # Set instance variables self.input = input_PIL_img self.photoLog = photoLog # The photoLog, cellLog, and progress should probably be in it's own information expert self.cellLog = cellLog self.progress = int(progress) self.ImgAnalyzer = ImageAnalyzer() self.ImgFinder = ImageFinder(lib_Lab_vectors) self.ImgLoader = ImageLoader() self.subimage = subimage
def __init__(self): pygame.init() self.window = pygame.display.set_mode(WINDOWDIMS) pygame.display.set_caption("BLOODHELL") self.font = pygame.font.SysFont('Comic Sans MS', 48) self.pauseText = self.font.render("Game Paused", False, WHITE) self.clock = pygame.time.Clock() self.states = {'titleScreen': True, 'controlScreen': False, 'gameRunning': False, 'pause': False, 'gameOver': False} self.running = True self.titleScreenImage = pygame.transform.scale(pygame.image.load("assets//title_screen.png").convert(), WINDOWDIMS) self.controlScreenImage = pygame.transform.scale(pygame.image.load("assets//control_screen.png").convert(), WINDOWDIMS) self.endScreenImage = pygame.transform.scale(pygame.image.load("assets//end_screen.png").convert(), WINDOWDIMS) self.input = {'closeGame': False} ImageLoader.loadImages() return
def sort_file(self, path: Path): self.logger.info(f"Processing FILE {path}") path = self.cleanup_filename(path) incoming_image = ImageLoader.load(path) existing_image = self.find_existing(incoming_image.hash) if not existing_image: self.move_to_sorted(incoming_image) else: self.logger.info( f"Found match for incoming image {incoming_image}") self.logger.info(f" With existing image {existing_image}") self.keep_better(existing_image, incoming_image)
def get(self, userId, photoId): # Get Access Token and Photo URL from header access_token = self.request.headers["access-token"] photo_url = self.request.headers["photo-url"] # Load PIL image from facebook url im = ImageLoader().load_url_image(photo_url) # Crop image to a square cols, rows = im.size # Landscape Layout (or Square) if cols >= rows: target_cols = rows left = (cols-target_cols)/2 right = left+target_cols im = im.crop( (left, 0, right, rows) ) # Portrait Layout else: target_rows = cols upper = (rows-target_rows)/2 lower = upper+target_rows im = im.crop( (0, upper, cols, lower) ) # Analyze image imgAnalyzer = ImageAnalyzer() cols, rows = im.size labVec = imgAnalyzer.getLABVector(im, 0, 0, cols, rows) # Store the Lab Vector into the Google Datastore ImageDatastore().set_Lab_vector(userId, photoId, labVec) # Prepare JSON response json_response = json.dumps( {"success": True, "photoId": photoId}, indent=4) # Write JSON response self.response.headers['Content-Type'] = 'application/json' self.response.write(json_response)
def reload(self, path: Path): self.logger.info(f"Reloading {path}") reloaded = ImageLoader.load(path) existing = self.db.get_by_hash(reloaded.hash) if existing and existing.path != path: self.logger.warning(f"Reloaded image: {reloaded}") self.logger.warning(f" Matches existing: {existing}") better = self.find_better(reloaded, existing) if better == reloaded: self.db.remove(existing) self.recycle(existing) else: self.db.remove(reloaded) self.recycle(reloaded) self.db.add(reloaded)
def run_model(self, writer, set_path, preload_epoch, epoch, training=False, shuffle=False, pretrain=False): if not training: print('VALIDATION') image_loader = ImageLoader(batch_size=2, image_dir=set_path) if shuffle: image_loader.shuffle_data() batch_gen = image_loader.getImages() for i, (batch_x, batch_y) in enumerate(batch_gen): subbatch = 100 feed = { 'tf_x:0': batch_x, 'tf_y:0': batch_y, 'tf_training:0': training } if (i % subbatch == 0): print('batch ' + str(i) + '/' + str(image_loader.batch_count)) loss = self.sess.run(self.merged, feed_dict=feed) writer.add_summary(loss) if (training and i % 1000 == 0): self.save(epoch=preload_epoch + epoch) if (not pretrain): _ = self.sess.run('train_op_disc', feed_dict=feed) _ = self.sess.run('train_op', feed_dict=feed) else: loss, _ = self.sess.run([self.mse_loss_summ, 'train_mse_op'], feed_dict=feed) writer.add_summary(loss)
def accuracy(self, net, path, epoch, phase, device, log_path, batch_size=64, do_logwrite=False): try: os.makedirs(log_path) except OSError: pass category = path.split('/')[-1] + "_" + phase with torch.no_grad(): transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, ), (0.5, )) # Normalize [-1, 1] ]) dataset = ImageLoader(path, phase, transforms=transform) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False) correct = 0 for idx, (images, labels) in enumerate(data_loader): images = images.to(device) labels = labels.to(device) outputs = net(images) _, pred_y = torch.max(outputs.data, 1) correct += (pred_y == labels).sum().item() accuracy = (correct / len(dataset)) * 100 print('phase:%s --- correct [%d/%d] acc: %.2f%%' % (category, correct, len(dataset), accuracy)) if do_logwrite: f = open('%s/%s_log.txt' % (log_path, category), 'a') f.write('epoch:%d, phase:%s --- correct [%d/%d] %.4f%%\n' % (epoch, phase, correct, len(dataset), accuracy)) f.close() return accuracy
def keep_incoming(self, existing_image: ImageInfo, incoming_image: ImageInfo): self.logger.info(f"Deleting existing: {existing_image}") self.logger.info(f" Keeping incoming: {incoming_image}") if existing_image.path.name.lower().endswith( ".jpg" ) and existing_image.ts > OLD_TS and existing_image.ts < incoming_image.ts: self.logger.info( f" But preserving existing's exif: {existing_image}") try: piexif.transplant(existing_image.path.as_posix(), incoming_image.path.as_posix()) except ValueError as e: self.logger.warning(f"Failed to transplant exif: {e}") incoming_image = ImageLoader.load(incoming_image.path) self.db.remove(existing_image) self.recycle(existing_image) self.move_to_sorted(incoming_image)
def __InitUI(self): ImageLoader.LoaderInit() Navigation.NavigationInit() self.__buttons = [] self.__ids = [] self.__menubar = wx.MenuBar() self.__fileMenu = wx.Menu() self.__fileItemQ = self.__fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application') self.__fileItemL = self.__fileMenu.Append(wx.ID_OPEN, 'Load', 'Load application') self.__menubar.Append(self.__fileMenu, '&File') self.__frame.SetMenuBar(self.__menubar) self.__frame.Bind(wx.EVT_MENU, self.OnQuit, self.__fileItemQ) self.__frame.Bind(wx.EVT_MENU, self.__world.Load, self.__fileItemL) self.__panel = wx.Panel(self.__frame) self.__panel.SetBackgroundColour("white") self.__vbox = wx.BoxSizer(wx.VERTICAL) self.__hbox = wx.BoxSizer(wx.HORIZONTAL) self.__st1 = wx.StaticText(self.__panel, label='Set border dimensions') self.__tc = wx.TextCtrl(self.__panel) self.__hbox.Add(self.__st1, flag=wx.RIGHT, border=8) self.__hbox.Add(self.__tc, proportion=1) self.__vbox.Add(self.__hbox, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=10) self.__btn = wx.Button(self.__panel, wx.ID_STOP, 'Done', (70, 30)) self.__vbox.Add(self.__btn, flag=wx.ALIGN_CENTRE | wx.TOP, border=30) self.__frame.Bind(wx.EVT_BUTTON, self.__Done, id=wx.ID_STOP) self.__panel.SetSizer(self.__vbox)
def __init__(self): t = ImageGrab.grab().convert("RGB") self.screen = cv2.cvtColor(numpy.array(t), cv2.COLOR_RGB2BGR) self.ultLoader = ImageLoader('image/ult/') if self.have('topleft'): tl = self._imageLoader.get('topleft') res = cv2.matchTemplate(self.screen, tl, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) x1, y1 = max_loc rd = self._imageLoader.get('rightdown') res = cv2.matchTemplate(self.screen, rd, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) x2, y2 = max_loc # default 989 GameStatus().y = y2 - y1 GameStatus().use_Droid4X = True
def FRR(self, net, path, device, log_path, batch_size=64, do_logwrite=False): try: os.makedirs(log_path) except OSError: pass with torch.no_grad(): transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, ), (0.5, )) # Normalize [-1, 1] ]) dataset = ImageLoader(path, "Real", transforms=transform) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False) wrong = 0 for idx, (images, labels) in enumerate(data_loader): images = images.to(device) labels = labels.to(device) outputs = net(images) _, pred_y = torch.max(outputs.data, 1) wrong += (pred_y != labels).sum().item() metric = (wrong / len(dataset)) * 100 print_log = '%s --- pos(real) -> neg(fake) Wrong [%d/%d] FRR: %.2f%%' % ( "FRR", wrong, len(dataset), metric) print(print_log) if do_logwrite: f = open('%s/%s_log.txt' % (log_path, "test_"), 'a') f.write(print_log) f.close() return metric
def test_load_images_from_two_categories(self): numberOfImages = 60 loader = ImageLoader() loader.load_from(imageLocation, 2) images = loader.get_images() labels = loader.get_labels() self.assertEqual(numberOfImages, len(images)) self.assertIs(np.ndarray, type(images)) self.assertIs(np.ndarray, type(images[0])) np.testing.assert_array_equal(np.zeros(30), labels[:30]) np.testing.assert_array_equal(np.ones(30), labels[30:numberOfImages]) self.assertIs(np.ndarray, type(labels))
def test_load_images_from_one_category(self): numberOfImages = 30 loader = ImageLoader() loader.load_from(imageLocation, 1) images = loader.get_images() labels = loader.get_labels() self.assertEqual(numberOfImages, len(images)) self.assertIs(np.ndarray, type(images)) self.assertIs(np.ndarray, type(images[0])) np.testing.assert_array_equal(np.zeros(numberOfImages), labels) self.assertIs(np.ndarray, type(labels))
def __init__(self): self.currentProgram = 'menu' # Current main loop WIDTH, HEIGHT = 720,406 # Output video quality self.clock = pygame.time.Clock() self.timerController = TimerController() self.renderer = Renderer(WIDTH, HEIGHT) self.imageLoader = ImageLoader() self.soundController = SoundController('bgMusic.ogg',[('cutSpell',0.1),('lightingSpell',0.1),('explosionSpell',0.1)],0.05) self.mouseController = MouseController() self.menu = Menu(self.imageLoader.imageStorage['menu'],self) self.player = Player((WIDTH, HEIGHT),self.imageLoader.imageStorage["player"],[(0,2),(2,5),(5,8),(8,11),(11,14),(14,22),(22,37)]) self.spellController = SpellController(self.mouseController,self.imageLoader.imageStorage,self.renderer, self.player,self.soundController) self.amountBars = AmountBars(self.player, None, self.imageLoader.imageStorage['bars'],(WIDTH//2,HEIGHT//2)) self.boss = None self.level = None self.playerMovement = None
def main(): "main function" # optional command line args parser = argparse.ArgumentParser() parser.add_argument('--train', help='train the NN', action='store_true') parser.add_argument('--validate', help='validate the NN', action='store_true') args = parser.parse_args() # train or validate on IAM dataset if args.train or args.validate: # load training data, create TF model loader = ImageLoader(FilePaths.fnTrain, Model.batchSize, Model.imgSize, Model.maxTextLen) # save characters of model for inference mode open(FilePaths.fnCharList, 'w').write(str().join(loader.charList)) # save words contained in dataset into file open(FilePaths.fnCorpus, 'w').write( str(' ').join(loader.trainWords + loader.validationWords)) # execute training or validation if args.train: model = Model(loader.charList) train(model, loader) elif args.validate: model = Model(loader.charList, mustRestore=True) validate(model, loader) # infer text on test image else: print(open(FilePaths.fnAccuracy).read()) model = Model(open(FilePaths.fnCharList).read(), mustRestore=True) derive(model, FilePaths.fnDerive, contrast=False)
class PreFetcher(): class RescaleInfo: def __init__(self): self.rescale_path = None self.rescale_viewport_size = None self.rescale_matrix = None def __init__(self, filename_image, viewportSize_imageScaled, matrix=QtGui.QMatrix()): # These variables are needed later to handle rescaling. self.rescale_info = PreFetcher.RescaleInfo() if isinstance(filename_image, QtGui.QPixmap) \ and isinstance(viewportSize_imageScaled, QtGui.QPixmap): self.image = filename_image self.image_scaled = viewportSize_imageScaled self.from_loader = False self.to_rescale = False elif (isinstance(filename_image, QtCore.QString) or \ isinstance(filename_image, str)) \ and isinstance(viewportSize_imageScaled, QtCore.QSize): self.loader = ImageLoader(filename_image, viewportSize_imageScaled, matrix) self.loader.start() self.from_loader = True self.to_rescale = False else: msg = 'Incorrect PreFetcher contructor: ' + \ str(type(filename_image)) + ', ' + \ str(type(viewportSize_imageScaled)) raise InternalException(msg) def get_images(self): if self.from_loader: self.loader.join() self.image = QtGui.QPixmap.fromImage(self.loader.image) self.image_scaled = QtGui.QPixmap.fromImage(self.loader.image_scaled) self.from_loader = False if self.to_rescale: self.image_scaled = scale_and_rotate_image( self.image, self.rescale_info.rescale_path, self.rescale_info.rescale_viewport_size, self.rescale_info.rescale_matrix) self.to_rescale = False return (self.image, self.image_scaled) def get_rotated_image(self, path, matrix=QtGui.QMatrix()): (image, _) = self.get_images() return rotate_image(image, path, matrix) def rescale(self, path, viewport_size, matrix=QtGui.QMatrix()): self.to_rescale = True self.rescale_info.rescale_path = path self.rescale_info.rescale_viewport_size = viewport_size self.rescale_info.rescale_matrix = matrix def set_image(self, new_image): if not self.from_loader: self.image = new_image def set_scaled_image(self, new_image): if not self.from_loader: self.image_scaled = new_image
import sys from ImageLoader import ImageLoader from ClusteringHandler import ClusteringHandler from HTMLCreator import HTMLCreator from ClustersPrinter import ClustersPrinter import constants as c if len(sys.argv) < 2: print("Please pass a path to a file containing image paths list") else: paths_file = sys.argv[1] images = ImageLoader.load_images(paths_file) clustered_images = ClusteringHandler.cluster(images) HTMLCreator.create_html(c.HTML_TEMPLATE, c.HTML_OUTPUT, clustered_images=clustered_images, clusters_count=len(clustered_images)) ClustersPrinter.print_clusters_to_file(clustered_images, c.FILE_OUTPUT)
def __init__(self, parent=None): super(MinesweeperGUI, self).__init__(parent) self.benchmarking = False self.setCentralWidget(QWidget(self)) self.setWindowTitle(" Unreal Minesweeper ") #Menu menubar = self.menuBar() benchMenu = menubar.addMenu(" Benchmark ") newGameMenu = menubar.addMenu(" Game ") helperMenu = menubar.addMenu(" Helper ") solverMenu = menubar.addMenu(" Solver ") debugMenu = menubar.addMenu(" Debug ") ''' Benchmark menu ''' benchmarkProbasV1 = QAction(" Benchmark probabilistic algorithm v1", self) benchmarkProbasV1.triggered.connect(self.runBenchmarkProbasV1) benchMenu.addAction(benchmarkProbasV1) ''' Game menu ''' newGameEasy = QAction(" Easy (8x8 + 10 mines) ", self) newGameIntermediate = QAction(" Intermediate (16x16 + 40 mines) ", self) newGameHard = QAction(" Expert (30x16 + 99 mines) ", self) newGameEasy.triggered.connect(lambda: self.newGame(8, 8, 10)) newGameIntermediate.triggered.connect(lambda: self.newGame(16, 16, 40)) newGameHard.triggered.connect(lambda: self.newGame(30, 16, 99)) newGameMenu.addAction(newGameEasy) newGameMenu.addAction(newGameIntermediate) newGameMenu.addAction(newGameHard) '''layout.addWidget(QPushButton(" Probabilistic solver : next step")) layout.addWidget(QPushButton(" Probabilistic solver : auto-solve")) layout.addWidget(QPushButton(" CSP Solver : next step ")) layout.addWidget(QPushButton(" CSP Solver : auto-solve "))''' ''' Helper menu ''' helpers = QActionGroup(self, exclusive=True) self.helperNone = helpers.addAction( QAction(" No help !", self, checkable=True, checked=True)) self.helperNone.triggered.connect(self.setHelper) helperMenu.addAction(self.helperNone) self.helperProba = helpers.addAction( QAction(" Probabilistic approach ", self, checkable=True)) self.helperProba.triggered.connect(self.setHelper) helperMenu.addAction(self.helperProba) self.helperCSP = helpers.addAction( QAction(" CSP approach ", self, checkable=True)) self.helperCSP.triggered.connect(self.setHelper) helperMenu.addAction(self.helperCSP) ''' Helper menu ''' self.verboseDisplay = QAction(" Verbose display ", self, checkable=True) self.verboseDisplay.triggered.connect(self.setDebug) debugMenu.addAction(self.verboseDisplay) ''' Solver menu ''' solverOneStep = QAction(" Solve next step ", self) solverOneStep.triggered.connect(self.solveNextStep) solverAllStep = QAction(" Solve all game ", self) solverAllStep.triggered.connect(self.solveAllStep) solverMenu.addAction(solverOneStep) solverMenu.addAction(solverAllStep) ImageLoader.init() self.mainLayout = None self.setStatus(" Ready to play ! ")
class Photomosaic: # Variables total_rows = 0 total_cols = 0 progress = 0 photoLog = [] cellLog = [] photos = {} subimage = {} # Convenience objects ImgAnalyzer = None ImgFinder = None ImgLoader = None # The input image to analyze input = None input_grid_width = 0 input_grid_height = 0 input_cell_width = 0 input_cell_height = 0 # The output photomosiac based on the input image output = None output_mag = 1 output_grid_width = 0 output_grid_height = 0 output_cell_width = 0 output_cell_height = 0 # Constructor def __init__(self, input_PIL_img, lib_Lab_vectors, photoLog, cellLog, subimage, progress=0): # Set instance variables self.input = input_PIL_img self.photoLog = photoLog # The photoLog, cellLog, and progress should probably be in it's own information expert self.cellLog = cellLog self.progress = int(progress) self.ImgAnalyzer = ImageAnalyzer() self.ImgFinder = ImageFinder(lib_Lab_vectors) self.ImgLoader = ImageLoader() self.subimage = subimage # Calculate all of the closests photos in the photomosaic def calculate_photomosaic(self, rows, cols): # Initialize input image self._input_dims(int(rows), int(cols)) # Find the initial coordinates row = int(len(self.cellLog) / self.total_cols) col = int(len(self.cellLog) % self.total_cols) x0 = col*self.input_cell_width y0 = row*self.input_cell_height # Traverse the cells, and call "_process_cell" for each one of them self._traverse_cells(self._process_cell, x0, y0) # Create the photomosiac - currently only works with a square (rows=cols) def create_photomosaic(self, rows, cols, mag): # Initialize input and output images self._input_dims(int(rows), int(cols)) self._output_dims(float(mag)) # Find the initial coordinates to start pasting cells row = int(self.progress / self.total_cols) col = int(self.progress % self.total_cols) x0 = col*self.input_cell_width y0 = row*self.input_cell_height # Traverse the cells, and call "_paste_cell" for each one of them self._traverse_cells(self._paste_cell, x0, y0) # Return the ouput image as a base64 encoded string return self.base64() # Return the output image as a base64 encoded string def base64(self): file = StringIO() self.output.save(file, "png") return b64encode(file.getvalue()) # Traverse the cells def _traverse_cells(self, fnc_process_cell, x0=0, y0=0): for y in range(y0, self.input_grid_height, self.input_cell_height): if y != y0: x0 = 0 # Only start in the middle of the grid on the first iteration for x in range(x0, self.input_grid_width, self.input_cell_width): fnc_process_cell(x, y) self.progress += 1 # Analyze the input cell, find the best match, and add it to the cell log def _process_cell(self, x0, y0): labVec = self.ImgAnalyzer.getLABVector(self.input, x0, y0, self.input_cell_width, self.input_cell_height) closest_photoId = self.ImgFinder.closest_match(labVec) self.cellLog.append(closest_photoId) # Download the image and paste it into the output image def _paste_cell(self, x0, y0): # Translate the x and y coordinates into a cellLog index and find the photoId row = int(y0/self.input_cell_height) col = int(x0/self.input_cell_width) cellLogIndex = row*self.total_cols + col photoId = self.cellLog[cellLogIndex] # Get the image associated with the photo if photoId in self.photos: # We already have the image, so grab it from the dictionary closest_img = self.photos[photoId] else: # We haven't previously downloaded the image, so get it from Facebook closest_img = self.ImgLoader.load_url_image(self._get_url(photoId)) # Crop the image and resize it into a square closest_img = self._crop_resize_square(closest_img) # Add the image to the photos dictionary self.photos[photoId] = closest_img # Now that the image has been found, paste it into the corresponding output cell self.output.paste( closest_img, (col*self.output_cell_width, row*self.output_cell_height) ) # Returns the URL associated with the photoId def _get_url(self, photoId): for log in self.photoLog: if log["photoId"] == photoId: return log["url"] else: return None # Crop the image into a square and resize it to the output cell size def _crop_resize_square(self, im): cols, rows = im.size # Landscape Layout (or Square) if cols >= rows: target_cols = rows left = (cols-target_cols)/2 right = left+target_cols return im.transform( (self.output_cell_width, self.output_cell_height), Image.EXTENT, (left, 0, right, rows) ) # Portrait Layout else: target_rows = cols upper = (rows-target_rows)/2 lower = upper+target_rows return im.transform( (self.output_cell_width, self.output_cell_height), Image.EXTENT, (0, upper, cols, lower) ) # Defines input dimensions def _input_dims(self, rows, cols): # Since number of columns is the width and number of rows is height self.input_grid_width = self.subimage["w"] self.input_grid_height = self.subimage["h"] self.total_rows = int(rows) self.total_cols = int(cols) self.input_grid_width -= self.input_grid_width % self.total_cols self.input_grid_height -= self.input_grid_height % self.total_rows self.input_cell_width = self.input_grid_width / self.total_cols self.input_cell_height = self.input_grid_height / self.total_rows # Crop Image self.input = self.input.crop( (self.subimage["x"], self.subimage["y"], self.subimage["x"]+self.input_cell_width*self.total_cols, self.subimage["y"]+self.input_cell_height*self.total_rows) ) # Defines output dimensions and creates output image def _output_dims(self, mag): # Set dimensions self.output_mag = float(mag) self.output_grid_width = int(self.input_grid_width * self.output_mag) self.output_grid_height = int(self.input_grid_height * self.output_mag) self.output_grid_width -= self.output_grid_width % self.total_cols self.output_grid_height -= self.output_grid_height % self.total_rows self.output_cell_width = self.output_grid_width / self.total_cols self.output_cell_height = self.output_grid_height / self.total_rows # Create output image self.output = Image.new("RGB", (self.output_grid_width, self.output_grid_height), "red")
class Screen(metaclass=Singleton): _delay = 0.3 _imageLoader = ImageLoader('image/') _skills = ImageLoader('image/skills/') target = ImageLoader('./', need_scale=False) @staticmethod def log(text): GameStatus().window.add_text(text) def __init__(self): t = ImageGrab.grab().convert("RGB") self.screen = cv2.cvtColor(numpy.array(t), cv2.COLOR_RGB2BGR) self.ultLoader = ImageLoader('image/ult/') if self.have('topleft'): tl = self._imageLoader.get('topleft') res = cv2.matchTemplate(self.screen, tl, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) x1, y1 = max_loc rd = self._imageLoader.get('rightdown') res = cv2.matchTemplate(self.screen, rd, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) x2, y2 = max_loc # default 989 GameStatus().y = y2 - y1 GameStatus().use_Droid4X = True def get_cards(self): self.capture() GameStatus().cards = [] GameStatus().cards += self.find_list('buster') GameStatus().cards += self.find_list('art') GameStatus().cards += self.find_list('quick') def get_current_level(self): c33 = self.chances_of('3_3') c23 = self.chances_of('2_3') c31 = self.chances_of('1_3') if c33 > max(c23, c31): self.log('3-3') return 3 elif c23 > max(c33, c31): self.log('2-3') return 2 else: self.log('1-3') return 1 def find_list(self, name): cards = [] res = cv2.matchTemplate(self.screen, self._imageLoader.get(name), cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = numpy.where(res >= threshold) x = 0 t = sorted(zip(*loc[::-1])) for pt in t: if abs(x - pt[0]) > 100 or x == 0: x = pt[0] cards.append((pt[0], pt[1])) else: continue self.log(name + ': ' + str(len(cards))) return cards def set_delay(self, delay): self._delay = delay def capture(self): t = ImageGrab.grab().convert("RGB") self.screen = cv2.cvtColor(numpy.array(t), cv2.COLOR_RGB2BGR) @staticmethod def _click(x, y): handle = win32gui.GetForegroundWindow() x_old, y_old = win32api.GetCursorPos() # see https://github.com/asweigart/pyautogui/issues/23 try: pyautogui.click(x, y, 1) except FileNotFoundError: pass win32api.SetCursorPos((x_old, y_old)) win32gui.SetForegroundWindow(handle) def click_on(self, name, repeat=False, loader=_imageLoader): if GameStatus().game_stage == GameStage.Stopped: return self.log('try click ' + name) p = loader.get(name) max_val = 0 x, y = 0, 0 while max_val < 0.8: if GameStatus().game_stage == GameStage.Stopped: return self.capture() res = cv2.matchTemplate(self.screen, p, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) self.log(name + ' ' + str(max_val)) x, y = max_loc time.sleep(self._delay) m, n, q = p.shape x += n / 2 y += m / 2 self._click(x, y) max_val = 1 if repeat else 0 while max_val > 0.8: if GameStatus().game_stage == GameStage.Stopped: return time.sleep(1) self.capture() res = cv2.matchTemplate(self.screen, p, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if max_val > 0.8: self._click(x, y) def have(self, name, loader=_imageLoader): return self.chances_of(name, loader) > 0.8 def chances_of(self, name, loader=_imageLoader): self.capture() p = loader.get(name) res = cv2.matchTemplate(self.screen, p, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) self.log('chances of ' + name + ': ' + str(max_val)) return max_val
T_B_GRAPH_PATH = './graph/' + args.save_model + NOWTIME BATCH_SIZE = args.batchsize LEARNING_RATE = 0.0001 NUM_EPOCHS = args.maxepoch is_write_sub_log = False transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, ), (0.5, )) # Normalize [-1, 1] ]) # train data set: image 1 x 57 x 116 train_dataset = ImageLoader(TRAIN_DATASET_PATH, transforms=transform) # data loader: batch_size x 1 x 57 x 116 train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True) # data set: image 1 x 57 x 116 test_dataset = ImageLoader(TEST_DATASET_PATH, transforms=transform) # data loader: batch_size x 1 x 57 x 116 test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False) # Network if args.model == "Ann": net = Ann(node=args.node, num_classes=2).to(device) # Real or Fake
class Game: """This class is main Game class. """ def __init__(self): """__init__ method for Game class. """ # initialise game window, settings etc. pygame.mixer.pre_init(44100, -16, 2, 2048) pygame.mixer.init() pygame.init() pygame.mouse.set_visible(False) pygame.key.set_repeat(10, cfg.KEY_DELAY) self.actual_screen = pygame.display.set_mode( (cfg.S_WIDTH, cfg.S_HEIGHT)) #self.actual_screen = pygame.display.set_mode((cfg.S_WIDTH, cfg.S_HEIGHT), pygame.FULLSCREEN) self.screen = pygame.Surface((cfg.WIDTH, cfg.HEIGHT)) self.clock = pygame.time.Clock() self.running = True self.loaded = False self.dircheck = None # booleans for drawing the hit rects and other debug stuff self.debug = False self.draw_vectors = False self.show_player_stats = False self.caption = '' self.key_down = None self.state = 'GAME' self.in_transition = False self.loadAssets() self.clearcount = 0 self.check = True self.timer = 0 self.levelcleared = 1 self.pistolpick = True self.machinegunpick = False self.lastweapon = 'MachineGun' self.spritecheck = [] def keyDown(self, events, game): """Game class method for checking keys presses. Args: events (<Event>): key press events. game (Integrate.Game): Integrate.Game class object. """ for event in events: if event.type == pygame.KEYUP: if event.key == cfg.KEY_RIGHT: game.player.RightCheck = False if event.key == cfg.KEY_UP: game.player.UpCheck = False if event.key == cfg.KEY_LEFT: game.player.LeftCheck = False if event.key == cfg.KEY_DOWN: game.player.DownCheck = False def transitRoom(self, game, dungeon, offset=pygame.math.Vector2(0, 0)): """Game class method for room transition. Args: game (Integrate.Game): Integrate.Game class object. dungeon (Dungeon.Dungeon): Dungeon.Dungeon object """ # get the index of the next and the previous room index_next = dungeon.current_room_index index_prev = game.prev_room # select the rooms based on the indices room_prev = dungeon.room_matrix[index_prev[0]][index_prev[1]] room_next = dungeon.room_matrix[index_next[0]][index_next[1]] # remove all sprite from the previous room room_prev.object_data = [] for sprite in game.all_sprites: if sprite != game.player and sprite not in game.item_drops: if hasattr(sprite, 'data'): room_prev.object_data.append(sprite.data) sprite.kill() if room_next.visited == False: # if room not visited, get the object data from the initial layout data = room_next.layout for d in data: try: if offset == (0, 0): self.create(game, d) else: self.create(game, d, offset) except Exception: traceback.print_exc() pass room_next.visited = True else: # if room already visited, get the objects from the stored data data = room_next.object_data for d in data: try: if offset == (0, 0): self.create(game, d) else: self.create(game, d, offset) except Exception: traceback.print_exc() pass # set the dungeon's current room based on room index dungeon.room_current = dungeon.room_matrix[ dungeon.current_room_index[0]][dungeon.current_room_index[1]] def create(self, game, data, offset=pygame.math.Vector2(0, cfg.GUI_HEIGHT)): """Game class method for room transition. Args: game (Integrate.Game): Integrate.Game class object. data (dict{'id', 'name', 'x', 'y', 'width', 'height'}): objects data """ # takes a dictionary of sprite properties name = data['name'] # capitalizing first letter name_1 = name[0].capitalize() name_2 = name[1:] name = name_1 + name_2 #instantiate the sprite spr = module_dict[name](game, (data['x'] + offset.x, data['y'] + offset.y), (data['width'], data['height'])) for key, value in data.items(): try: setattr(spr, key, value) except: print('cant set value of {0} for {1}'.format(key, spr)) if hasattr(spr, 'on_create'): # do initialisation stuff after ___init__() spr.on_create() spr.data = data def loadAssets(self): """Game class method to load all assets. """ #loading assets (images, sounds) self.imageLoader = ImageLoader(self) self.soundLoader = snd.Sound() try: self.imageLoader.load_assets() self.soundLoader.load() except Exception: traceback.print_exc() self.running = False def new(self): """Game class method to start a new game. """ # start a new game # initialise sprite groups self.all_sprites = pygame.sprite.LayeredUpdates() self.walls = pygame.sprite.LayeredUpdates() self.gui = pygame.sprite.LayeredUpdates() self.enemies = pygame.sprite.LayeredUpdates() self.item_drops = pygame.sprite.LayeredUpdates() # instantiate dungeon self.dungeon = Dungeon(self, cfg.DUNGEON_SIZE) if self.loaded: self.dungeon.tileset = self.saveGame.data['tileset'] else: self.dungeon.create() self.WSign = self.imageLoader.WarnSign self.WSign2 = self.imageLoader.WarnSign2 self.inventory = Inventory(self) # spawn the player in the middle of the room self.player = Player(self, (cfg.WIDTH // 2, cfg.TILESIZE * 12)) self.currentpistol = Pistol(self, self.player) self.currentmachine = MachineGun(self, self.player) if self.pistolpick == True: self.player.itemA = self.currentpistol elif self.machinegunpick == True: self.player.itemA = self.currentmachine # load settings if self.loaded: self.loadSavefile() # spawn the new objects (invisible) self.prev_room = self.dungeon.current_room_index self.transitRoom(self, self.dungeon) # create a background image from the tileset for the current room self.background = self.tileRoom(self, self.imageLoader.tileset, self.dungeon.current_room_index) self.run() def checkFight(self, game): """Game class method to check distance from door and closes the doors and opens them when player defeats all enemies in the room """ room = game.dungeon.room_current if len(game.enemies) > 0: room.cleared = False else: if not room.is_doors_shut: room.cleared = True return # check if the room's doors are closed if room.is_doors_shut == False: # check player's position margin_x = 5 * cfg.TILESIZE_SMALL margin_y = 5.5 * cfg.TILESIZE_SMALL + cfg.GUI_HEIGHT rect = pygame.Rect((margin_x, margin_y), (cfg.WIDTH - 2 * margin_x, cfg.HEIGHT - cfg.GUI_HEIGHT - margin_y)) if rect.colliderect(game.player.hit_rect): # player is far enough in the room to shut the doors room.shut_doors() game.soundLoader.get['roomLocked'].play() else: if len(game.enemies) == 0: # if all enemies are defeated, open the doors room.open_doors() game.soundLoader.get['roomCleared'].play() room.cleared = True def get_inputs(self, game): """Game class method to load all assets store keyboard inputs in a key map """ game.keys = { 'A': False, 'B': False, 'X': False, 'Y': False, 'L': False, 'BACK': False, 'START': False, 'STICK_L_PRESSED': False, 'STICK_R_PRESSED': False, 'STICK_R': pygame.math.Vector2(0, 0), 'STICK_L': pygame.math.Vector2(0, 0), 'DPAD': pygame.math.Vector2(0, 0), 'DPAD_MENU': pygame.math.Vector2(0, 0) } key = game.keys # get keyboard keys get_keys = pygame.key.get_pressed() if get_keys[cfg.KEY_RIGHT]: game.player.RightCheck = True elif get_keys[cfg.KEY_LEFT]: game.player.LeftCheck = True if get_keys[cfg.KEY_DOWN]: game.player.DownCheck = True elif get_keys[cfg.KEY_UP]: game.player.UpCheck = True get_mkeys = pygame.mouse.get_pressed() key['A'] = get_mkeys == cfg.KEY_A or key['A'] key['B'] = game.key_down == cfg.KEY_B or key['B'] key['X'] = game.key_down == cfg.KEY_ENTER or key['X'] key['START'] = get_keys[cfg.KEY_MENU] def run(self): """Game class method to start running infinite loop until quit. """ # game loop self.playing = True while self.playing: #reset game screen self.screen = pygame.Surface((cfg.WIDTH, cfg.HEIGHT)) self.dt = self.clock.tick(cfg.FPS) / 1000 self.events() self.get_inputs(self) self.update() self.draw() def events(self): """Game class method to loop game events. """ # game loop events self.event_list = pygame.event.get() for event in self.event_list: if event.type == pygame.QUIT: if self.playing: self.playing = False self.running = False pygame.quit() quit() if event.type == pygame.KEYDOWN: # Key events if event.key == pygame.K_r and self.debug: self.loaded = False self.new() if event.key == pygame.K_h: self.debug = not self.debug if event.key == pygame.K_k and self.debug: # kill all enemies for e in self.enemies: e.hp = 0 def screenWrap(self, player, dungeon): """Game class method to check if the player goes outside the screen if they do, set their new position based on where they went """ index = list(dungeon.current_room_index) direction = '' new_pos = pygame.math.Vector2(player.hit_rect.center) if player.hit_rect.left < cfg.TILESIZE: direction = (-1, 0) player.vel = pygame.math.Vector2(0, 0) new_pos.x = cfg.WIDTH - player.hit_rect.width - cfg.TILESIZE index[1] -= 1 elif player.hit_rect.right > cfg.WIDTH - cfg.TILESIZE: player.vel = pygame.math.Vector2(0, 0) direction = (1, 0) new_pos.x = player.hit_rect.width + cfg.TILESIZE index[1] += 1 elif player.hit_rect.top < cfg.GUI_HEIGHT + cfg.TILESIZE: player.vel = pygame.math.Vector2(0, 0) direction = (0, -1) new_pos.y = cfg.HEIGHT - player.hit_rect.height - cfg.TILESIZE index[0] -= 1 elif player.hit_rect.bottom > cfg.HEIGHT - cfg.TILESIZE: player.vel = pygame.math.Vector2(0, 0) direction = (0, 1) new_pos.y = player.hit_rect.height + cfg.GUI_HEIGHT + cfg.TILESIZE index[0] += 1 try: return direction, index, new_pos except Exception: traceback.print_exc() def update(self): """Game class method update game situation. """ if self.pistolpick == True: self.player.itemA = self.currentpistol elif self.machinegunpick == True: self.player.itemA = self.currentmachine if self.debug: self.caption = (str(round(self.clock.get_fps(), 2))) else: self.caption = cfg.TITLE pygame.display.set_caption(self.caption) # check for key presses self.key_down = self.keyDown(self.event_list, self) if self.state == 'GAME': pygame.mouse.set_visible(False) self.all_sprites.update() self.inventory.update() # check for room transitions on screen exit (every frame) self.direction, self.new_room, self.new_pos = self.screenWrap( self.player, self.dungeon) if self.direction == UP: self.dircheck = UP elif self.direction == DOWN: self.dircheck = DOWN elif self.direction == LEFT: self.dircheck = LEFT elif self.direction == RIGHT: self.dircheck = RIGHT if self.new_room != self.dungeon.current_room_index: self.prev_room = self.dungeon.current_room_index self.dungeon.current_room_index = self.new_room self.state = 'TRANSITION' # When in a fight, shut the doors: if not self.dungeon.room_current.cleared: self.checkFight(self) if self.check: if self.dungeon.room_current.cleared: a = self.clearcount self.clearcount = self.clearcount + 1 self.spritecheck = [] if a + 1 == self.clearcount: self.check = False elif self.state == 'MENU' or self.state == 'MENU_TRANSITION': pygame.mouse.set_visible(True) self.inventory.update() elif self.state == 'TRANSITION': #self.RoomTransition(self.new_pos, self.direction) # ^this went into draw() pass elif self.state == 'CUTSCENE': self.walls.update() def WinSit(self): """Game class method to check if player won then show next screen. """ global Dx, Dy if self.dungeon.room_current.type == "endboss" and self.dungeon.room_current.cleared: pygame.mouse.set_visible(True) self.state = 'WIN' self.actual_screen.blit(self.imageLoader.WinImg, (0, 0)) self.Quitbtn = Button(400, 450, 150, 50, 'Quit', (200, 20, 20, 0), (180, 0, 0, 0), self.imageLoader.font1, self.imageLoader.font2) self.Nextbtn = Button(200, 450, 150, 50, 'Next', (200, 20, 20, 0), (180, 0, 0, 0), self.imageLoader.font1, self.imageLoader.font2) self.Quitbtn.show(self.imageLoader.WinImg) self.Nextbtn.show(self.imageLoader.WinImg) if self.Quitbtn.is_mouse_clicked(): pygame.quit() quit() if self.Nextbtn.is_mouse_clicked(): self.levelcleared += 1 self.clearcount = 0 self.check = True cfg.DUNGEON_SIZE = (Dx, Dy) self.state = 'GAME' self.new() Dx = Dx + 1 Dy = Dy + 1 def GameOverr(self): """Game class method to check if player is dead and game is over. """ global Dx, Dy if self.player.Dead == True: self.state = 'GAME OVER' pygame.mouse.set_visible(True) self.actual_screen.blit(self.imageLoader.GameOverImg, (0, 0)) self.Quitbtn = Button(400, 450, 150, 50, 'Quit', (200, 20, 20, 0), (180, 0, 0, 0), self.imageLoader.font1, self.imageLoader.font2) self.Nextbtn = Button(200, 450, 150, 50, 'Restart', (200, 20, 20, 0), (180, 0, 0, 0), self.imageLoader.font1, self.imageLoader.font2) self.Quitbtn.show(self.imageLoader.GameOverImg) self.Nextbtn.show(self.imageLoader.GameOverImg) if self.Quitbtn.is_mouse_clicked(): pygame.quit() quit() if self.Nextbtn.is_mouse_clicked(): self.levelcleared = 1 self.clearcount = 0 Dx = 5 Dy = 5 self.pistolpick = True self.machinegunpick = False self.check = True cfg.DUNGEON_SIZE = (Dx, Dy) self.state = 'GAME' self.new() def draw(self): """Game class method to draw """ if self.state != 'TRANSITION': # draw the background (tilemap) self.screen.blit(self.background, (0, cfg.GUI_HEIGHT)) # call additional draw methods (before drawing) for sprite in self.all_sprites: if hasattr(sprite, 'draw_before'): sprite.draw_before() # draw the sprites self.all_sprites.draw(self.screen) for sprite in self.all_sprites: if hasattr(sprite, 'draw_after'): sprite.draw_after() # for machine gun with player if self.machinegunpick and self.player.itemA == self.currentmachine: if self.player.itemA.check and self.player.mana < 9.8: self.WSignRect = self.WSign.get_rect() self.WSignRect.center = pygame.mouse.get_pos( ) - pygame.math.Vector2(0, 30) self.screen.blit(self.WSign, self.WSignRect) if self.player.itemA.check and self.player.mana > 9.8: self.WSignRect = self.WSign2.get_rect() self.WSignRect.center = pygame.mouse.get_pos( ) - pygame.math.Vector2(0, 30) self.screen.blit(self.WSign2, self.WSignRect) if self.player.mana < 0.2: self.cursor = self.imageLoader.CursorMain1 elif self.player.mana < 1.4: self.cursor = self.imageLoader.cursor[0] elif self.player.mana < 2.8: self.cursor = self.imageLoader.cursor[1] elif self.player.mana < 4.2: self.cursor = self.imageLoader.cursor[2] elif self.player.mana < 5.6: self.cursor = self.imageLoader.cursor[3] elif self.player.mana < 7: self.cursor = self.imageLoader.cursor[4] elif self.player.mana < 8.4: self.cursor = self.imageLoader.cursor[5] elif self.player.mana < 9.8: self.cursor = self.imageLoader.cursor[6] elif self.player.mana < 11.4: self.cursor = self.imageLoader.cursor[7] self.cursorrect = self.cursor.get_rect() self.cursorrect.center = pygame.mouse.get_pos() self.screen.blit(self.cursor, self.cursorrect) else: self.cursor = self.imageLoader.CursorMain1 self.cursorrect = self.cursor.get_rect() self.cursorrect.center = pygame.mouse.get_pos() self.screen.blit(self.cursor, self.cursorrect) else: self.RoomTransition(self.new_pos, self.direction) if not self.dungeon.room_current.cleared: self.check = True # ----- DEBUG STUFF ----- # # draw hitboxes in debug mode if self.debug: for sprite in self.all_sprites: if hasattr(sprite, 'hit_rect'): pygame.draw.rect(self.screen, cfg.CYAN, sprite.hit_rect, 1) if hasattr(sprite, 'interact_rect'): pygame.draw.rect(self.screen, cfg.GREEN, sprite.interact_rect, 1) # draw the inventory self.drawGUI() self.screen = pygame.transform.scale(self.screen, (cfg.S_WIDTH, cfg.S_HEIGHT)) self.actual_screen.blit(self.screen, (0, 0)) self.WinSit() self.GameOverr() pygame.display.update() def drawGUI(self): """Game class method draw inventory with map. """ self.inventory.map_img = self.dungeon.render_rooms_map() self.inventory.draw() def tileRoom(self, game, tileset, index): """Game class method render room tiles. """ image = pygame.Surface((cfg.WIDTH, cfg.HEIGHT - cfg.GUI_HEIGHT)) data = game.dungeon.room_matrix[index[0]][index[1]].tiles for i in range(len(data)): for j in range(len(data[i])): x = j * cfg.TILESIZE y = i * cfg.TILESIZE try: image.blit(tileset[data[i][j]], (x, y)) except Exception: traceback.print_exc() return return image def RoomTransition(self, new_pos, direction): """Game class method for room transition. Args: new_pos (tuple): tuple with x,y corrdinates for the new room for player direction (Up, DOWN, LEFT OR RIGHT): direction of start in new room """ if not self.in_transition: # store the old background image temporarily self.old_background = self.background # blit the background and sprites to prevent flickering self.screen.blit(self.old_background, (0, cfg.GUI_HEIGHT)) self.all_sprites.draw(self.screen) # build the new room self.background = self.tileRoom(self, self.imageLoader.tileset, self.dungeon.current_room_index) # scroll the new and old background # start positions for the new bg are based on the direction the # player is moving start_positions = { UP: pygame.math.Vector2(0, -(cfg.HEIGHT - cfg.GUI_HEIGHT * 2)), DOWN: pygame.math.Vector2(0, cfg.HEIGHT), LEFT: pygame.math.Vector2(-cfg.WIDTH, cfg.GUI_HEIGHT), RIGHT: pygame.math.Vector2(cfg.WIDTH, cfg.GUI_HEIGHT) } self.bg_pos1 = start_positions[direction] # pos2 is the old bg's position that gets pushed out of the screen self.bg_pos2 = pygame.math.Vector2(0, cfg.GUI_HEIGHT) self.in_transition = True self.transitRoom(self, self.dungeon, self.bg_pos1) else: if self.bg_pos1 != (0, cfg.GUI_HEIGHT): # moves the 2 room backrounds until the new background is at (0,0) # PROBLEM: Only works with certain scroll speeds! # calculate the move vector based on the direction move = (pygame.math.Vector2(0, 0) - direction) * cfg.SCROLLSPEED # move the background surfaces self.bg_pos1 += move self.bg_pos2 += move if direction == UP: self.bg_pos1.y = min(cfg.GUI_HEIGHT, self.bg_pos1.y) elif direction == DOWN: self.bg_pos1.y = max(cfg.GUI_HEIGHT, self.bg_pos1.y) elif direction == LEFT: self.bg_pos1.x = min(0, self.bg_pos1.x) elif direction == RIGHT: self.bg_pos1.x = max(0, self.bg_pos1.x) # move the sprites during transition for sprite in self.all_sprites: sprite.rect.topleft += move sprite.hit_rect.topleft += move sprite.pos += move self.screen.blit(self.old_background, self.bg_pos2) self.screen.blit(self.background, self.bg_pos1) self.all_sprites.draw(self.screen) else: # update the player's position self.player.pos = pygame.math.Vector2(new_pos) self.player.hit_rect.center = pygame.math.Vector2(new_pos) self.player.spawn_pos = pygame.math.Vector2(new_pos) self.player.rect.bottom = self.player.hit_rect.bottom # end transtition self.in_transition = False self.state = 'GAME' # blit the background and sprites to prevent flickering self.screen.blit(self.background, (0, cfg.GUI_HEIGHT)) self.all_sprites.draw(self.screen)
def write_to_file(self, filename): """ Salva os dados em um arquivo usando o loader strategy designado """ loader = ImageLoader() loader.write(self, filename)