示例#1
0
    def wait(self,
             temp_rel_path,
             threshold=threshold,
             cycle_interval=0,
             max_wait_time=None,
             episode=None):
        timer = Timer()
        while True:
            duration = timer.get_duration()
            print('\r > wait %s ... %ds ' % (temp_rel_path, duration), end='')

            if max_wait_time is not None and 0 < max_wait_time < duration:
                print(' ×', flush=True)
                return Location(self, None, None, None)

            if episode is not None:
                try:
                    episode()
                except Exception as e:
                    print('过程方法执行异常')
                    print(e)

            loc = self.get_location(temp_rel_path, threshold=threshold)
            if loc is not None:
                print(' √', flush=True)
                return loc

            if cycle_interval > 0:
                time.sleep(cycle_interval)
示例#2
0
def fight_stage(stage_temp_list):
    if stage_temp_list is None or len(stage_temp_list) == 0:
        print('目标关卡未指定')
        exit(1)

    auto_adb = AutoAdb()
    # 判断是否已经在关卡中
    in_enemy = PageUtils.in_enemy_page()
    if in_enemy:
        fight_all_enemy()
        return

    # 确定进入
    timer = Timer()
    while True:
        print('\r扫描目标关卡中 ... %ds ' % timer.get_duration(), end='')
        loc = auto_adb.get_location(*stage_temp_list)
        if loc is not None:
            break

    print('%s √' % loc.temp_rel_path)
    loc.click()  # 点击关卡图标
    confirmed = confirm_stage_team()  # 确认队伍
    if not confirmed:  # 如果队伍确认失败,则重新做一次
        fight_stage(stage_temp_list)
示例#3
0
    def wait(self,
             temp_rel_path,
             threshold=threshold,
             max_wait_time=None,
             episode=None):
        timer = Timer()
        none_loc = Location(self, None, None, None)
        while True:
            duration = timer.get_duration()
            print('\r > wait %s ... %ds ' % (temp_rel_path, duration), end='')

            if max_wait_time is not None and 0 < max_wait_time < duration:
                print(' ×', flush=True)
                return none_loc

            if episode is not None:
                try:
                    res = episode()
                    if res is not None and not res:
                        return none_loc
                except Exception as e:
                    print('过程方法执行异常')
                    print(e)

            loc = self.get_location(temp_rel_path, threshold=threshold)
            if loc is not None:
                print(' √', flush=True)
                return loc
示例#4
0
def wind_up_stage_fight():
    timer = Timer()
    while PageUtils.in_fight_page():
        print('\r战斗中。。。 %ds ' % timer.get_duration(), end='')
        time.sleep(5)

    if PageUtils.in_enemy_page():
        print('进行关卡收尾。。。')
        fight_all_enemy()
        return True
    return False
示例#5
0
 def __init__(self, fps=0):
     self.fps = fps  # 0 means read max fps
     self.is_running = None
     self.cap = cv2.VideoCapture(0)
     self.buffer = queue.Queue(10)
     if fps == 0:
         self.frame_reader = Timer(interval=0,
                                   callback=self.read_frames,
                                   drift=True)
     else:
         self.frame_reader = Timer(interval=1.0 / fps,
                                   callback=self.read_frames,
                                   drift=False)
