def drawPlayState(self, player): self.screen.fill((255, 255, 255)) for column in Map.getInstance().grid: for cell in column: if len(cell.beings) != 0: self.drawCharacter(cell.beings[-1]) if cell.barrier: self.screen.blit( Images.getInstance().getImage(Sprites.KYOKO_BARRIER), pygame.Rect(cell.x * 16, cell.y * 16, 16, 16)) if isinstance(player, Homura): if player.timeStopped: self.screen.blit( Images.getInstance().getImage(Sprites.TIME_STOP_EFFECT), pygame.Rect(0, 0, 144, 144)) player.image.set_colorkey((255, 255, 255)) self.drawCharacter(player) if player.targeting is not None: targetRect = pygame.Rect(player.targetX * 16, player.targetY * 16, 16, 16) self.screen.blit( Images.getInstance().getImage(Sprites.TARGET_CURSOR), targetRect) pygame.display.flip()
def main(): Images.load_images() print("Images loaded") game_manager = GameManager() t = threading.Thread(target=game_manager.connect_clients) t.start() input()
def load_image(self, image_path): # Read the image image = Images.read(image_path) # Preprocessing image = Images.preprocess(image) self.files = [image_path] self.x = image
def save_all_3(self, update_queries, insert_queries, update_discount_queries,insert_prices_queries,update_price_queries,insert_product_sizes_queries,insert_images_queries,insert_styles_queries): print "INSERTING PRODUCTS", len(update_queries)+len(insert_queries) self.db.execute_many_updates("products", ["update_at", "description", "color", "style_line"], [["id", "="]], update_queries) self.db.execute_many_inserts("products", self.attributes+self.other_attributes+self.forgotten_attributes+["update_at", "style_line"]+["need_additional_data", "need_process"], insert_queries) product_ids = [ x[-1][0] for x in update_queries] + [ x[0][0] for x in insert_queries] product_skus = { x[5][0] : { "id": x[0][0] } for x in insert_queries } print "INSERTING PRICES", len(insert_prices_queries)+len(update_discount_queries)+len(update_price_queries) Price = Prices(self.db) Price.insert_many(insert_prices_queries) self.db.execute_many_updates("products", ["current_discount_id"], [["id", "="]], update_discount_queries) self.db.execute_many_updates("products", ["current_price_id"], [["id", "="]], update_price_queries) print "INSERTING SIZES", len(insert_product_sizes_queries) ProductSize = ProductSizes(self.db) ProductSize.insert_many(insert_product_sizes_queries) print "INSERTING IMAGES", len(insert_images_queries) Image = Images(self.db) Image.insert_many(insert_images_queries) print "INSERTING STYLES", len(insert_styles_queries) #print insert_styles_queries ProductStyle = ProductStyles(self.db) ProductStyle.insert_many(insert_styles_queries) return product_ids, product_skus
def __init__(self): Location.__init__(self) pygame.font.init() self.fontSize = 25 self.font = pygame.font.Font(None, self.fontSize) self.images = Images() self.BG = self.images.getImage("menuBG").convert() self.initButton()
def __init__(self, map, player, pointOfRespawn, generalTimer, portalWin): self.initWindow() self.player = player self.portalWin = portalWin self.image = Images() self.loadTexture(map) self.generalTimer = generalTimer self.pointofRespawn = pointOfRespawn
def add_images_3(self, product, images): Image = Images(self.db) insert_queries = [] for img in images: #if img not in current_images_urls: insert_queries.append(Image.insert_query(img, product)) #delete_queries = Image.delete_missing_pictures(product, images, current_images, query=True) return insert_queries
class Menu_Location(Location): indikator = 1 def __init__(self): Location.__init__(self) pygame.font.init() self.fontSize = 25 self.font = pygame.font.Font(None, self.fontSize) self.images = Images() self.BG = self.images.getImage("menuBG").convert() self.initButton() def initButton(self): self.startUp = self.images.getImage("startUp") self.startDown = self.images.getImage("startDown") self.exitUp = self.images.getImage("exitUp") self.exitDown = self.images.getImage("exitDown") def draw(self): self.drawBG() self.drawMenu() pygame.display.flip() def drawMenu(self): if self.indikator == 1: self.windows.blit(self.startDown, (446, 200)) self.windows.blit(self.exitUp, (446, 270)) elif self.indikator == 2: self.windows.blit(self.startUp, (446, 200)) self.windows.blit(self.exitDown, (446, 270)) def drawBG(self): self.windows.blit(self.BG, (0, 0)) def events(self, event): if event.type == KEYDOWN: if event.key == K_UP: if self.indikator == 1: self.indikator = 2 else: self.indikator -= 1 if event.key == K_DOWN: if self.indikator == 2: self.indikator = 1 else: self.indikator += 1 if event.key == K_RETURN: if self.indikator == 1: general.location = gameLocation general.location.startTime() else: sys.exit() def process(self): self.draw()
def add_images_2(self, product, images): Image = Images(self.db) current_images = Image.find_all_by_product(product) current_images_urls = [ x["url"]for x in current_images ] insert_queries = [] for img in images: if img not in current_images_urls: #if img not in current_images_urls: insert_queries.append(Image.insert_query(img, product)) delete_queries = Image.delete_missing_pictures(product, images, current_images, query=True) return insert_queries, delete_queries
def load_folder(self, directory_path): # Load real images files = Images.list_images_directory(directory_path) images = Images.read_list(directory_path, files, self.target_size) # Preprocessing images = Images.preprocess(images) # Shuffle the dataset if self.shuffle: indices = np.arange(images.shape[0]) np.random.shuffle(indices) files = files[indices] images = images[indices] return (files, images)
def __init__(self, uid=None, restart=None): #Get uid if needed if uid != None: self.uid = uid else: self.uid = input("Input your Unique/User ID for this Dataset: ") #Initialize user progress to existing progress if it exists and default starting progress otherwise self.progress = UserProgress(self.uid) #Check whether to reload the imgs archive, and possibly restart our progress if restart != None: self.restart = restart else: self.restart = input( "Would you like to reset your classification progress and restart from the beginning? (This will re-load all images) [Y\\N]: " ).upper() == "Y" if self.restart: #User wants to restart, both imgs and progress self.imgs = Images(restart=True) self.progress.restart() self.type_one_detections = TypeOneDetections(self, self.uid, restart=True) self.prediction_grids = PredictionGrids(self, self.uid, restart=True) else: #User does not want to restart. Defaults to this if they didn't put in "Y" if self.progress.editing_started(): #If they were already editing these images, resume progress self.imgs = Images(restart=False) self.type_one_detections = TypeOneDetections(self, self.uid, restart=False) self.prediction_grids = PredictionGrids(self, self.uid, restart=False) else: #If they weren't already editing these images (i.e. they haven't started editing), load the images. #No need to restart our progress since it's already the initial value. self.imgs = Images(restart=True) self.type_one_detections = TypeOneDetections(self, self.uid, restart=True) self.prediction_grids = PredictionGrids(self, self.uid, restart=True)
def fit_model(self, train: Images): self.model = ModelUNet.init_model(self.shape) earlystopper = EarlyStopping(patience=5, verbose=1) checkpointer = ModelCheckpoint(self.model_file, verbose=1, save_best_only=True) self.fit_history = self.model.fit( train.get_images(self.shape[:2]), train.get_masks(self.shape[:2], labeled=False), validation_split=0.1, batch_size=16, epochs=50, callbacks=[earlystopper, checkpointer]) self.trained = True
def saveRecordsToFiles(self, world, start, goal, found, blocked, records, prefix="play_"): # for stepCount, (position, action, nextPosition) in enumerate(records): # img = Images.worldToImage(world, position, goal) # img.save(prefix + 'step' + str(stepCount).zfill(3) + '_willGo_' + action.name + '.png') if found: # generate a last image with the player reaching the goal img = Images.worldToImage(world, goal, None) img.save(prefix + "step" + str(len(records)).zfill(3) + "_success.png")
def __init__(self, player1, player2, ui_draw=False): """ Start a game against the two selected types of player and build UI. """ self.player1 = player1 self.player2 = player2 self.ui_draw = ui_draw self.board_canvas = None if (player1 == "Human"): self.white_player = Player.HumanPlayer(colour.white) self.listen = True else: self.white_player = Player.AIPlayer( Piece.PieceColour.white, player1) self.listen = False if (player2 == "Human"): self.black_player = Player.HumanPlayer(colour.black) else: self.black_player = Player.AIPlayer( Piece.PieceColour.black, player2) self.game_state = Gamestate.Gamestate() if(self.ui_draw): self.master = Tk() self.frame = Frame(self.master) self.board_canvas = Canvas(self.frame, width=BOARD_SIZE, height=BOARD_SIZE) # bind mouse event listener to board canvas self.board_canvas.bind("<Button-1>", self.mouse_press) Images.load_images(self.board_canvas) self.build_ui() self.frame.pack() self.master.after(1, self.play) self.master.mainloop() f = open("game.pgn", 'w') f.close()
def readAllWallpaper(self): if os.path.exists(self.wallpapersPath): with open(self.wallpapersPath, 'r') as f: jsonData = f.read() jsonArray = json.loads(jsonData) allWallpaper = Images.parserImages(jsonArray) return allWallpaper else: return []
def add_images(self, product, images): Image = Images(self.db) current_images = Image.find_all_by_product(product) current_images_urls = [ x["url"]for x in current_images ] for img in images: if img not in current_images_urls: Image.save(img, product) Image.delete_missing_pictures(product, images)
def load_folder(self, directory_path): # Load real images image_files = Images.list_images_directory(directory_path) images = Images.read_list(directory_path, image_files, self.target_size) # Preprocessing images = Images.preprocess(images) # Shuffle the dataset if self.shuffle: indices = np.arange(images.shape[0]) np.random.shuffle(indices) image_files = image_files[indices] images = images[indices] self.x = images # Load text files txt_files = Images.list_texts_directory(directory_path) self.y = Images.read_list_txt(directory_path, txt_files)
def fit_area_model(self, train: Images, force=False): if not self.trained_area or force: self.area_model = ModelUNet.init_model(self.shape) earlystopper = EarlyStopping(patience=5, verbose=1) checkpointer = ModelCheckpoint(self.area_model_file, verbose=1, save_best_only=True) self.area_fit_history = self.area_model.fit( train.get_images(self.shape[:2]), train.get_masks(self.shape[:2], labeled=False), validation_split=0.1, batch_size=16, epochs=50, callbacks=[earlystopper, checkpointer]) self.trained_area = True self.area_model = load_model(self.area_model_file, custom_objects={ 'mean_iou': ModelUNet.mean_iou, })
def post(self): form_image = self.get_uploads('newImage') blogId = self.request.get('blogId') caller = self.request.get('caller') self.response.out.write('<html><body>You wrote:<pre>') self.response.out.write(cgi.escape(self.request.get('PageName'))) self.response.out.write('</pre></body></html>') username = "" # try: # user = UserLoggedIn.get_by_id(int(sessionId)) # username = user.blogger.nickname() # login = 1 # except db.BadKeyError: # login = 0 user = users.get_current_user() if user: login = 1 username = user.nickname() else: login = 0 login_url = users.create_login_url(cur_url) logout_url = users.create_logout_url('/') form_owner = username blob_info = form_image[0] im_key = blob_info.key() im_url = images.get_serving_url(blob_info.key()) i = Images(owner = form_owner, image_url = im_url, image_key = str(im_key)) target_url = "/AddImage.py?blogId="+blogId+"&caller="+caller i.put() self.redirect(target_url, False, False, None, None) self.response.write('</body></html>')
def fit_boundary_model(self, train: Images, force=False): if not self.trained_boundary or force: self.boundary_model = ModelUNet.init_model(self.shape) earlystopper = EarlyStopping(patience=5, verbose=1) checkpointer = ModelCheckpoint(self.boundary_model_file, verbose=1, save_best_only=True) self.boundary_fit_history = self.boundary_model.fit( train.get_images(self.shape[:2]), train.get_mask_boundaries(self.shape[:2]), validation_split=0.1, batch_size=16, epochs=50, callbacks=[earlystopper, checkpointer]) self.trained_boundary = True # not sure whether this is required # but the intention is when last training epoche was not optimal, the saved model should be better than self.boundary_model = load_model( self.boundary_model_file, custom_objects={'mean_iou': ModelUNet.mean_iou})
def __init__(self, name="Pygame App", winSize=(500, 500), tick=60): self.running = True self.clock = pygame.time.Clock() self.tick = tick self.compositeColors() self.playerCol = "w" self.lastX = 0 self.lastY = 0 self.board = Board() pygame.init() self.window = pygame.display.set_mode(winSize, pygame.RESIZABLE) pygame.display.set_caption(name) self.images = Images(self.window) self.resize(winSize) self.mainloop()
def __init__(self): Images.load_images() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(('127.0.0.1', 1729)) self.connection = Connection(self.socket) self.user_info = None self.world = None self.current_map_location = [0, 0] self.current_map = None self.display = None self.movement_state = { "UP": False, "DOWN": False, "RIGHT": False, "LEFT": False }
def __init__(self): # create an experiment object self.exp = Experiment(resolution=(1024,768)) self.video = VideoTrack("video") self.pc = PresentationClock() self.video.clear("black") self.stim = Text("", color="black") self.keyboard = KeyTrack("keyboard") self.bc = ButtonChooser(Key("a"), Key("l"), Key("SPACE"), Key("q")) self.images = Images() self.images.setup() self.log = LogTrack("session")
def drawPlayState(self, player): self.screen.fill((255, 255, 255)) for column in Map.getInstance().grid: for cell in column: if len(cell.beings) != 0: self.drawCharacter(cell.beings[-1]) if cell.barrier: self.screen.blit(Images.getInstance().getImage(Sprites.KYOKO_BARRIER), pygame.Rect(cell.x * 16, cell.y * 16, 16, 16)) if isinstance(player, Homura): if player.timeStopped: self.screen.blit(Images.getInstance().getImage(Sprites.TIME_STOP_EFFECT), pygame.Rect(0, 0, 144, 144)) player.image.set_colorkey((255, 255, 255)) self.drawCharacter(player) if player.targeting is not None: targetRect = pygame.Rect(player.targetX * 16, player.targetY * 16, 16, 16) self.screen.blit(Images.getInstance().getImage(Sprites.TARGET_CURSOR), targetRect) pygame.display.flip()
def post(self): form_image = self.get_uploads('newImage') blogId = self.request.get('blogId') caller = self.request.get('caller') self.response.out.write('<html><body>You wrote:<pre>') self.response.out.write(cgi.escape(self.request.get('PageName'))) self.response.out.write('</pre></body></html>') username = "" # try: # user = UserLoggedIn.get_by_id(int(sessionId)) # username = user.blogger.nickname() # login = 1 # except db.BadKeyError: # login = 0 user = users.get_current_user() if user: login = 1 username = user.nickname() else: login = 0 login_url = users.create_login_url(cur_url) logout_url = users.create_logout_url('/') form_owner = username blob_info = form_image[0] im_key = blob_info.key() im_url = images.get_serving_url(blob_info.key()) i = Images(owner=form_owner, image_url=im_url, image_key=str(im_key)) target_url = "/AddImage.py?blogId=" + blogId + "&caller=" + caller i.put() self.redirect(target_url, False, False, None, None) self.response.write('</body></html>')
def __init__(self): super(Familiar, self).__init__() self.maxHP = 25 self.hp = self.maxHP self.image = Images.getInstance().getImage(Sprites.FAMILIAR_STANDING) self.rect = self.image.get_rect() self.beingType = BeingType.FAMILIAR self.block = BlockStatus.BLOCK_ALL self.range = 1 self.strength = 10 self.vision = 3
def __init__(self): super(Walpurgisnacht, self).__init__() self.maxHP = 150 self.hp = self.maxHP self.image = Images.getInstance().getImage(Sprites.WALPURGISNACHT_STANDING) self.rect = self.image.get_rect() self.beingType = BeingType.WALPURGISNACHT self.block = BlockStatus.BLOCK_ALL self.range = 1 self.strength = 25 self.vision = 3
def predict_boundary(self, img: Images, th=None): if self.trained_boundary: #self.boundary_model = load_model(self.boundary_model_file, custom_objects={'mean_iou': ModelUNet.mean_iou,'iou_loss':iou_loss}) preds = self.boundary_model.predict(img.get_images(self.shape[:2]), verbose=2) if not th is None: # Threshold predictions preds = preds > th # todo: da kann man sich noch was besseres einfallen lassen else: preds = None warnings.warn('Model not trained yet') return preds
def __init__(self): super(Witch, self).__init__() self.maxHP = 75 self.hp = self.maxHP self.image = Images.getInstance().getImage(Sprites.WITCH_STANDING) self.rect = self.image.get_rect() self.beingType = BeingType.WITCH self.block = BlockStatus.BLOCK_ALL self.range = 1 self.strength = 20 self.vision = 3
def __init__(self): super(Walpurgisnacht, self).__init__() self.maxHP = 150 self.hp = self.maxHP self.image = Images.getInstance().getImage( Sprites.WALPURGISNACHT_STANDING) self.rect = self.image.get_rect() self.beingType = BeingType.WALPURGISNACHT self.block = BlockStatus.BLOCK_ALL self.range = 1 self.strength = 25 self.vision = 3
def saveRecordsToFiles(self, world, start, goal, found, blocked, records, prefix="play_"): # for stepCount, (position, action, nextPosition) in enumerate(records): # img = Images.worldToImage(world, position, goal) # img.save(prefix + 'step' + str(stepCount).zfill(3) + '_willGo_' + action.name + '.png') if found: # generate a last image with the player reaching the goal img = Images.worldToImage(world, goal, None) img.save(prefix + 'step' + str(len(records)).zfill(3) + '_success.png')
def __init__(self): super(Homura, self).__init__() self.image = Images.getInstance().getImage(Sprites.HOMURA_STANDING) self.rect = self.image.get_rect() self.bombs = [] self.timeStopped = False self.abilityOneName = "Golf Club" self.abilityOneDamage = 10 self.abilityOneMagic = 5 self.abilityOneRange = 1 self.abilityOneStatus = None self.abilityOneTargeted = True self.abilityOneTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityTwoName = "Pistol" self.abilityTwoDamage = 15 self.abilityTwoMagic = 10 self.abilityTwoRange = 3 self.abilityTwoStatus = None self.abilityTwoTargeted = True self.abilityTwoTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityThreeName = "Bomb" self.abilityThreeDamage = 25 self.abilityThreeMagic = 0 # Using this so extra Magic won't be used up for each character hit by the explosion self.abilityThreeRange = 1 self.abilityThreeStatus = None self.abilityThreeTargeted = True self.abilityThreeTargets = Victims.EVERYTHING self.bombMagicCost = 10 self.bombTimer = 0 self.bombBlastZone = 2 self.abilityFourName = "Time Stop" self.abilityFourDamage = 0 self.abilityFourMagic = 2 self.abilityFourRange = float('inf') self.abilityFourStatus = None self.abilityFourTargeted = False self.abilityFourTargets = Victims.EVERYTHING turnManager.delayFunction(self.regenerate, self.regenerationRate)
def __init__(self): super(Kyoko, self).__init__() self.image = Images.getInstance().getImage(Sprites.KYOKO_STANDING) self.rect = self.image.get_rect() self.barriers = [] self.stunVictims = [] self.abilityOneName = "Spear Thrust" self.abilityOneDamage = 15 self.abilityOneMagic = 5 self.abilityOneRange = 2 self.abilityOneStatus = None self.abilityOneTargeted = True self.abilityOneTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityTwoName = "Spear Spin" self.abilityTwoDamage = 15 self.abilityTwoMagic = 0 # Using this so extra Magic won't be used up for each character hit by the spin self.abilityTwoRange = 2 self.abilityTwoStatus = None self.abilityTwoTargeted = False self.abilityTwoTargets = Victims.NON_PLAYER_AND_HUMAN self.spinMagicCost = 15 self.abilityThreeName = "Spear Slam" self.abilityThreeDamage = 10 self.abilityThreeMagic = 10 self.abilityThreeRange = 2 self.abilityThreeStatus = Status.STUN self.abilityThreeTargeted = True self.abilityThreeTargets = Victims.NON_PLAYER_AND_HUMAN self.stunDuration = 5 self.abilityFourName = "Barrier" self.abilityFourDamage = 0 self.abilityFourMagic = 5 self.abilityFourRange = float('inf') self.abilityFourStatus = None self.abilityFourTargeted = True self.abilityFourTargets = Victims.EVERYTHING self.barrierDuration = 5 turnManager.delayFunction(self.regenerate, self.regenerationRate)
def __init__(self): super(Kyoko, self).__init__() self.image = Images.getInstance().getImage(Sprites.KYOKO_STANDING) self.rect = self.image.get_rect() self.barriers = [] self.stunVictims = [] self.abilityOneName = "Spear Thrust" self.abilityOneDamage = 15 self.abilityOneMagic = 5 self.abilityOneRange = 2 self.abilityOneStatus = None self.abilityOneTargeted = True self.abilityOneTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityTwoName = "Spear Spin" self.abilityTwoDamage = 15 self.abilityTwoMagic = 0 # Using this so extra Magic won't be used up for each character hit by the spin self.abilityTwoRange = 2 self.abilityTwoStatus = None self.abilityTwoTargeted = False self.abilityTwoTargets = Victims.NON_PLAYER_AND_HUMAN self.spinMagicCost =15 self.abilityThreeName = "Spear Slam" self.abilityThreeDamage = 10 self.abilityThreeMagic = 10 self.abilityThreeRange = 2 self.abilityThreeStatus = Status.STUN self.abilityThreeTargeted = True self.abilityThreeTargets = Victims.NON_PLAYER_AND_HUMAN self.stunDuration = 5 self.abilityFourName = "Barrier" self.abilityFourDamage = 0 self.abilityFourMagic = 5 self.abilityFourRange = float('inf') self.abilityFourStatus = None self.abilityFourTargeted = True self.abilityFourTargets = Victims.EVERYTHING self.barrierDuration = 5 turnManager.delayFunction(self.regenerate, self.regenerationRate)
def __init__(self): super(Mami, self).__init__() sself.image = Images.getInstance().getImage(Sprites.MAMI_STANDING) self.rect = self.image.get_rect() self.ribbonVictim = None self.abilityOneName = "Musket Slam" self.abilityOneDamage = 10 self.abilityOneMagic = 3 self.abilityOneRange = 1 self.abilityOneStatus = None self.abilityOneTargeted = True self.abilityOneTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityTwoName = "Musket Shot" self.abilityTwoDamage = 15 self.abilityTwoMagic = 5 self.abilityTwoRange = 3 self.abilityTwoStatus = None self.abilityTwoTargeted = True self.abilityTwoTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityThreeName = "Trio Finale" self.abilityThreeDamage = 45 self.abilityThreeMagic = 25 self.abilityThreeRange = 3 self.abilityThreeStatus = None self.abilityThreeTargeted = True self.abilityThreeTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityFourName = "Ribbon Tie" self.abilityFourDamage = 0 self.abilityFourMagic = 15 self.abilityFourRange = float('inf') self.abilityFourStatus = Status.STUN self.abilityFourTargeted = True self.abilityFourTargets = Victims.NON_PLAYER turnManager.delayFunction(self.regenerate, self.regenerationRate)
def __init__(self): super(Sayaka, self).__init__() self.image = Images.getInstance().getImage(Sprites.SAYAKA_STANDING) self.rect = self.image.get_rect() self.abilityOneName = "Sword Slash" self.abilityOneDamage = 15 self.abilityOneMagic = 5 self.abilityOneRange = 1 self.abilityOneStatus = None self.abilityOneTargeted = True self.abilityOneTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityTwoName = "Sword Toss" self.abilityTwoDamage = 10 self.abilityTwoMagic = 15 self.abilityTwoRange = 3 self.abilityTwoStatus = None self.abilityTwoTargeted = True self.abilityTwoTargets = Victims.NON_PLAYER_AND_HUMAN self.abilityThreeName = "Aqua Jet" self.abilityThreeDamage = 10 self.abilityThreeMagic = 0 # Using this so extra Magic won't be used up for each character hit by the jet self.abilityThreeRange = float('inf') self.abilityThreeStatus = None self.abilityThreeTargeted = True self.abilityThreeTargets = Victims.EVERYTHING self.jetMagicCost = 5 self.abilityFourName = "Heal" self.abilityFourDamage = -50 self.abilityFourMagic = 10 self.abilityFourRange = float('inf') self.abilityFourStatus = None self.abilityFourTargeted = False self.abilityFourTargets = Victims.NON_ENEMY turnManager.delayFunction(self.regenerate, self.regenerationRate)
def getWallPaper(self): req = request.Request(self.api, headers=self.headers) resp = request.urlopen(req) jsonData = resp.read().decode('utf-8') jsonObject = json.loads(jsonData) file = FileUtils() all = file.readAllWallpaper() first = None if len(all) > 0: first = all[0] jsonArray = jsonObject['images'] if jsonArray != None and len(jsonArray) > 0: today = Images(jsonArray[0], self.host) if first == None or today.url != first.url: file.writeAllWallpaper(all, today) file.writeReadMe(all, today) print('完成') else: print('数据相同,不添加')
class attentionExperiment: def __init__(self): # create an experiment object self.exp = Experiment(resolution=(1024,768)) self.video = VideoTrack("video") self.pc = PresentationClock() self.video.clear("black") self.stim = Text("", color="black") self.keyboard = KeyTrack("keyboard") self.bc = ButtonChooser(Key("a"), Key("l"), Key("SPACE"), Key("q")) self.images = Images() self.images.setup() self.log = LogTrack("session") def __del__(self): pass def userSpace(self): ts, b, rt = self.stim.present(clk=self.pc,duration=0,bc=self.bc) if b==Key("SPACE"): return True elif b==Key("q"): return "quit" else: return self.userSpace() def userInput(self, orientation=None ): ts, b, rt = self.stim.present(clk=self.pc,duration=0,bc=self.bc) response_time = rt[0]-ts[0] self.video.clear("black") if b==Key(orientation): self.video.showCentered(Text("Correct.\nPress space for next")) result = True #correct else: self.video.showCentered(Text("Incorrect.\nPress space for next")) #self.play_buzzer() result = False return result, response_time def baitAndSwitch(self, target, dist_1, dist_2): random.seed() position = range(12) if target: target.append( random.sample(position,1)[0]) position.remove(target[1]) if dist_1: dist_1.append( random.sample(position,1)[0] ) position.remove(dist_1[1]) if dist_2: dist_2.append( random.sample(position,1)[0] ) return target, dist_1, dist_2 """ Draw the canvas for the trial @input: images dictionary - contains the images, video - the video track to write, pc - the presentation clock posRed - the position of the red circle numDist - the number of distractors dist1 - the first distractor position, if no distractor then None dist2 - the second distractor position, if no distractor then None @output: A tuple containing the gabor patch orientation for the target and distractor """ def drawCanvas(self, obj): target, dist1, dist2 = obj["target"],obj["dist1"],obj["dist2"] # reset the display to black self.video.clear("black") self.video.showCentered(Text("+")) flashStimulus(Text("+",size=0.01), 1500, clk=self.pc) self.video.clear("black") self.video.showCentered(Text("+")) pos = [[0.8,0.5], [0.76,0.65] , [0.65,0.76] , [0.5,0.8] , [0.35,0.76] , [0.24,0.65] , [0.2,0.5], [0.24,0.35] , [0.35,0.24] , [0.5,0.2] , [0.65,0.24] , [0.76,0.35]] gabor_switch = [0]*6+[1]*6 #determine whether to keep it horizontal or vertical for the 12 cases random.shuffle(gabor_switch) ret = {"red":None, "square":None, "size":None} target, dist1, dist2 = self.baitAndSwitch(target, dist1, dist2) print target, dist1, dist2 for i,location in enumerate(pos): if target[0] and i == target[1]: self.video.showProportional( Image(self.images.images[target[0]][gabor_switch[i]]) , location[0], location[1]) ret[target[0]] = ("a" if gabor_switch[i] else "l", i) elif dist1 and i == dist1[1]: self.video.showProportional(Image( self.images.images[dist1[0]][gabor_switch[i]]) , location[0], location[1]) ret[dist1[0]] = ("a" if gabor_switch[i] else "l", i) elif dist2 and i == dist2[1]: self.video.showProportional(Image( self.images.images[dist2[0]][gabor_switch[i]]) , location[0], location[1]) ret[dist2[0]] = ("a" if gabor_switch[i] else "l", i) else: self.video.showProportional(Image( self.images.images["green"][gabor_switch[i]]) , location[0], location[1]) self.video.updateScreen() return ret def instruct_text(self, target): if target == "red": return "red circle" elif target == "square": return "green_square" elif target == "size": return "large green circle" def create_log(self, trials): self.log.logMessage("Trial# \t result \t response_time \t target \t square \t red \t size \t #Dist \t presence") for k,v in trials.items(): trial = "%s"%k result = "correct" if v[0] else "Incorrect" response_time = "%s"%v[1] target = "%s"%v[2] pos = "" count=0 tFlag = False for key,value in v[3].items(): if value: pos = pos+"%s=%s|%s"%(key,value[0],value[1])+"," count=count+1 if key == target: tFlag = True else: pos = pos+"," if tFlag: self.log.logMessage("%s,%s,%s,%s,%s%s,%s"%(trial,result,response_time,target,pos,count-1,tFlag)) else: self.log.logMessage("%s,%s,%s,%s,%s%s,%s"%(trial,result,response_time,target,pos,count,tFlag)) def run(self,distOrder, target, distractors): self.log.logMessage("Session Start") instruct1 = open("instructions.txt","r").read() instruct(instruct1%self.instruct_text(target),size=0.03, clk=self.pc) #self.pc.delay(10000) trials = {} paramsDict = {0: {"target":[target], "dist1":None, "dist2":None}, 1: {"target":[target], "dist1":[distractors[0]], "dist2":None}, 2: {"target":[target], "dist1":[distractors[1]], "dist2":None}, 3: {"target":[target], "dist1":[distractors[0]], "dist2":[distractors[0]]}, 4: {"target":[None], "dist1":None, "dist2":None}, 5: {"target":[None], "dist1":[distractors[0]], "dist2":None}, 6: {"target":[None], "dist1":[distractors[1]], "dist2":None}, 7: {"target":[None], "dist1":[distractors[0]], "dist2":[distractors[1]]} } for i in range(len(distOrder)): #params are populated from paramDict retOrient = self.drawCanvas( paramsDict[distOrder[i]] ) if EXP == 'gabor': result,response_time = self.userInput(retOrient[target][0].lower()) else: if distOrder[i] >= 4: result,response_time = self.userInput('a'.lower()) else: result,response_time = self.userInput('l'.lower()) trials[i] = [result, response_time, target, retOrient] ret = self.userSpace() if ret == "quit": break self.create_log(trials) self.log.logMessage("Session end")
class Display: color = (200, 2, 2) def __init__(self, map, player, pointOfRespawn, generalTimer, portalWin): self.initWindow() self.player = player self.portalWin = portalWin self.image = Images() self.loadTexture(map) self.generalTimer = generalTimer self.pointofRespawn = pointOfRespawn def loadTexture(self, map): self.initBlocks(map) self.background = self.image.getImage("background").convert() self.topBar = self.image.getImage("top_bar").convert() self.meat = self.image.getImage("MEAT") self.win = self.image.getImage("WIN") def initBlocks(self, map): size = 50 imageUnConvert = [100, 800, 700, 300, 400] empty = [0, 500] self.entities = pygame.sprite.Group() for row in range(map.getHeight()): for col in range(map.getWidth()): if not map.getValues(row, col) in empty: if map.getValues(row, col) in imageUnConvert: platform = Platform(col * size, row * size, self.image.getImage(map.getValues(row, col)), map.getValues(row, col)) else: platform = Platform(col * size, row * size, self.image.getImage(map.getValues(row, col)).convert(), map.getValues(row, col)) self.entities.add(platform) def initWindow(self): pygame.font.init() self.screen = pygame.display.get_surface() pygame.display.set_caption("GAME") def draw(self): self.drawBackGround() self.drawScore() self.drawBots() self.drawPortalWin() self.drawMap() self.drawGeneralTimer() self.drawPlayer() self.drawPortalsRespawn() self.drawAtacks() pygame.display.flip() def drawBackGround(self): self.screen.blit(self.background, (0, 0)) self.screen.blit(self.topBar, (0, 0)) def drawScore(self): (posX, posY, fontSize) = (800, 5, 50) myFont = pygame.font.Font("fonts/Plasma Drip.ttf", fontSize) fontImage = myFont.render("Score:" + str(self.player.getScore()), 0, (self.color)) downImage = myFont.render("Score:" + str(self.player.getScore()), 0, ((0, 0, 0))) self.screen.blit(downImage, (posX + 3, posY + 3)) self.screen.blit(fontImage, (posX, posY)) def drawPlayer(self): if self.player.isLive(): self.screen.blit(self.player.getImage(), self.player.getPosition()) self.screen.blit(self.player.getHealth().getImage(), self.player.getHealth().getPosition()) def drawAtacks(self): if self.player.getAtack().isAtack(): self.screen.blit(self.player.getAtack().getImage(), self.player.getAtack().getPosition()) def drawMap(self): self.entities.draw(self.screen) def getEntities(self): return self.entities def drawBots(self): for portal in self.pointofRespawn: bots = portal.getBots() for bot in bots: if bot.isLive(): self.screen.blit(bot.getImage(), bot.getPosition()) self.screen.blit(bot.getHealth().getImage(), bot.getHealth().getPosition()) def drawPortalsRespawn(self): for pointRespawn in self.pointofRespawn: self.screen.blit(pointRespawn.getImage(), pointRespawn.getPosition()) def drawGeneralTimer(self): (posX, posY, fontSize) = (650, 5, 50) myFont = pygame.font.Font("fonts/Plasma Drip.ttf", fontSize) if self.generalTimer.getTimeOpenPortal() == 0: fontImage = myFont.render(self.generalTimer.getStrTimeLivePortal(), 0, (self.color)) else: fontImage = myFont.render(self.generalTimer.getStrTimeOpenPortal(), 0, (self.color)) self.screen.blit(fontImage, (posX, posY)) def drawPortalWin(self): if self.portalWin.isOpen(): self.screen.blit(self.portalWin.getImage(), self.portalWin.getPosition()) def drawMeat(self): self.screen.blit(self.meat, (0, 50)) pygame.display.flip() def drawWin(self): self.screen.blit(self.win, (0, 50)) pygame.display.flip()
from nolearn.lasagne.visualize import draw_to_notebook from nolearn.lasagne.visualize import plot_loss from nolearn.lasagne.visualize import plot_conv_weights from nolearn.lasagne.visualize import plot_conv_activity from nolearn.lasagne.visualize import plot_occlusion from nolearn.lasagne.visualize import plot_saliency theano.config.exception_verbosity='high' theano.config.traceback.limit=100 path1 = '/home/karna/Karna_Work/Handwriting_Project/Handwriting-Segmentation/data/' img = Images(path1) print(img.cnt) img.applyCanny() img.createFeatures() fimgi = img.getEdgesFeature(1) imgi = img.getImage(0) #dividing the image into two pages and removing the marginal white part from 4 sides. sh = np.shape(imgi) limgi = imgi[:,0:sh[1]/2-1] rimgi = imgi[:,sh[1]/2:sh[1]-1] plt.imshow(rimgi,cmap='gray') plt.show() sh=np.shape(limgi) up = 120 down=150
from Images import Images from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn import metrics import lasagne import theano import theano.tensor as T theano.config.exception_verbosity='high' theano.config.traceback.limit=100 #Data preparation path2 = '/home/karna/Karna_Work/Handwriting_Project/Handwriting-Segmentation/testdata2/' testimg = Images(path2) plt.imshow(testimg.getImage(1),cmap='gray') plt.show() batchsize = testimg.cnt varout=[] varin=() output = np.eye(batchsize,batchsize) output=output.astype(int) size=150 for i in range(batchsize): timgi = testimg.getImage(i)/255 sh = np.shape(timgi[:,:,0]) dest = np.zeros((size,size,1)) dest[0:sh[0],0:sh[1],:]=timgi[:,:,0,None]
import numpy as np import os from Images import Images from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn import metrics import lasagne import theano import theano.tensor as T theano.config.exception_verbosity='high' theano.config.traceback.limit=100 path2 = '/home/karna/Karna_Work/Handwriting_Project/Handwriting-Segmentation/testdata2/uppercontour/' uppercontourimg = Images(path2) #testimg.applyCanny() #testimg.invertImages() #testimg.normalize() #plt.imshow(testimg.getImage(2),cmap='gray') #plt.show() #testimg.createImageFeatures() uppercontourno = uppercontourimg.cnt path2 = '/home/karna/Karna_Work/Handwriting_Project/Handwriting-Segmentation/testdata2/lowercontour/' imglowercont = Images(path2) #testimg.applyCanny() #imglowercont.invertImages() #testimg.normalize() #plt.imshow(imglowercont.getImage(2),cmap='gray')
import cv2 import cv import sklearn import numpy as np import os from Images import Images from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn import metrics path1 = '/home/karna/Karna_Work/Handwriting_Project/Handwriting-Segmentation/data/' img = Images(path1) print(img.cnt) img.applyCanny() img.createFeatures() fimgi = img.getEdgesFeature(1) imgi = img.getImage(0) #dividing the image into two pages and removing the marginal white part from 4 sides. sh = np.shape(imgi) limgi = imgi[:,0:sh[1]/2-1] rimgi = imgi[:,sh[1]/2:sh[1]-1] plt.imshow(rimgi,cmap='gray') plt.show() sh=np.shape(limgi) up = 120 down=150 left = 400 right = 90