Exemplo n.º 1
0
 def __init__(self):
     super().__init__()
     # 环境配置
     self.srcpath = pathm.GetUiPath()
     self.logpath = pathm.GetLogPath()
     self.Timing = False
     self.setupUI()
Exemplo n.º 2
0
 def exportPath(self):
     if len(self.hexaMap.hexamapState.robotPath) > 0:
         filename = QtGui.QFileDialog.getSaveFileName(
             self, "Save file", "", ".xml")
         pathMgr = PathManager(self.hexaMap.hexamap, self.labelMgr.mapFile,
                               5, self.formSize[0], self.formSize[1])
         pathMgr.dumpPath(self.hexaMap.hexamapState.robotPath, filename)
def GetFP_s():
    strings = FU_s.GetStringPath()

    Strings = []
    for k in strings:
        for n in k:
            Strings.append(n)

    Fault_Diag_EventStrings_IDs = list()
    for i in range(len(Strings)):
        f_strings = list()
        for each in Strings[i]:
            f_strings.append(
                DiagnoserFunctions.GetEquivalentDiagEventFromAut(each))
        Fault_Diag_EventStrings_IDs.append(f_strings)

    # print(f'Fault_Diag_EventStrings_IDs = {Fault_Diag_EventStrings_IDs}')
    cadeias = DefineStrings.GetDiagStates(Fault_Diag_EventStrings_IDs)
    # print(f'cadeias = {cadeias}')

    lista_fp = []
    for each in cadeias:
        FP = False
        last = each[-1]

        if not PathManager.ConditionCHolds(last, antes_fu=True):
            lista_fp.append('')
        else:
            target_id_last = DiagnoserFunctions.GetNextStatesInID(last)

            if FP:
                lista_fp.append(fp)
            else:
                j = 0
                for i in range(len(each), 0, -1):
                    if i - 2 < 0:
                        break
                    else:
                        if j == 0 and not PathManager.ConditionCHolds(
                                each[i - 2], antes_fu=True):
                            fp = each[i - 1]
                        if PathManager.ConditionCHolds(each[i - 2],
                                                       antes_fu=True):
                            fp = each[i - 2]
                        else:
                            break
                    j += 0
                lista_fp.append(fp)

    nomes_lista_fp = []
    for each in lista_fp:
        nomes_lista_fp.append(DiagnoserFunctions.GetNextStatesInNames(each))

    return nomes_lista_fp
Exemplo n.º 4
0
    def __init__(self,
                 planning_range,
                 segment_length,
                 cost_func=None,
                 map_file=None):
        self.planningRange = planning_range
        self.segmentLength = segment_length
        self.mapFile = map_file
        self.rrts = BiRRTstar(self.planningRange, self.segmentLength)
        if self.mapFile != None:
            self.rrts.loadMap(self.mapFile)

        self.pathMgr = PathManager(cost_func)
        self.rrts_viz = BiRRTVisualizer(self.rrts, self.pathMgr)
        self.cost_func = cost_func