示例#6
0
def fight_finish():
    adb = AutoAdb()

    # 等待战斗结束
    timer = Timer()
    while True:
        print('\r等待战斗结束 %ds ...' % timer.get_duration(), end='')
        skip_dialog()
        time.sleep(3)  # 每次循环加一个等待时间,降低cpu占用
        if adb.check('temp_images/fight/fight-finish.png'):
            print(' √ 总耗时: %ds' % timer.get_duration())
            break

    # 战斗结束
    fight_result = None
    ending_loc = Location(adb, None, 1160, 690)
    while True:
        if fight_result is None:
            # 处理新船
            new_ship = adb.check('temp_images/fight/new-ship.png')
            if new_ship:
                print('发现新船!!')
                fight_result = True
                ending_loc.click()
                adb.click('temp_images/confirm-btn.png')
                continue
            # 处理失败
            fail_confirm = adb.click('temp_images/fight/fail-confirm.png')
            if fail_confirm:
                fight_result = False
                # 战队难以成型时点击确定
                adb.wait('temp_images/confirm-btn.png', max_wait_time=3).click()
                break
        # 持续点击右下角
        ending_loc.click()
        # 回到 stage列表页面 或 敌人列表页面 也说明战斗已经结束
        if adb.check('temp_images/page/in-stage.png',  # stage列表
                     'temp_images/page/in-enemy.png',  # enemy列表
                     'temp_images/page/in-daily.png'):  # 日常任务结束后的界面
            fight_result = True
            break
        if adb.check('temp_images/page/in-operation.png'):
            print('误入演习界面,退出。。。')
            PageUtils.back()
            continue

    print('战斗胜利~(~ ̄▽ ̄)~' if fight_result else '战斗失败 >_<')
    # 战斗结束后可能出现紧急任务提示
    # 由于是透明遮罩, 所以无法根据其他元素是否显示而做出反应, 只能等一定的时间
    adb.wait('temp_images/confirm-btn.png', max_wait_time=2).click()
    return fight_result
示例#7
0
def soundDone():
    global state, image1, image2, imageSurface1, imageSurface2, timer, camera1, camera2

    if state == WAITING_FOR_PHOTO:
        # Take pictures
        image1 = imutils.rotate_bound(currImage1.copy(), 270)
        image2 = imutils.rotate_bound(currImage2.copy(), 270)
        cameraEffect.play()

        timer = Timer(DELAY_UNTIL_PICTURES_SHOW, showPictures)
示例#8
0
class FPS_Controller(object):
    def __init__(self, fps=0):
        self.fps = fps  # 0 means read max fps
        self.is_running = None
        self.cap = cv2.VideoCapture(0)
        self.buffer = queue.Queue(10)
        if fps == 0:
            self.frame_reader = Timer(interval=0,
                                      callback=self.read_frames,
                                      drift=True)
        else:
            self.frame_reader = Timer(interval=1.0 / fps,
                                      callback=self.read_frames,
                                      drift=False)

    def read_frames(self):
        ret, frame = self.cap.read()
        log.info("read a frame")
        try:
            self.buffer.put_nowait(frame)
        except queue.Full:
            log.warning("Buffer is full, eject oldest frame")
            self.buffer.get_nowait()
            self.buffer.put_nowait(frame)

    def start(self):
        self.is_running = True
        self.frame_reader.start()
        # Wait a while for frames are filled to buffer
        time.sleep(0.5)
        while self.is_running:
            frame = self.buffer.get()
            log.info("yielding a frame")
            yield frame

    def stop(self):
        self.frame_reader.stop()
        self.cap.release()
        self.is_running = False
        log.info("Released")
示例#9
0
def confirm_stage_team():
    adb = AutoAdb()
    timer = Timer()
    while True:
        print('\r确认关卡队伍中。。。 %ds ' % timer.get_duration(), end='')
        # 如果已经进入敌人列表界面,则跳出循环
        if PageUtils.in_enemy_page():
            print(' √')
            fight_all_enemy()  # 战斗
            return True

        button_list = [
            'temp_images/stage/immediate-start.png',  # 立刻前往
            'temp_images/stage/weigh-anchor.png',  # 出击按钮
            'temp_images/fight/fight-confirm.png'  # 特殊关卡会提示更多
        ]
        button_loc = adb.get_location(*button_list)
        if button_loc is not None:
            button_loc.click()
        port_full = PortUtils.check_port_full()
        if port_full:
            return False
示例#10
0
def fight_stage(stage_temp_list):
    if stage_temp_list is None or len(stage_temp_list) == 0:
        print('目标关卡未指定')
        exit(1)

    auto_adb = AutoAdb()
    # 判断是否已经在关卡中
    wind_up_stage_fight()

    # 确定进入
    timer = Timer()
    while True:
        print('\r扫描目标关卡中 ... %ds ' % timer.get_duration(), end='')
        loc = auto_adb.get_location(*stage_temp_list)
        if loc is not None:
            break

    print('%s √' % loc.temp_rel_path)
    loc.click()  # 点击关卡图标
    confirm_result = confirm_stage_team()  # 确认队伍, 战斗
    if confirm_result is None:  # 如果关卡进入失败, 则重新尝试
        print('关卡进入失败, 重新尝试...')
        fight_stage(stage_temp_list)
    return confirm_result