Exemplo n.º 5
0
    def isOk(self):
        # set info piece
        gap = datetime.strptime(self.GetFinish.text(), "%Y-%m-%d %H:%M:%S") - \
            datetime.strptime(self.GetStart.text(), "%Y-%m-%d %H:%M:%S")
        gap_m = int(gap.seconds / 60)
        # did't change edit line protocol
        try:
            detail = self.Detail.text()
            detail = detail.strip()
            if len(detail) == 0:
                recentLog = self.GetRecentLog(pathm.GetLogFile())
                lastLogTemp = recentLog.split("|")
                detail = lastLogTemp[-1]

            if gap_m > 1:
                pieceInfo = self.GetStart.text()+"|"+self.GetFinish.text() + \
                    "|"+str(gap_m)+"|" + detail
                self.pieceInfo = pieceInfo
                # self.bingoLabel.setVisible(True)
                infoProto = 'T0:' + self.GetStart.text() + '\n' \
                    + 'T1:' + self.GetFinish.text() + '\n' \
                    + 'Gap:' + str(gap_m) + '\n' \
                    + 'Detail:' + detail
                reply = QMessageBox.question(self, 'Save Message', infoProto,
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.Yes:
                    self.emitPiece()
                    self.close()
                    print('emit')
                    event.accept()
                else:
                    event.ignore()
        except:
            self.__reset__()
Exemplo n.º 6
0
 def __WritePiece__(self, info):
     if not isinstance(info, str):
         return
     elif len(info.strip()) < 10:
         return
     else:
         try:
             with open(pathm.GetLogFile(), 'a+', encoding='UTF-8') as f:
                 infoAppend = info + "\n"
                 f.write(infoAppend)
         except:
             pass
Exemplo n.º 7
0
class BiRRTstarPlanner(object):
    def __init__(self,
                 planning_range,
                 segment_length,
                 cost_func=None,
                 map_file=None):
        self.planningRange = planning_range
        self.segmentLength = segment_length
        self.mapFile = map_file
        self.rrts = BiRRTstar(self.planningRange, self.segmentLength)
        if self.mapFile != None:
            self.rrts.loadMap(self.mapFile)

        self.pathMgr = PathManager(cost_func)
        self.rrts_viz = BiRRTVisualizer(self.rrts, self.pathMgr)
        self.cost_func = cost_func

    def findPaths(self, start, goal, iterationNum, homotopyMgr):

        self.rrts.init(start, goal, self.cost_func, homotopyMgr)
        dividingRefs = homotopyMgr.getDividingRefs(start, goal)
        for dr in dividingRefs:
            self.rrts.dividingRefs.append([dr.open_seg[0], dr.open_seg[1]])

        for i in range(iterationNum):
            print "Iter@" + str(i)
            self.rrts.extend(self.rrts.st_kdtree_root, self.rrts.st_nodes)
            self.rrts.extend(self.rrts.gt_kdtree_root, self.rrts.gt_nodes)
            self.rrts_viz.update()

        paths, infos, costs = self.rrts.findPaths()

        for i in range(len(paths)):
            self.pathMgr.addPath(Path(paths[i], costs[i], infos[i]))

        self.rrts_viz.activePaths = paths

        #self.rrts_viz.update()

        return paths
Exemplo n.º 8
0
 def putVtecRecords(self, vtecRecords, reqInfo={}):
     import PathManager
     pathMgr = PathManager.PathManager()
     vtecLF = pathMgr.getLocalizationFile(self.__vtecRecordsLocPath,
                                          'CAVE_STATIC', 'USER')
     fd = None
     try:
         fd = vtecLF.getFile("w")
         json.dump(vtecRecords, fd)
     finally:
         if fd:
             fd.close()
         vtecLF.save()
         if reqInfo.get("lock") != "True" and self.__vtecRecordsLockFD:
             self._unlockVtecDatabase()
Exemplo n.º 9
0
 def __WritePiece_1__(self, info):
     if not isinstance(info, str):
         return
     elif len(info.strip()) < 10:
         return
     else:
         try:
             with open(pathm.GetLogFile(), 'r+', encoding='UTF-8') as f:
                 allLines = f.readlines()
                 # 避免重复写入
                 lastLine = allLines[-1]
                 if not info.strip('\n') == lastLine.strip('\n'):
                     # allLines[-1] = info + "\n"
                     f.write(info + "\n")
         except:
             pass
Exemplo n.º 10
0
 def _readVtecDatabase(self):
     import PathManager
     pathMgr = PathManager.PathManager()
     vtecLF = pathMgr.getLocalizationFile(self.__vtecRecordsLocPath,
                                          'CAVE_STATIC', 'USER')
     fd = None
     vtecRecords = []
     try:
         fd = vtecLF.getFile("r")
         vtecRecords = json.load(fd)
         vtecRecords = self.as_str(vtecRecords)
     except:
         vtecRecords = []
     finally:
         if fd:
             fd.close()
     return vtecRecords
Exemplo n.º 11
0
    def __init__(self, operationalMode):
        operationalMode = bool(operationalMode)
        recordsFileName = "vtecRecords.json" if operationalMode else "testVtecRecords.json"
        lockFileName = "vtecRecords.lock" if operationalMode else "testVtecRecords.lock"

        import PathManager
        pathMgr = PathManager.PathManager()
        lf = pathMgr.getLocalizationFile("HazardServices", 'CAVE_STATIC',
                                         'USER')
        basepath = lf.getPath()

        # Verify the basepath exists, if it doesnt create it.
        if os.path.isdir(basepath) == False:
            os.makedirs(basepath)

        self.__vtecRecordsLocPath = os.path.join("HazardServices",
                                                 recordsFileName)
        self.__vtecRecordsFilename = os.path.join(basepath, recordsFileName)
        self.__vtecRecordsLockname = os.path.join(basepath, lockFileName)
        self.__vtecRecordsLockFD = None
Exemplo n.º 12
0
 def ManmalTrack(self):
     # 读取并打开单个文件,所以tuple索引为0。
     if False:
         openfile_name = QFileDialog.getOpenFileName(
             self, '打开日志', '', 'Text Files (*.txt)')
         if openfile_name[0].strip() != "":
             startNotepad = "notepad " + openfile_name[0].strip()
             try:
                 os.system(openfile_name[0].strip())
             except:
                 pass
     # 打开文件路径
     else:
         logpath = './'
         try:
             logpath = pathm.GetLogPath()
         except:
             curPath = os.path.abspath(__file__)
             logpath = os.path.dirname(curPath)
         os.system('start explorer.exe %s' % (logpath))
Exemplo n.º 13
0
 def __Writelog__(self):
     ret = False
     self.gap = self.StopTime - self.StartTime
     if int(self.gap.seconds) >= 2:
         text, ok = QInputDialog.getText(self, 'Track', 'What Did U DO?')
         if ok & (text.strip() != ""):
             try:
                 with open(pathm.GetLogFile(), 'a+', encoding='UTF-8') as f:
                     item = datetime.strftime(self.StartTime, "%Y-%m-%d %H:%M:%S") + \
                         "|" + \
                         datetime.strftime(
                             self.StopTime, "%Y-%m-%d %H:%M:%S")
                     item = item + "|" + str(int(
                         self.gap.seconds / 60)) + "|"
                     item = item + text
                     item = item + '\n'
                     f.write(item)
             except:
                 pass
             self.gap = datetime.now() - datetime.now()
             self.StartTime = datetime.now()
             self.StopTime = datetime.now()
             ret = True
     return ret
Exemplo n.º 14
0
            return cstr
    return None


if __name__ == '__main__':

    pathStrings = []

    FILENAME = 'classes01.txt'

    with open(FILENAME, 'r') as fp:
        data = fp.readlines()
        for line in data:
            exec 'pathStrings.append(' + line + ')'

    mgr = PathManager(None)

    print pathStrings

    pairs = []
    for i in range(len(pathStrings) - 1):
        for j in range(i + 1, len(pathStrings)):
            refPathStr = pathStrings[i]
            compathStr = pathStrings[j]
            if compareStringPath(compathStr, refPathStr, True) == True:
                print "Found Equivalence"
                strA = mgr.getString(compathStr)
                strB = mgr.getString(refPathStr)
                print strA
                print strB
Exemplo n.º 15
0
class MultiInputDialog(QDialog):
    timedateStyle_1 = (
        "QDateTimeEdit{border-radius:4px;font-size:16px;font-weight:bold;color:rgb(6, 75, 177);}"
        "QDateTimeEdit{border:2px solid rgb(189, 189, 189);}"
        "QDateTimeEdit{font-family:'Century'}")

    lineEditStyle_1 = (
        "QLineEdit{border-radius:4px;font-size:16px;font-weight:bold;color:rgb(6, 75, 177);}"
        "QLineEdit{border:2px solid rgb(189, 189, 189);}"
        "QLineEdit{font-family:'Century'}")
    srcpath = pathm.GetUiPath()

    signal_PieceInfo = pyqtSignal(str)

    def __init__(self, parent=None, handleflag=0):
        super().__init__(parent)
        self.setWindowTitle("Piece Info")
        self.setWindowIcon(QIcon(os.path.join(self.srcpath, "记录-1.png")))
        # 交互模态设置
        self.setWindowModality(Qt.ApplicationModal)
        # 无边框
        if False:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog)
        # protop info
        self.pieceInfo = ""

        self.bingoLabel = QLabel("Bingo")
        style = (
            "QLabel{font-size:16px;font-weight:bold;color:green;font-family:'Century'}"
            "QLabel{border-radius:4px;border:2px solid rgb(118,154,40);}"
            "QLabel{background-color: #ABABAB;}"
            "QLabel:title{text-align:center}")
        self.bingoLabel.setStyleSheet(style)
        self.bingoLabel.setVisible(False)
        # 手动添加log文件
        if handleflag == 1:
            try:
                # 获取最后一条日志 作为start protop
                recentLog = self.GetRecentLog(pathm.GetLogFile())
                a = recentLog.split("|")
                startProto = datetime.strptime(a[1], "%Y-%m-%d %H:%M:%S")
                self.GetStart = QDateTimeEdit(startProto)  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)
            except:
                self.GetStart = QDateTimeEdit(
                    QDateTime.currentDateTime())  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)

            self.GetFinish = QDateTimeEdit(
                QDateTime.currentDateTime())  # 创建日期+时间的组件
            self.GetFinish.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
            self.GetFinish.setStyleSheet(self.timedateStyle_1)

            # detail item
            self.Detail = QLineEdit()
            self.Detail.setStyleSheet(self.lineEditStyle_1)
            self.Detail.setPlaceholderText("what did you do")
            self.Detail.setClearButtonEnabled(True)
        # 修改最后一条log文件
        else:
            try:
                # 获取最新一条详细日志
                recentLog = self.GetRecentLog(pathm.GetLogFile())
                a = recentLog.split("|")
                startProto = datetime.strptime(a[0], "%Y-%m-%d %H:%M:%S")
                self.GetStart = QDateTimeEdit(startProto)  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)

                finishProto = datetime.strptime(a[1], "%Y-%m-%d %H:%M:%S")
                self.GetFinish = QDateTimeEdit(finishProto)  # 创建日期+时间的组件
                self.GetFinish.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetFinish.setStyleSheet(self.timedateStyle_1)
                # detail item
                self.Detail = QLineEdit()
                self.Detail.setStyleSheet(self.lineEditStyle_1)
                self.Detail.setPlaceholderText(a[-1])
                self.Detail.setClearButtonEnabled(True)
            except:
                self.GetStart = QDateTimeEdit(
                    QDateTime.currentDateTime())  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)

                self.GetFinish = QDateTimeEdit(
                    QDateTime.currentDateTime())  # 创建日期+时间的组件
                self.GetFinish.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetFinish.setStyleSheet(self.timedateStyle_1)
                self.Detail = QLineEdit()
                self.Detail.setStyleSheet(self.lineEditStyle_1)
                self.Detail.setPlaceholderText("try failed ")
                self.Detail.setClearButtonEnabled(True)
        # button area
        buttonbox = QDialogButtonBox(self)
        buttonbox.setOrientation(Qt.Horizontal)
        buttonbox.setStandardButtons(QDialogButtonBox.Cancel
                                     | QDialogButtonBox.Ok)
        buttonbox.accepted.connect(self.isOk)
        buttonbox.rejected.connect(self.isCancle)

        # space item
        spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)

        # frame layout
        layout_2 = QVBoxLayout()

        layout_2.addWidget(self.GetStart, 0)
        layout_2.addWidget(self.GetFinish, 1)
        layout_2.addWidget(self.Detail, 2)
        layout_2.addItem(spacerItem)
        layout_2.addWidget(self.bingoLabel, 3)
        layout_2.addWidget(buttonbox, 4)

        # layout
        self.setLayout(layout_2)
        self.setFixedWidth(400)

    def isOk(self):
        # set info piece
        gap = datetime.strptime(self.GetFinish.text(), "%Y-%m-%d %H:%M:%S") - \
            datetime.strptime(self.GetStart.text(), "%Y-%m-%d %H:%M:%S")
        gap_m = int(gap.seconds / 60)
        # did't change edit line protocol
        try:
            detail = self.Detail.text()
            detail = detail.strip()
            if len(detail) == 0:
                recentLog = self.GetRecentLog(pathm.GetLogFile())
                lastLogTemp = recentLog.split("|")
                detail = lastLogTemp[-1]

            if gap_m > 1:
                pieceInfo = self.GetStart.text()+"|"+self.GetFinish.text() + \
                    "|"+str(gap_m)+"|" + detail
                self.pieceInfo = pieceInfo
                # self.bingoLabel.setVisible(True)
                infoProto = 'T0:' + self.GetStart.text() + '\n' \
                    + 'T1:' + self.GetFinish.text() + '\n' \
                    + 'Gap:' + str(gap_m) + '\n' \
                    + 'Detail:' + detail
                reply = QMessageBox.question(self, 'Save Message', infoProto,
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.Yes:
                    self.emitPiece()
                    self.close()
                    print('emit')
                    event.accept()
                else:
                    event.ignore()
        except:
            self.__reset__()

    def isCancle(self):
        self.close()

    def closeEvent(self, event):
        return

    # 静态方法
    @staticmethod
    def GetPieceInfo(self):
        return self.pieceInfo

    # 信号发射
    def emitPiece(self):
        self.signal_PieceInfo.emit(self.pieceInfo)
        self.GetStart.setDateTime(QDateTime.currentDateTime())
        self.GetFinish.setDateTime(QDateTime.currentDateTime())
        self.pieceInfo = ""

    def __reset__(self):
        # self.bingoLabel.setVisible(False)
        self.GetStart.setDateTime(QDateTime.currentDateTime())
        self.GetFinish.setDateTime(QDateTime.currentDateTime())
        self.pieceInfo = ""

    def GetRecentLog(self, logfile):
        # 参数检查 用try替换
        recentPiece = str()
        try:
            with open(logfile, mode="r", encoding="utf-8") as f:
                allIn = f.readlines()
                cnt = -1
                while (allIn[cnt].endswith('\n') and len(allIn[cnt]) == 1):
                    cnt -= 1
                    if cnt < -10:
                        break
                if not cnt < -10:
                    recentPiece = allIn[cnt]
        except:
            pass
        return recentPiece
Exemplo n.º 16
0
def main():
   os.environ['SDL_VIDEO_CENTERED'] = '1'
   pygame.mixer.init()
   pygame.init()
   pygame.display.set_caption("连连看 powered by Python")
   global dc,psubft,psubfts
   dc = pygame.display.set_mode((SW, SH),pygame.DOUBLEBUF)
   appico=pygame.image.load('data/app.png').convert_alpha()
   pygame.display.set_icon(appico)
   psubft=pygame.font.Font('data/shaonv.ttf', 35)
   psubfts=pygame.font.Font('data/shaonv.ttf', 18)
   global gamecm,gamemap,gamepm
   gamecm = gameComm()
   #gamemap = Imap(dc,0,SW,SH)
   #mymap = gamemap.cellinfo
   #gamepm= PathManager(mymap)
   gamecm.set_background(color=(25,50,24))
   
   app=gui.App()
   c=gui.Container(width=SW,align=0,valign=-1)
   #print c.style.x
   global mainmenu,meswin,misswin
   mainmenu=MenuControl()
   #print mainmenu.rect
   c.add(mainmenu, (SW-166)/2, 200)
   app.init(c)
   #print mainmenu.rect
   global clearsp
   _quit = 0
   clock = pygame.time.Clock()
   pausewin=PauseDialog()
   
   #meswin.connect(gui.K_ESCAPE, quitGame,None)
   #meswin.connect(gui.K_SPACE, show_mainmenu,c)
   qmeswin=MessageDialog(u"你要放弃此游戏返回主菜单吗?", psubft)
   misswin=MessageDialog(u"通过此关,进入下一关!",psubft)
   misswina=MessageDialog(u"恭喜你通关了!",psubft)
   global clicksnd,lasersnd
   clicksnd=load_sound('click.wav')
   clicksnd.set_volume(0.2)
   lasersnd=load_sound('laser.wav')
   lasersnd.set_volume(0.2)
   if pygame.mixer:
        menumusic = os.path.join('data', 'menu.wav')
        pygame.mixer.music.load(menumusic)
        pygame.mixer.music.set_volume(0.2)
        
   gameTime=0    #程序运行总时间
   playTime=0    #游戏中玩的时间
   tmpTime=0     #不在玩的时间
   playTime1=0
   sprizeTime=0
  
   miscid=0
   #pausewin.connect(gui.K_F7, pausewin.close())
   while not _quit:
       delta=clock.tick(30)
       
       gameTime=pygame.time.get_ticks()
       dc.blit(gamecm.backgd,(0,0))
       #pygame.draw.line(dc, (255,0,2), (SW/2,0), (SW/2,SH))       
       for evt in pygame.event.get():
            if evt.type == pygame.QUIT: _quit = 1
            if evt.type == pygame.KEYDOWN:
               if evt.key == pygame.K_ESCAPE: 
                   if mainmenu.selectedm==gameState.gameRun:          #弹出信息窗口
                         mainmenu.selectedm=gameState.gameMess
                         qmeswin.open()
                         pygame.mixer.music.pause()
                   elif mainmenu.selectedm==gameState.gameMess:     #退出信息窗口或退出游戏
                       if qmeswin in app.windows:
                            mainmenu.selectedm=gameState.gameRun
                            pygame.mixer.music.unpause()
                            qmeswin.close()
                       elif meswin in app.windows:
                            _quit=1
                       #elif misswin in app.windows:
                           
               elif evt.key == pygame.K_SPACE or evt.key == pygame.K_RETURN:   ##超时或生命没有了或放弃游戏信息窗口返回主菜单
                   if mainmenu.selectedm==gameState.gameMess:
                         mainmenu.selectedm=gameState.gameBegin
                         if qmeswin in app.windows:
                              qmeswin.close()
                         elif meswin in app.windows:
                              meswin.close()
                         c.add(mainmenu,(SW-166)/2, 200)               
                         gamecm.reinit()
                         pygame.mixer.music.load(menumusic)
                   elif mainmenu.selectedm==gameState.gameNextmiss:   #下一关
                         mainmenu.selectedm=gameState.gameRun
                         gamecm.update_heart(1)
                         #gamecm.update_misslv(1)
                         gamecm.update_score(2000)
                         gamemap.reset_map()
                         gamepm.set_map(gamemap.cellinfo)
                         playTime=0
                         pygame.mixer.music.unpause()
                         misswin.close() 
                   elif mainmenu.selectedm==gameState.gameWin:        #通关-返回主菜单
                         mainmenu.selectedm=gameState.gameBegin
                         misswina.close()
                         c.add(mainmenu,(SW-166)/2, 200)               
                         gamecm.reinit()
                         pygame.mixer.music.load(menumusic) 
               elif evt.key == pygame.K_F8:                        #弹出暂停窗口
                   if mainmenu.selectedm==gameState.gameRun:
                       mainmenu.selectedm=gameState.gamePause
                       pygame.mixer.music.pause()
                       pausewin.open()
                       #c.add(pausewin,(SW-500)/2, 200)
                   elif mainmenu.selectedm==gameState.gamePause:
                       mainmenu.selectedm=gameState.gameRun
                       pygame.mixer.music.unpause()
                       pausewin.close()
               elif evt.key == pygame.K_F4:                       #提示功能
                   if gamecm.hintcount>0:
                       if gamepm.search_path():
                          if gamepm.pot1!=gamepm.pot2 and gamepm.pot1!=(0,0):
                              gamecm.update_hint(-1)
                              gamemap.add_hint(gamepm.pot1)
                              gamemap.add_hint(gamepm.pot2)
                              
            if evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 1:
                 if mainmenu.selectedm==gameState.gameRun:
                     update_Game()
            elif evt.type == pygame.MOUSEBUTTONUP:
                   pygame.event.set_grab(0)
                                           
            if mainmenu.selectedm!=gameState.gameRun: app.event(evt)
            
       
       if mainmenu.selectedm!=gameState.gameRun:           #非游戏进行中
           app.paint(dc)
           tmpTime=gameTime
           playTime1=(gamecm.sptime-0)
           if mainmenu.selectedm==gameState.gameBegin:
               gamemap=None
               gamepm=None
               if not pygame.mixer.music.get_busy(): pygame.mixer.music.play(-1)
           elif mainmenu.selectedm==gameState.gameEnd:  
               _quit=1
           elif mainmenu.selectedm==gameState.gameOver:          #时间超时/无生命点弹出信息窗口
               mainmenu.selectedm=gameState.gameMess
               meswin.open()
           

       elif mainmenu.selectedm==gameState.gameRun:        #游戏进行中
           if mainmenu in c.widgets: c.remove(mainmenu)
           
           if not pygame.mixer.music.get_busy():
               pygame.mixer.music.load('data/'+backmisc[miscid]+'.mid')
               pygame.mixer.music.play()
               print (miscid)
               miscid=miscid+1 
           
           if gamemap is None:
               gamemap=Imap(dc, mainmenu.diflevel,mainmenu.styleset, SW, SH)
               gamecm.reinit()
               playTime=0
           if gamepm is None:
               gamepm=PathManager(gamemap.cellinfo)
           mx,my=pygame.mouse.get_pos()
           px, py = gamemap.transPoint((mx,my))
           if gameTime>tmpTime:
                #playTime=playTime1 + gameTime - tmpTime - sprizeTime
                playTime=playTime+clock.get_time()
                #print gtt,playTime
                if clearsp==True:
                    #sprizeTime=playTime<3000 and playTime or 3000
                    if playTime<3000: 
                        sprizeTime=playTime
                    else:
                        sprizeTime=3000
                    playTime = playTime-sprizeTime
                    #print sprizeTime
                    #playTime1=(playTime-3000)>0 and (playTime1-3000) or playTime1
           if not gamecm.set_spendTime(playTime): 
               mainmenu.selectedm=gameState.gameOver
               meswin=MessageDialog(u"时间到!返回主菜单或退出程序?",psubft)
               pygame.mixer.music.stop()
           gamecm.show_gameinfo(dc)
           gamemap.draw_sprites()
           #if clearsp==True: 
           gamemap.draw_rect(px, py)
           gamemap.draw_hint(clock.get_time(), 300)   
           if clearsp==True: gamepm.draw_line(dc)    

       
       pygame.display.flip()     
       if clearsp==True:
            
            gamemap.remove_cell(gamepm.selected_cell[1])
            gamemap.remove_cell(gamepm.selected_cell[0])
            gamepm.clear_selected_cell()
            gamemap.clear_select()
            lasersnd.play()
            clearsp=False
            pygame.time.delay(150)
            gamemap.map_change(gamecm.misslv)
            spcount,sptemp=gamemap.get_spcount()
            #print spcount
            if spcount==0:  #消除完
                 gamecm.update_misslv(1)
                 if gamecm.misslv>9:      #通关
                     mainmenu.selectedm=gameState.gameWin
                     misswina.open()
                     pygame.mixer.music.stop()
                 else:                        #下一关
                     mainmenu.selectedm=gameState.gameNextmiss
                     misswin.open()
                     pygame.mixer.music.pause()
            else:
                 if not gamepm.search_path():   #没有可消除的
                     if gamecm.heart>0:
                         gamecm.update_heart(-1)
                         gamemap.refresh_map()
                     else:
                         mainmenu.selectedm=gameState.gameOver
                         meswin=MessageDialog(u"你的生命点数没有了!",psubft)
                         pygame.mixer.music.stop()
Exemplo n.º 17
0
class BiRRTstarPlanner(object):
    def __init__(self,
                 planning_range,
                 segment_length,
                 cost_func=None,
                 map_file=None,
                 name=None):
        self.planningRange = planning_range
        self.segmentLength = segment_length
        self.mapFile = map_file
        self.name = name
        self.rrts = BiRRTstar(self.planningRange, self.segmentLength)
        if self.mapFile != None:
            self.rrts.loadMap(self.mapFile)

        self.pathMgr = PathManager(cost_func)
        self.rrts_viz = BiRRTVisualizer(self.rrts, self.pathMgr, name)
        self.cost_func = cost_func

    def connectPath(self, new_s_node, new_g_node, rrts):
        minPath = None

        if new_s_node == None:

            near_node_list = rrts.findNearVertices(rrts.st_kdtree_root,
                                                   new_g_node.pos)

            infoVec = []
            for near_node in near_node_list:
                if rrts.isObstacleFree(new_g_node.pos, near_node.pos):
                    delta_cost = self.cost_func(new_g_node.pos, near_node.pos)
                    total_cost = new_g_node.cost + near_node.cost + delta_cost
                    infoVec.append((near_node, total_cost))

            if len(infoVec) > 0:
                infoVec.sort(key=lambda x: x[1], reverse=False)

                min_cost = infoVec[0][1]
                min_node = infoVec[0][0]
                min_path, min_stringbit = self.getPathFromTwoNodes(
                    min_node, new_g_node, self.rrts)

                minPath = Path(min_path, min_cost, min_stringbit)

        elif new_g_node == None:

            near_node_list = rrts.findNearVertices(rrts.gt_kdtree_root,
                                                   new_s_node.pos)

            infoVec = []
            for near_node in near_node_list:
                if rrts.isObstacleFree(new_s_node.pos, near_node.pos):
                    delta_cost = self.cost_func(new_s_node.pos, near_node.pos)
                    total_cost = new_s_node.cost + near_node.cost + delta_cost
                    infoVec.append((near_node, total_cost))

            if len(infoVec) > 0:
                infoVec.sort(key=lambda x: x[1], reverse=False)

                min_cost = infoVec[0][1]
                min_node = infoVec[0][0]
                min_path, min_stringbit = self.getPathFromTwoNodes(
                    new_s_node, min_node, self.rrts)

                minPath = Path(min_path, min_cost, min_stringbit)

        return minPath

    def getPathFromTwoNodes(self, node_s, node_g, rrts):
        path = []
        stringbit = []

        if node_s == None or node_g == None:
            return path, stringbit

        if rrts.isObstacleFree(node_s.pos, node_g.pos) == False:
            return path, stringbit

        subpathFromStart = rrts.getSubNodeList(node_s, rrts.st_root)
        subpathFromGoal = rrts.getSubNodeList(node_g, rrts.gt_root)

        crossInts = self.rrts.homotopyMgr.world_map.getCrossingSubsegments(
            node_s.pos, node_g.pos)

        for p in reversed(subpathFromStart):
            path.append(p.pos)
        for p in subpathFromGoal:
            path.append(p.pos)

        if len(node_s.homoPath) > 0:
            for c in node_s.homoPath:
                stringbit.append(c)
        if len(crossInts) > 0:
            for crossInt in crossInts:
                stringbit.append(crossInt.name)
        if len(node_g.homoPath) > 0:
            for c in reversed(node_g.homoPath):
                stringbit.append(c)

        return path, stringbit

    def findPaths(self, start, goal, iterationNum, homotopyMgr):

        self.rrts.init(start, goal, self.cost_func, homotopyMgr)
        dividingRefs = homotopyMgr.getDividingRefs(start, goal)
        for dr in dividingRefs:
            self.rrts.dividingRefs.append([dr.open_seg[0], dr.open_seg[1]])

        self.pathMgr.loadSupportingClasses(homotopyMgr.allHomotopyClasses)

        for i in range(iterationNum):
            print "Iter@" + str(i)
            new_s_node = self.rrts.extend(self.rrts.st_kdtree_root,
                                          self.rrts.st_nodes)
            new_g_node = self.rrts.extend(self.rrts.gt_kdtree_root,
                                          self.rrts.gt_nodes)

            min_s_path = self.connectPath(new_s_node, None, self.rrts)
            min_g_path = self.connectPath(None, new_g_node, self.rrts)

            if min_s_path != None:
                self.pathMgr.importPath(min_s_path)
            if min_g_path != None:
                self.pathMgr.importPath(min_g_path)

            self.rrts_viz.currentPaths = self.pathMgr.getPaths()

            self.rrts_viz.update()

        self.rrts_viz.currentPaths = []
        self.rrts_viz.activePaths = self.pathMgr.getPaths()

        self.pathMgr.reportEquivalence(self.rrts.homotopyMgr.reader)

        return self.pathMgr.getPathInfos()
Exemplo n.º 18
0
 def paintEvent(self, event):
     # painter = QPainter(self)
     # bg = QPixmap(os.path.join(pathm.GetUiPath(), r"Infinity-2.jpg"))
     # painter.drawPixmap(self.rect(), bg)
     self.setWindowTitle("IClock")
     self.setWindowIcon(QIcon(os.path.join(pathm.GetUiPath(), r"I-1.ico")))
Exemplo n.º 19
0
    def __init__(self, parent=None, handleflag=0):
        super().__init__(parent)
        self.setWindowTitle("Piece Info")
        self.setWindowIcon(QIcon(os.path.join(self.srcpath, "记录-1.png")))
        # 交互模态设置
        self.setWindowModality(Qt.ApplicationModal)
        # 无边框
        if False:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog)
        # protop info
        self.pieceInfo = ""

        self.bingoLabel = QLabel("Bingo")
        style = (
            "QLabel{font-size:16px;font-weight:bold;color:green;font-family:'Century'}"
            "QLabel{border-radius:4px;border:2px solid rgb(118,154,40);}"
            "QLabel{background-color: #ABABAB;}"
            "QLabel:title{text-align:center}")
        self.bingoLabel.setStyleSheet(style)
        self.bingoLabel.setVisible(False)
        # 手动添加log文件
        if handleflag == 1:
            try:
                # 获取最后一条日志 作为start protop
                recentLog = self.GetRecentLog(pathm.GetLogFile())
                a = recentLog.split("|")
                startProto = datetime.strptime(a[1], "%Y-%m-%d %H:%M:%S")
                self.GetStart = QDateTimeEdit(startProto)  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)
            except:
                self.GetStart = QDateTimeEdit(
                    QDateTime.currentDateTime())  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)

            self.GetFinish = QDateTimeEdit(
                QDateTime.currentDateTime())  # 创建日期+时间的组件
            self.GetFinish.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
            self.GetFinish.setStyleSheet(self.timedateStyle_1)

            # detail item
            self.Detail = QLineEdit()
            self.Detail.setStyleSheet(self.lineEditStyle_1)
            self.Detail.setPlaceholderText("what did you do")
            self.Detail.setClearButtonEnabled(True)
        # 修改最后一条log文件
        else:
            try:
                # 获取最新一条详细日志
                recentLog = self.GetRecentLog(pathm.GetLogFile())
                a = recentLog.split("|")
                startProto = datetime.strptime(a[0], "%Y-%m-%d %H:%M:%S")
                self.GetStart = QDateTimeEdit(startProto)  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)

                finishProto = datetime.strptime(a[1], "%Y-%m-%d %H:%M:%S")
                self.GetFinish = QDateTimeEdit(finishProto)  # 创建日期+时间的组件
                self.GetFinish.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetFinish.setStyleSheet(self.timedateStyle_1)
                # detail item
                self.Detail = QLineEdit()
                self.Detail.setStyleSheet(self.lineEditStyle_1)
                self.Detail.setPlaceholderText(a[-1])
                self.Detail.setClearButtonEnabled(True)
            except:
                self.GetStart = QDateTimeEdit(
                    QDateTime.currentDateTime())  # 创建日期+时间的组件
                self.GetStart.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetStart.setStyleSheet(self.timedateStyle_1)

                self.GetFinish = QDateTimeEdit(
                    QDateTime.currentDateTime())  # 创建日期+时间的组件
                self.GetFinish.setDisplayFormat('yyyy-MM-dd hh:mm:ss')  # 显示样式
                self.GetFinish.setStyleSheet(self.timedateStyle_1)
                self.Detail = QLineEdit()
                self.Detail.setStyleSheet(self.lineEditStyle_1)
                self.Detail.setPlaceholderText("try failed ")
                self.Detail.setClearButtonEnabled(True)
        # button area
        buttonbox = QDialogButtonBox(self)
        buttonbox.setOrientation(Qt.Horizontal)
        buttonbox.setStandardButtons(QDialogButtonBox.Cancel
                                     | QDialogButtonBox.Ok)
        buttonbox.accepted.connect(self.isOk)
        buttonbox.rejected.connect(self.isCancle)

        # space item
        spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)

        # frame layout
        layout_2 = QVBoxLayout()

        layout_2.addWidget(self.GetStart, 0)
        layout_2.addWidget(self.GetFinish, 1)
        layout_2.addWidget(self.Detail, 2)
        layout_2.addItem(spacerItem)
        layout_2.addWidget(self.bingoLabel, 3)
        layout_2.addWidget(buttonbox, 4)

        # layout
        self.setLayout(layout_2)
        self.setFixedWidth(400)
Exemplo n.º 20
0
class MainWindow(QWidget):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self, spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.tick = ClockStatics_V1()
        layout.addWidget(self.tick)
        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet(StyleSheet)
    mainWnd = FramelessWindow()
    mainWnd.setTitleBarHeight(height=30)
    # mainWnd.setWindowTitle('IClock')
    mainWnd.setWindowIcon(QIcon(os.path.join(pathm.GetUiPath(), r"I-1.ico")))
    mainWindowWidth = 360
    # mainWnd.resize(QSize(mainWindowWidth, mainWindowWidth*0.52))
    desktop = QApplication.desktop()
    # 获取显示器分辨率大小
    screenRect = desktop.screenGeometry()
    height = screenRect.height()

    mainWnd.setWidget(MainWindow(mainWnd))  # 把自己的窗口添加进来
    mainWnd.setGeometry(0, height - 50 - mainWindowWidth * 0.52,
                        mainWindowWidth, mainWindowWidth * 0.52)
    # mainWnd.move(0,700)
    mainWnd.show()
    sys.exit(app.exec_())