示例#11
0
def showPictures():
    global image1, image2, imageSurface1, imageSurface2, timer

    imageSurface1 = getSurfaceFromFrame(image1)
    imageSurface2 = getSurfaceFromFrame(image2)

    Log.info('SHOW')

    # Save both images with timestamp
    timeString = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    image = np.concatenate((image1, image2), axis=1)
    cv2.imwrite('images/' + timeString + '-image.png', image)

    Log.info('SAVED')

    timer = Timer(DELAY_BETWEEN_SOUNDS, moveNext)
示例#12
0
	def run(self):
		with Timer("BackTester::run", endDebugLevel = 'INFO'):
			inputConf = json.loads(self.inputConfRaw)
			jsonschema.validate(inputConf, BacktestSchema.schema)

			# generate backtest configuration based on the input file
			if 'backtestConf' in inputConf:
				for conf in inputConf['backtestConf']:
					backtestConf = BacktestGenerator.getBacktest(conf)

					self.log.debug("Generated backtest config: " + str(backtestConf))
					self.log.debug('')

					if 'backtest' not in inputConf:
						inputConf['backtest'] = []
					inputConf['backtest'] += backtestConf

			for conf in inputConf['backtest']:
				with Db.session_scope():
					ced = ExecManager.createCretenExecDetl(self.cretenExecId, conf)
					cretenExecDetlId = ced.creten_exec_detl_id

				self.exchangeDataListener.setCretenExecDetlId(cretenExecDetlId)
				self.exchangeEventSimulator.setCretenExecDetlId(cretenExecDetlId)

				for pairConf in conf['pairs']:
					pair = Pair(baseAsset = pairConf[0], quoteAsset = pairConf[1])

					self.log.info('')
					self.log.info('Loading market rules')
					self.marketRulesManager.init([pair.getSymbol()])
					self.log.info('Loading market rules completed')
					self.log.info('')

					for strategyConf in conf['strategies']:
						strategy = StrategyFactory.getStrategy(strategyConf, pair, cretenExecDetlId,
						                                       self.exchangeClient, self.marketDataManager,
						                                       self.marketRulesManager, self.portfolioManager, self.orderManager)

						self.strategyManager.reset()
						strategyExecutor = StrategyExecutor()
						strategyExecutor.addStrategy(strategy)
						self.strategyManager.addStrategyExecutor(strategyExecutor)

						startTimestamp = datetime.strptime(conf['start_tmstmp'], BACKTEST_TMSTMP_FORMAT)
						endTimestamp = datetime.strptime(conf['end_tmstmp'], BACKTEST_TMSTMP_FORMAT)

						self.log.info('Backtesting period: ' + str(startTimestamp) + ' - ' + str(endTimestamp))
						self.log.info('')

						self.exchangeDataListener.resetCandleListener()
						self.exchangeDataListener.resetUserDataListener()
						self.marketDataManager.removeAllCandles()
						self.orderManager.reset()

						self.log.info('Initialize portfolio:')
						for position in conf['portfolio']:
							self.log.info('\t' + position['asset'] + ': ' + str(position['quantity']))
						self.log.info('')
						self.initPortfolio(conf['portfolio'])

						interval = getattr(CretenInterval, "INTERVAL_" + conf['interval'])
						self.exchangeDataListener.init(startTimestamp, endTimestamp)
						self.exchangeDataListener.registerCandleListener(pair, interval, [self.exchangeEventSimulator.simulateEvent, strategyExecutor.execute])

						self.exchangeDataListener.start()

						# revert open trades in order not to interfere with overall statistics
						self._revertOpenTrades(strategy.getStrategyExecId())

						# evaluate results
						pos = self.portfolioManager.getPosition(pair.getQuoteAsset())
						self.log.info('')
						self.log.info('Final balance for ' + pair.getQuoteAsset() + ': ' + str(pos.getFree()))

						# calculate metrics
						self._showPerformance(strategy.getStrategyExecId())

				ced.exec_state = REF_EXEC_STATE.FINISHED
				with Db.session_scope():
					Db.Session().add(ced)