def createState(self): # state defintion mainState = QState(self.fsm) finalState = QFinalState(self.fsm) self.fsm.setInitialState(mainState) initState = QState(mainState) standbyState = QState(mainState) #transition defition mainState.setInitialState(initState) mainState.addTransition(self.sigStateStop, finalState) initState.addTransition(self.sigInitOk, standbyState) standbyState.addTransition(self.sigError, initState) # #state entered slot connect mainState.entered.connect(self.mainStateEntered) initState.entered.connect(self.initStateEntered) standbyState.entered.connect(self.standbyStateEntered) finalState.entered.connect(self.finalStateEntered) #fsm start self.fsm.start() pass
def makeState(self, parentState, animationFileName): topLevel = QState(parentState) animation = Animation() file = QFile(animationFileName) if file.open(QIODevice.ReadOnly): animation.load(file) frameCount = animation.totalFrames() previousState = None for i in range(frameCount): animation.setCurrentFrame(i) frameState = QState(topLevel) nodeCount = animation.nodeCount() for j in range(nodeCount): frameState.assignProperty(self.m_stickMan.node(j), "pos", animation.nodePos(j)) frameState.setObjectName("frame %d" % i) if previousState is None: topLevel.setInitialState(frameState) else: previousState.addTransition(previousState.propertiesAssigned, frameState) previousState = frameState previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState()) return topLevel
def createState(self): # state defintion mainState = QState(self.fsm) finalState = QFinalState(self.fsm) self.fsm.setInitialState(mainState) initState = QState(mainState) openState = QState(mainState) mainState.setInitialState(initState) standbyState = QState(openState) processingState = QState(openState) openState.setInitialState(standbyState) # transition defition initState.addTransition(self.sigComPortOpened, openState) openState.addTransition(self.sigComPortClosed, initState) standbyState.addTransition(self.sigPowerOn, processingState) processingState.addTransition(self.sigPowerOff, standbyState) initState.entered.connect(self.initStateEntered) openState.entered.connect(self.openStateEntered) standbyState.entered.connect(self.standbyStateEntered) processingState.entered.connect(self.processingStateEntered) # fsm start self.fsm.start() pass
def makeState(self, parentState, animationFileName): topLevel = QState(parentState) animation = Animation() file = QFile(animationFileName) if file.open(QIODevice.ReadOnly): animation.load(file) frameCount = animation.totalFrames() previousState = None for i in range(frameCount): animation.setCurrentFrame(i) frameState = QState(topLevel) nodeCount = animation.nodeCount() for j in range(nodeCount): frameState.assignProperty(self.m_stickMan.node(j), 'pos', animation.nodePos(j)) frameState.setObjectName('frame %d' % i) if previousState is None: topLevel.setInitialState(frameState) else: previousState.addTransition(previousState.propertiesAssigned, frameState) previousState = frameState previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState()) return topLevel
class StartTuto(QDialog): def __init__(self): super(StartTuto, self).__init__() QDialog.__init__(self) self.Next = 0 self.setWindowFlags(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowTitle("لنتعلم معا") self.font = QFont('abdo salem') self.font.setPointSize(20) self.font.setBold(True) self.ex = QPushButton(self) self.ex.setFont(self.font) self.ex.setGeometry(400 + 80, 450, 150, 50) self.ex.setText('خروج') self.ex.setStyleSheet( "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n" "") self.ex.clicked.connect(self.Exit) self.hm = QPushButton(self) self.hm.setFont(self.font) self.hm.setGeometry(200 + 80, 450, 150, 50) self.hm.setText('الرئيسية') self.hm.setStyleSheet( "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n" "") self.hm.clicked.connect(self.home) self.resize(925, 500) self.Ind = [ 'data', 'if', 'for', 'while', 'def', 'class', 'oop', 'exp', 'prj2', 'prj3', 'st' ] self.names = { 'home': [ 'المتغير و\n أنواع البيانات', 'الجملة الشرطية\nIF', 'حلقة التقسيم\nFOR', 'حلقة مادام\nWHILE', 'الدالة\nDEF', 'الفئة\nClass', 'البرمجة كائنية\nالتوجه OOP', 'العبارات', 'المشروع الاول\nRANGE', 'المشروع الثاني\nStr', 'ابدء' ], 'data': [ 'المتغير', 'الأحرف ', 'الأرقام ', 'القائمة', 'القاموس', 'الخطأ\nالصحيح', 'دوال \nانواع البيانات', 'الأمثلة' ], 'if': [ 'الجملة الشرطية\nIF', 'ادوات المقارنة', 'استعمالات\n ELIF و ELSE' ], 'for': ['فكرة \nFOR', 'استعمالات \nFOR', 'امثلة'], 'while': ['فكرة \nWHILE', 'استعمالات \nWHILE', 'امثلة'], 'def': [ 'دالة بسيطة', 'arg\nدالة مع', '*arg\nدالة مع', 'دالة مع\n**kwargs' ], 'class': ['فئة بسيطة\n مع متغير', 'فئة بسيطة\n مع دالة'], 'oop': ['البناء\n__init__', 'خاصية الاراثة', 'دالة\nsuper()'], 'exp': ['عبارة\nreturn', 'عبارة\nassert', 'عبارة\nyield'], 'prj2': ['المشروع'], 'prj3': ['محاكات\nCount', 'محاكات\nFind', 'تطوير\nFind'], 'st': 'exit' } self.Home() def Home(self): self.items = [] for i in range(len(self.names['home'])): item = QPushButton(self) item.setText(self.names['home'][i]) item.setGeometry(395, 350, 120, 80) item.setStyleSheet( "QPushButton:hover{background-color:rgb(241, 90, 36);border:5px solid rgb(0, 97, 157);}\n" "QPushButton{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}QPushButton:pressed{color:white;background-color: rgb(50, 50, 50);border:5px solid rgb(255, 255, 255);}\n" "") self.font.setPointSize(15) item.setFont(self.font) self.items.append(item) exec("""item.clicked.connect(partial(self.IND,i=%i))""" % (i)) self.rootState = QState() self.tiledState = QState(self.rootState) self.centeredState = QState(self.rootState) for i, item in enumerate(self.items): self.tiledState.assignProperty( item, 'pos', QPointF(((i % 6) * 5.3) * 30, ((i // 6) * 5.3) * 30)) self.centeredState.assignProperty(item, 'pos', QPointF()) self.states = QStateMachine() self.states.addState(self.rootState) self.states.setInitialState(self.rootState) self.rootState.setInitialState(self.centeredState) self.group = QParallelAnimationGroup() for i, item in enumerate(self.items): anim = QPropertyAnimation(item, b'pos') anim.setStartValue(QPoint(400, 300)) anim.setDuration(750 + i * 25) anim.setEasingCurve(QEasingCurve.InOutBack) self.group.addAnimation(anim) for u in self.items: trans = self.rootState.addTransition(u.clicked, self.tiledState) trans.addAnimation(self.group) self.states.start() def Exit(self): open('Files/choice', 'w').write('exit') self.close() def home(self): open('Files/choice', 'w').write('home') self.close() def IND(self, i): open('Files/choice', 'a').write(str(i)) if self.Next != 2: self.Next += 1 if self.names[self.Ind[i]] != 'exit': a = self.names[self.Ind[i]] k = 0 for i in self.items[0:len(a)]: i.setText(a[k]) k += 1 for i in self.items[len(a):]: i.hide() else: self.items[-1].hide() else: self.close()
def __init__(self, size, parent=None): super(PadNavigator, self).__init__(parent) self.form = Ui_Form() splash = SplashItem() splash.setZValue(1) pad = FlippablePad(size) flipRotation = QGraphicsRotation(pad) xRotation = QGraphicsRotation(pad) yRotation = QGraphicsRotation(pad) flipRotation.setAxis(Qt.YAxis) xRotation.setAxis(Qt.YAxis) yRotation.setAxis(Qt.XAxis) pad.setTransformations([flipRotation, xRotation, yRotation]) backItem = QGraphicsProxyWidget(pad) widget = QWidget() self.form.setupUi(widget) self.form.hostName.setFocus() backItem.setWidget(widget) backItem.setVisible(False) backItem.setFocus() backItem.setCacheMode(QGraphicsItem.ItemCoordinateCache) r = backItem.rect() backItem.setTransform(QTransform().rotate(180, Qt.YAxis).translate( -r.width() / 2, -r.height() / 2)) selectionItem = RoundRectItem(QRectF(-60, -60, 120, 120), QColor(Qt.gray), pad) selectionItem.setZValue(0.5) smoothSplashMove = QPropertyAnimation(splash) smoothSplashOpacity = QPropertyAnimation(splash) smoothSplashMove.setEasingCurve(QEasingCurve.InQuad) smoothSplashMove.setDuration(250) smoothSplashOpacity.setDuration(250) smoothXSelection = QPropertyAnimation(selectionItem) smoothYSelection = QPropertyAnimation(selectionItem) smoothXRotation = QPropertyAnimation(xRotation) smoothYRotation = QPropertyAnimation(yRotation) smoothXSelection.setDuration(125) smoothYSelection.setDuration(125) smoothXRotation.setDuration(125) smoothYRotation.setDuration(125) smoothXSelection.setEasingCurve(QEasingCurve.InOutQuad) smoothYSelection.setEasingCurve(QEasingCurve.InOutQuad) smoothXRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothYRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipRotation = QPropertyAnimation(flipRotation) smoothFlipScale = QPropertyAnimation(pad) smoothFlipXRotation = QPropertyAnimation(xRotation) smoothFlipYRotation = QPropertyAnimation(yRotation) flipAnimation = QParallelAnimationGroup(self) smoothFlipScale.setDuration(500) smoothFlipRotation.setDuration(500) smoothFlipXRotation.setDuration(500) smoothFlipYRotation.setDuration(500) smoothFlipScale.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipXRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipYRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipScale.setKeyValueAt(0, 1.0) smoothFlipScale.setKeyValueAt(0.5, 0.7) smoothFlipScale.setKeyValueAt(1, 1.0) flipAnimation.addAnimation(smoothFlipRotation) flipAnimation.addAnimation(smoothFlipScale) flipAnimation.addAnimation(smoothFlipXRotation) flipAnimation.addAnimation(smoothFlipYRotation) setVariablesSequence = QSequentialAnimationGroup() setFillAnimation = QPropertyAnimation(pad) setBackItemVisibleAnimation = QPropertyAnimation(backItem) setSelectionItemVisibleAnimation = QPropertyAnimation(selectionItem) setFillAnimation.setDuration(0) setBackItemVisibleAnimation.setDuration(0) setSelectionItemVisibleAnimation.setDuration(0) setVariablesSequence.addPause(250) setVariablesSequence.addAnimation(setBackItemVisibleAnimation) setVariablesSequence.addAnimation(setSelectionItemVisibleAnimation) setVariablesSequence.addAnimation(setFillAnimation) flipAnimation.addAnimation(setVariablesSequence) stateMachine = QStateMachine(self) splashState = QState(stateMachine) frontState = QState(stateMachine) historyState = QHistoryState(frontState) backState = QState(stateMachine) frontState.assignProperty(pad, "fill", False) frontState.assignProperty(splash, "opacity", 0.0) frontState.assignProperty(backItem, "visible", False) frontState.assignProperty(flipRotation, "angle", 0.0) frontState.assignProperty(selectionItem, "visible", True) backState.assignProperty(pad, "fill", True) backState.assignProperty(backItem, "visible", True) backState.assignProperty(xRotation, "angle", 0.0) backState.assignProperty(yRotation, "angle", 0.0) backState.assignProperty(flipRotation, "angle", 180.0) backState.assignProperty(selectionItem, "visible", False) stateMachine.addDefaultAnimation(smoothXRotation) stateMachine.addDefaultAnimation(smoothYRotation) stateMachine.addDefaultAnimation(smoothXSelection) stateMachine.addDefaultAnimation(smoothYSelection) stateMachine.setInitialState(splashState) anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState) anyKeyTransition.setTargetState(frontState) anyKeyTransition.addAnimation(smoothSplashMove) anyKeyTransition.addAnimation(smoothSplashOpacity) enterTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Enter, backState) returnTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Return, backState) backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Enter, frontState) backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Return, frontState) enterTransition.setTargetState(historyState) returnTransition.setTargetState(historyState) backEnterTransition.setTargetState(backState) backReturnTransition.setTargetState(backState) enterTransition.addAnimation(flipAnimation) returnTransition.addAnimation(flipAnimation) backEnterTransition.addAnimation(flipAnimation) backReturnTransition.addAnimation(flipAnimation) columns = size.width() rows = size.height() stateGrid = [] for y in range(rows): stateGrid.append([QState(frontState) for _ in range(columns)]) frontState.setInitialState(stateGrid[0][0]) selectionItem.setPos(pad.iconAt(0, 0).pos()) for y in range(rows): for x in range(columns): state = stateGrid[y][x] rightTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Right, state) leftTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Left, state) downTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Down, state) upTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Up, state) rightTransition.setTargetState(stateGrid[y][(x + 1) % columns]) leftTransition.setTargetState( stateGrid[y][((x - 1) + columns) % columns]) downTransition.setTargetState(stateGrid[(y + 1) % rows][x]) upTransition.setTargetState(stateGrid[((y - 1) + rows) % rows][x]) icon = pad.iconAt(x, y) state.assignProperty(xRotation, "angle", -icon.x() / 6.0) state.assignProperty(yRotation, "angle", icon.y() / 6.0) state.assignProperty(selectionItem, "x", icon.x()) state.assignProperty(selectionItem, "y", icon.y()) frontState.assignProperty(icon, "visible", True) backState.assignProperty(icon, "visible", False) setIconVisibleAnimation = QPropertyAnimation(icon) setIconVisibleAnimation.setDuration(0) setVariablesSequence.addAnimation(setIconVisibleAnimation) scene = QGraphicsScene(self) scene.setBackgroundBrush( QBrush(QPixmap(":/images/blue_angle_swirl.jpg"))) scene.setItemIndexMethod(QGraphicsScene.NoIndex) scene.addItem(pad) scene.setSceneRect(scene.itemsBoundingRect()) self.setScene(scene) sbr = splash.boundingRect() splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2) frontState.assignProperty(splash, "y", splash.y() - 100.0) scene.addItem(splash) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setMinimumSize(50, 50) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) self.setCacheMode(QGraphicsView.CacheBackground) self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing) if QGLFormat.hasOpenGL(): self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers))) stateMachine.start()
class LifeCycle(object): def __init__(self, stickMan, keyReceiver): self.m_stickMan = stickMan self.m_keyReceiver = keyReceiver # Create animation group to be used for all transitions. self.m_animationGroup = QParallelAnimationGroup() stickManNodeCount = self.m_stickMan.nodeCount() self._pas = [] for i in range(stickManNodeCount): pa = QPropertyAnimation(self.m_stickMan.node(i), b"pos") self._pas.append(pa) self.m_animationGroup.addAnimation(pa) # Set up intial state graph. self.m_machine = QStateMachine() self.m_machine.addDefaultAnimation(self.m_animationGroup) self.m_alive = QState(self.m_machine) self.m_alive.setObjectName("alive") # Make it blink when lightning strikes before entering dead animation. lightningBlink = QState(self.m_machine) lightningBlink.assignProperty(self.m_stickMan.scene(), "backgroundBrush", Qt.white) lightningBlink.assignProperty(self.m_stickMan, "penColor", Qt.black) lightningBlink.assignProperty(self.m_stickMan, "fillColor", Qt.white) lightningBlink.assignProperty(self.m_stickMan, "isDead", True) timer = QTimer(lightningBlink) timer.setSingleShot(True) timer.setInterval(100) lightningBlink.entered.connect(timer.start) lightningBlink.exited.connect(timer.stop) self.m_dead = QState(self.m_machine) self.m_dead.assignProperty(self.m_stickMan.scene(), "backgroundBrush", Qt.black) self.m_dead.assignProperty(self.m_stickMan, "penColor", Qt.white) self.m_dead.assignProperty(self.m_stickMan, "fillColor", Qt.black) self.m_dead.setObjectName("dead") # Idle state (sets no properties). self.m_idle = QState(self.m_alive) self.m_idle.setObjectName("idle") self.m_alive.setInitialState(self.m_idle) # Lightning strikes at random. self.m_alive.addTransition(LightningStrikesTransition(lightningBlink)) lightningBlink.addTransition(timer.timeout, self.m_dead) self.m_machine.setInitialState(self.m_alive) def setDeathAnimation(self, fileName): deathAnimation = self.makeState(self.m_dead, fileName) self.m_dead.setInitialState(deathAnimation) def start(self): self.m_machine.start() def addActivity(self, fileName, key): state = self.makeState(self.m_alive, fileName) self.m_alive.addTransition(KeyPressTransition(self.m_keyReceiver, key, state)) def makeState(self, parentState, animationFileName): topLevel = QState(parentState) animation = Animation() file = QFile(animationFileName) if file.open(QIODevice.ReadOnly): animation.load(file) frameCount = animation.totalFrames() previousState = None for i in range(frameCount): animation.setCurrentFrame(i) frameState = QState(topLevel) nodeCount = animation.nodeCount() for j in range(nodeCount): frameState.assignProperty(self.m_stickMan.node(j), "pos", animation.nodePos(j)) frameState.setObjectName("frame %d" % i) if previousState is None: topLevel.setInitialState(frameState) else: previousState.addTransition(previousState.propertiesAssigned, frameState) previousState = frameState previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState()) return topLevel
class NS_Animate(object): def __init__(self, scene, x_max, y_max, back_color): scene = QGraphicsScene(0, 0, x_max, y_max) scene.setBackgroundBrush(back_color) color = [Qt.green, Qt.lightGray, Qt.darkYellow, QtGui.QColor.fromRgb(255, 85, 0)] self.anim_butt = [ QGraphicsRectWidget(color[j]) for j in range(4) ] for j in range(4): scene.addItem(self.anim_butt[j]) self.window = QGraphicsView(scene) self.window.setFrameStyle(0) self.window.setAlignment(Qt.AlignLeft | Qt.AlignTop) self.window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.machine = QStateMachine() self.group = QState() self.timer = QTimer() self.timer.setInterval(1250) self.timer.setSingleShot(True) self.group.entered.connect(self.timer.start) # set states positions anim_state_rects = [ [QRect(x_max*xp/6, y_max*yp/4, 8, 8) for xp in range(4)] for yp in range(4) ] self.states = [ self.createGeometryState( self.anim_butt[0], anim_state_rects[0][j], self.anim_butt[1], anim_state_rects[1][j], self.anim_butt[2], anim_state_rects[2][j], self.anim_butt[3], anim_state_rects[3][j], self.group ) for j in range(4) ] self.group.setInitialState(self.states[0]) self.animationGroup = QParallelAnimationGroup() self.anim = QPropertyAnimation(self.anim_butt[3], 'geometry') self.anim.setDuration(1250) self.anim.setEasingCurve(QEasingCurve.InBack) self.animationGroup.addAnimation(self.anim) self.subGroup = QSequentialAnimationGroup(self.animationGroup) self.subGroup.addPause(100) self.anim = QPropertyAnimation(self.anim_butt[2], 'geometry') self.anim.setDuration(1000) self.anim.setEasingCurve(QEasingCurve.OutElastic) self.subGroup.addAnimation(self.anim) self.subGroup = QSequentialAnimationGroup(self.animationGroup) self.subGroup.addPause(500) self.anim = QPropertyAnimation(self.anim_butt[1], 'geometry') self.anim.setDuration(500) self.anim.setEasingCurve(QEasingCurve.OutElastic) self.subGroup.addAnimation(self.anim) self.subGroup = QSequentialAnimationGroup(self.animationGroup) self.subGroup.addPause(750) self.anim = QPropertyAnimation(self.anim_butt[0], 'geometry') self.anim.setDuration(250) self.anim.setEasingCurve(QEasingCurve.OutElastic) self.subGroup.addAnimation(self.anim) self.stateSwitcher = StateSwitcher(self.machine) self.group.addTransition(self.timer.timeout, self.stateSwitcher) for j in range(4): self.stateSwitcher.addState(self.states[j], self.animationGroup) self.machine.addState(self.group) self.machine.setInitialState(self.group) self.machine.start() # def createGeometryState(self, w1, rect1, w2, rect2, w3, rect3, w4, rect4, parent): result = QState(parent) result.assignProperty(w1, 'geometry', rect1) result.assignProperty(w1, 'geometry', rect1) result.assignProperty(w2, 'geometry', rect2) result.assignProperty(w3, 'geometry', rect3) result.assignProperty(w4, 'geometry', rect4) return result
class SetupMachine(QStateMachine): """ Setup game state machine """ action_complete = pyqtSignal() # emitted when action completed time_out = pyqtSignal() # emitted on clock timeout try_again = pyqtSignal() # emitted if repeat action required not_valid = pyqtSignal() # emitted if turn invalid end_game = pyqtSignal() # emitted to end game players_complete = pyqtSignal() # emitted when players set up radio_complete = pyqtSignal(int, int) # emitted when radio button clicked def __init__(self, scene): super(SetupMachine, self).__init__() self.st_code = qstates.States(scene, self) buttons = scene.buttons.buttons self.rootState = None self.languageState, self.loadState, self.instructState = None, None, None self.nameState, self.setplayersState, self.tileState = None, None, None self.checkState, self.setupState, self.startState = None, None, None self.playState, self.blankState, self.acceptState = None, None, None self.passState, self.challengeState, self.exchangeState = None, None, None self.endState, self.quitState = None, None self.set_states() self.set_signal_transitions() self.set_button_transitions(buttons) states = self.assign_name() self.assign_visibility(states, buttons) self.assign_enabled(states, buttons) self.set_structure() self.set_connections() self.start() # start state machine def set_states(self): """ Create state machine states """ self.rootState = QState() # Initial setup states self.languageState = QState(self.rootState) self.loadState = QState(self.rootState) self.instructState = QState(self.rootState) self.nameState = QState(self.rootState) self.setplayersState = QState(self.rootState) self.tileState = QState(self.rootState) self.checkState = QState(self.rootState) self.setupState = QState(self.rootState) # Wait state between turns self.startState = QState(self.rootState) # Playing states self.playState = QState(self.rootState) self.blankState = QState(self.rootState) self.acceptState = QState(self.rootState) self.passState = QState(self.rootState) self.challengeState = QState(self.rootState) self.exchangeState = QState(self.rootState) self.endState = QState(self.rootState) # End state self.quitState = QFinalState() def set_signal_transitions(self): """ pyqtSignal transitions from states """ self.loadState.addTransition(self.action_complete, self.instructState) self.setplayersState.addTransition(self.players_complete, self.tileState) self.checkState.addTransition(self.action_complete, self.setupState) self.checkState.addTransition(self.try_again, self.tileState) self.setupState.addTransition(self.action_complete, self.startState) self.blankState.addTransition(self.not_valid, self.playState) self.blankState.addTransition(self.try_again, self.blankState) self.blankState.addTransition(self.action_complete, self.acceptState) self.acceptState.addTransition(self.action_complete, self.startState) self.passState.addTransition(self.action_complete, self.startState) self.challengeState.addTransition(self.action_complete, self.startState) self.rootState.addTransition(self.end_game, self.endState) def set_button_transitions(self, buttons): """ Button transitions from states """ self.languageState.addTransition(buttons["nextButton"].pressed, self.loadState) self.instructState.addTransition(buttons["nextButton"].pressed, self.nameState) self.nameState.addTransition(buttons["nextButton"].pressed, self.setplayersState) self.tileState.addTransition(buttons["nextButton"].pressed, self.checkState) self.acceptState.addTransition(buttons["challengeButton"].pressed, self.challengeState) self.rootState.addTransition(buttons["playButton"].pressed, self.playState) self.rootState.addTransition(buttons["passButton"].pressed, self.passState) self.rootState.addTransition(buttons["exchangeButton"].pressed, self.exchangeState) self.playState.addTransition(buttons["acceptButton"].pressed, self.blankState) self.exchangeState.addTransition(buttons["acceptButton"].pressed, self.acceptState) self.rootState.addTransition(buttons["quitButton"].pressed, self.endState) self.endState.addTransition(buttons["backButton"].pressed, self.startState) self.endState.addTransition(buttons["endButton"].pressed, self.quitState) self.endState.addTransition(buttons["newButton"].pressed, self.nameState) def assign_name(self): """ Assign name to property 'state' for each state """ states = {} self.rootState.assignProperty(self, "state", "root") states["root"] = self.rootState self.languageState.assignProperty(self, "state", "language") states["language"] = self.languageState self.loadState.assignProperty(self, "state", "load") states["load"] = self.loadState self.instructState.assignProperty(self, "state", "instruct") states["instruct"] = self.instructState self.nameState.assignProperty(self, "state", "name") states["name"] = self.nameState self.setplayersState.assignProperty(self, "state", "setplayers") states["setplayers"] = self.setplayersState self.tileState.assignProperty(self, "state", "tiles") states["tiles"] = self.tileState self.checkState.assignProperty(self, "state", "check") states["check"] = self.checkState self.setupState.assignProperty(self, "state", "setup") states["setup"] = self.setupState self.startState.assignProperty(self, "state", "start") states["start"] = self.startState self.playState.assignProperty(self, "state", "play") states["play"] = self.playState self.blankState.assignProperty(self, "state", "blank") states["blank"] = self.blankState self.acceptState.assignProperty(self, "state", "accept") states["accept"] = self.acceptState self.passState.assignProperty(self, "state", "pass") states["pass"] = self.passState self.challengeState.assignProperty(self, "state", "challenge") states["challenge"] = self.challengeState self.exchangeState.assignProperty(self, "state", "exchange") states["exchange"] = self.exchangeState self.endState.assignProperty(self, "state", "end") states["end"] = self.endState return states @staticmethod def assign_visibility(states, buttons): """ Assign visibility property for each button in each state """ visibility = { "language": ["nextButton"], "load": [], "instruct": ["nextButton"], "name": ["nextButton"], "tiles": ["nextButton"], "start": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "play": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "blank": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "accept": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "pass": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "exchange": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "challenge": [ "playButton", "acceptButton", "passButton", "challengeButton", "exchangeButton", "quitButton" ], "end": ["newButton", "endButton", "backButton"] } for name, state in states.items(): button_list = [] if name in visibility: button_list = visibility[name] for k, b in buttons.items(): if k in button_list: state.assignProperty(b, "visible", "True") else: state.assignProperty(b, "visible", "False") @staticmethod def assign_enabled(states, buttons): """ Assign enabled property for each button in each state """ enabled = { "language": ["nextButton"], "load": [], "instruct": ["nextButton"], "name": ["nextButton"], "tiles": ["nextButton"], "start": ["playButton", "quitButton"], "play": ["acceptButton", "passButton", "exchangeButton"], "accept": ["challengeButton"], "pass": ["playButton"], "exchange": ["acceptButton"], "end": ["newButton", "endButton", "backButton"] } for name, state in states.items(): button_list = [] if name in enabled: button_list = enabled[name] for k, b in buttons.items(): if k in button_list: state.assignProperty(b, "enabled", "True") else: state.assignProperty(b, "enabled", "False") def set_structure(self): """ Set initial anf final states """ self.addState(self.rootState) self.addState(self.quitState) self.setInitialState(self.rootState) self.rootState.setInitialState(self.languageState) self.finished.connect(self.end_m) def set_connections(self): """ Set enter and exit connections for states """ self.languageState.entered.connect(self.st_code.s_enter_language) self.languageState.exited.connect(self.st_code.s_exit_language) self.loadState.entered.connect(self.st_code.s_enter_load) self.instructState.entered.connect(self.st_code.s_enter_instruct) self.nameState.entered.connect(self.st_code.s_enter_name) self.setplayersState.entered.connect(self.st_code.s_enter_setplayers) self.setplayersState.exited.connect(self.st_code.s_exit_setplayers) self.tileState.entered.connect(self.st_code.s_enter_tile) self.checkState.entered.connect(self.st_code.s_enter_check) self.setupState.entered.connect(self.st_code.s_enter_setup) self.startState.entered.connect(self.st_code.s_enter_start) self.playState.entered.connect(self.st_code.s_enter_play) self.playState.exited.connect(self.st_code.s_exit_play) self.blankState.entered.connect(self.st_code.s_enter_blank) self.acceptState.entered.connect(self.st_code.s_enter_accept) self.passState.entered.connect(self.st_code.s_enter_pass) self.challengeState.entered.connect(self.st_code.s_enter_challenge) self.exchangeState.entered.connect(self.st_code.s_enter_exchange) self.endState.entered.connect(self.st_code.s_enter_end) self.endState.exited.connect(self.st_code.s_exit_end) @staticmethod def end_m(): """ State machine quit """ sys.exit(0)
# Centered. centeredState.assignProperty(item, 'pos', QPointF()) # Ui. view = View(scene) view.setWindowTitle("Animated Tiles") view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate) view.setBackgroundBrush(QBrush(bgPix)) view.setCacheMode(QGraphicsView.CacheBackground) view.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) view.show() states = QStateMachine() states.addState(rootState) states.setInitialState(rootState) rootState.setInitialState(centeredState) group = QParallelAnimationGroup() for i, item in enumerate(items): anim = QPropertyAnimation(item, b'pos') anim.setDuration(750 + i * 25) anim.setEasingCurve(QEasingCurve.InOutBack) group.addAnimation(anim) trans = rootState.addTransition(ellipseButton.pressed, ellipseState) trans.addAnimation(group) trans = rootState.addTransition(figure8Button.pressed, figure8State) trans.addAnimation(group) trans = rootState.addTransition(randomButton.pressed, randomState)
QRect(0, 100, 50, 50), button3, QRect(0, 50, 50, 50), button4, QRect(0, 0, 50, 50), group) state5 = createGeometryState(button1, QRect(100, 100, 50, 50), button2, QRect(150, 100, 50, 50), button3, QRect(100, 150, 50, 50), button4, QRect(150, 150, 50, 50), group) state6 = createGeometryState(button1, QRect(50, 50, 50, 50), button2, QRect(200, 50, 50, 50), button3, QRect(50, 200, 50, 50), button4, QRect(200, 200, 50, 50), group) state7 = createGeometryState(button1, QRect(0, 0, 50, 50), button2, QRect(250, 0, 50, 50), button3, QRect(0, 250, 50, 50), button4, QRect(250, 250, 50, 50), group) group.setInitialState(state1) animationGroup = QParallelAnimationGroup() anim = QPropertyAnimation(button4, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) animationGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup) subGroup.addPause(100) anim = QPropertyAnimation(button3, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) subGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup)
def _setup_states(self): parent_state = QState() # DISCONNECTED disconnected = QState(parent_state) disconnected.assignProperty(self, "status", "Disabled") disconnected.assignProperty(self.followButton, "text", "Follow Mode") disconnected.assignProperty(self.emergencyButton, "enabled", False) disconnected.assignProperty(self.liftButton, "enabled", False) disconnected.assignProperty(self.followButton, "enabled", False) disconnected.assignProperty(self.landButton, "enabled", False) disconnected.entered.connect(self._flight_mode_disconnected_entered) # HOVERING hovering = QState(parent_state) hovering.assignProperty(self, "status", "Hovering...") hovering.assignProperty(self.followButton, "text", "Follow Mode") hovering.assignProperty(self.emergencyButton, "enabled", True) hovering.assignProperty(self.liftButton, "enabled", False) hovering.assignProperty(self.followButton, "enabled", True) hovering.assignProperty(self.landButton, "enabled", True) hovering.entered.connect(self._flight_mode_hovering_entered) # GROUNDED grounded = QState(parent_state) grounded.assignProperty(self, "status", "Grounded") grounded.assignProperty(self.followButton, "text", "Follow Mode") grounded.assignProperty(self.emergencyButton, "enabled", True) grounded.assignProperty(self.liftButton, "enabled", True) grounded.assignProperty(self.followButton, "enabled", False) grounded.assignProperty(self.landButton, "enabled", False) grounded.entered.connect(self._flight_mode_grounded_entered) # FOLLOW follow = QState(parent_state) follow.assignProperty(self, "status", "Follow Mode") follow.assignProperty(self.followButton, "text", "Stop") follow.assignProperty(self.emergencyButton, "enabled", True) follow.assignProperty(self.landButton, "enabled", True) follow.assignProperty(self.followButton, "enabled", False) follow.assignProperty(self.liftButton, "enabled", False) follow.assignProperty(self.recordButton, "enabled", False) follow.entered.connect(self._flight_mode_follow_entered) # LIFT lift = QState(parent_state) lift.assignProperty(self, "status", "Lifting...") lift.assignProperty(self.emergencyButton, "enabled", True) lift.assignProperty(self.liftButton, "enabled", False) lift.assignProperty(self.followButton, "enabled", False) lift.assignProperty(self.landButton, "enabled", True) lift.entered.connect(self._flight_mode_lift_entered) # LAND land = QState(parent_state) land.assignProperty(self, "status", "Landing...") land.assignProperty(self.emergencyButton, "enabled", True) land.assignProperty(self.liftButton, "enabled", False) land.assignProperty(self.followButton, "enabled", False) land.assignProperty(self.landButton, "enabled", False) land.entered.connect(self._flight_mode_land_entered) def add_transition(mode, child_state, parent): transition = FlightModeTransition(mode) transition.setTargetState(child_state) parent.addTransition(transition) add_transition(FlightModeStates.LAND, land, parent_state) add_transition(FlightModeStates.LIFT, lift, parent_state) add_transition(FlightModeStates.HOVERING, hovering, parent_state) add_transition(FlightModeStates.FOLLOW, follow, parent_state) add_transition(FlightModeStates.GROUNDED, grounded, parent_state) add_transition(FlightModeStates.DISCONNECTED, disconnected, parent_state) parent_state.setInitialState(disconnected) self._machine.addState(parent_state) self._machine.setInitialState(parent_state) self._machine.start()
scene.addItem(p2) scene.addItem(p3) scene.addItem(p4) window = QGraphicsView(scene) window.setFrameStyle(0) window.setAlignment(Qt.AlignLeft | Qt.AlignTop) window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) machine = QStateMachine() machine.setGlobalRestorePolicy(QStateMachine.RestoreProperties) group = QState(machine) selectedRect = QRect(86, 86, 128, 128) idleState = QState(group) group.setInitialState(idleState) objects = [p1, p2, p3, p4] createStates(objects, selectedRect, group) createAnimations(objects, machine) machine.setInitialState(group) machine.start() window.resize(300, 300) window.show() sys.exit(app.exec_())
def __init__(self, size, parent=None): super(PadNavigator, self).__init__(parent) self.form = Ui_Form() splash = SplashItem() splash.setZValue(1) pad = FlippablePad(size) flipRotation = QGraphicsRotation(pad) xRotation = QGraphicsRotation(pad) yRotation = QGraphicsRotation(pad) flipRotation.setAxis(Qt.YAxis) xRotation.setAxis(Qt.YAxis) yRotation.setAxis(Qt.XAxis) pad.setTransformations([flipRotation, xRotation, yRotation]) backItem = QGraphicsProxyWidget(pad) widget = QWidget() self.form.setupUi(widget) self.form.hostName.setFocus() backItem.setWidget(widget) backItem.setVisible(False) backItem.setFocus() backItem.setCacheMode(QGraphicsItem.ItemCoordinateCache) r = backItem.rect() backItem.setTransform(QTransform().rotate(180, Qt.YAxis).translate(-r.width()/2, -r.height()/2)) selectionItem = RoundRectItem(QRectF(-60, -60, 120, 120), QColor(Qt.gray), pad) selectionItem.setZValue(0.5) smoothSplashMove = QPropertyAnimation(splash, b'y') smoothSplashOpacity = QPropertyAnimation(splash, b'opacity') smoothSplashMove.setEasingCurve(QEasingCurve.InQuad) smoothSplashMove.setDuration(250) smoothSplashOpacity.setDuration(250) smoothXSelection = QPropertyAnimation(selectionItem, b'x') smoothYSelection = QPropertyAnimation(selectionItem, b'y') smoothXRotation = QPropertyAnimation(xRotation, b'angle') smoothYRotation = QPropertyAnimation(yRotation, b'angle') smoothXSelection.setDuration(125) smoothYSelection.setDuration(125) smoothXRotation.setDuration(125) smoothYRotation.setDuration(125) smoothXSelection.setEasingCurve(QEasingCurve.InOutQuad) smoothYSelection.setEasingCurve(QEasingCurve.InOutQuad) smoothXRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothYRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipRotation = QPropertyAnimation(flipRotation, b'angle') smoothFlipScale = QPropertyAnimation(pad, b'scale') smoothFlipXRotation = QPropertyAnimation(xRotation, b'angle') smoothFlipYRotation = QPropertyAnimation(yRotation, b'angle') flipAnimation = QParallelAnimationGroup(self) smoothFlipScale.setDuration(500) smoothFlipRotation.setDuration(500) smoothFlipXRotation.setDuration(500) smoothFlipYRotation.setDuration(500) smoothFlipScale.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipXRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipYRotation.setEasingCurve(QEasingCurve.InOutQuad) smoothFlipScale.setKeyValueAt(0, 1.0) smoothFlipScale.setKeyValueAt(0.5, 0.7) smoothFlipScale.setKeyValueAt(1, 1.0) flipAnimation.addAnimation(smoothFlipRotation) flipAnimation.addAnimation(smoothFlipScale) flipAnimation.addAnimation(smoothFlipXRotation) flipAnimation.addAnimation(smoothFlipYRotation) setVariablesSequence = QSequentialAnimationGroup() setFillAnimation = QPropertyAnimation(pad, b'fill') setBackItemVisibleAnimation = QPropertyAnimation(backItem, b'visible') setSelectionItemVisibleAnimation = QPropertyAnimation(selectionItem, b'visible') setFillAnimation.setDuration(0) setBackItemVisibleAnimation.setDuration(0) setSelectionItemVisibleAnimation.setDuration(0) setVariablesSequence.addPause(250) setVariablesSequence.addAnimation(setBackItemVisibleAnimation) setVariablesSequence.addAnimation(setSelectionItemVisibleAnimation) setVariablesSequence.addAnimation(setFillAnimation) flipAnimation.addAnimation(setVariablesSequence) stateMachine = QStateMachine(self) splashState = QState(stateMachine) frontState = QState(stateMachine) historyState = QHistoryState(frontState) backState = QState(stateMachine) frontState.assignProperty(pad, "fill", False) frontState.assignProperty(splash, "opacity", 0.0) frontState.assignProperty(backItem, "visible", False) frontState.assignProperty(flipRotation, "angle", 0.0) frontState.assignProperty(selectionItem, "visible", True) backState.assignProperty(pad, "fill", True) backState.assignProperty(backItem, "visible", True) backState.assignProperty(xRotation, "angle", 0.0) backState.assignProperty(yRotation, "angle", 0.0) backState.assignProperty(flipRotation, "angle", 180.0) backState.assignProperty(selectionItem, "visible", False) stateMachine.addDefaultAnimation(smoothXRotation) stateMachine.addDefaultAnimation(smoothYRotation) stateMachine.addDefaultAnimation(smoothXSelection) stateMachine.addDefaultAnimation(smoothYSelection) stateMachine.setInitialState(splashState) anyKeyTransition = QEventTransition(self, QEvent.KeyPress, splashState) anyKeyTransition.setTargetState(frontState) anyKeyTransition.addAnimation(smoothSplashMove) anyKeyTransition.addAnimation(smoothSplashOpacity) enterTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Enter, backState) returnTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Return, backState) backEnterTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Enter, frontState) backReturnTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Return, frontState) enterTransition.setTargetState(historyState) returnTransition.setTargetState(historyState) backEnterTransition.setTargetState(backState) backReturnTransition.setTargetState(backState) enterTransition.addAnimation(flipAnimation) returnTransition.addAnimation(flipAnimation) backEnterTransition.addAnimation(flipAnimation) backReturnTransition.addAnimation(flipAnimation) columns = size.width() rows = size.height() stateGrid = [] for y in range(rows): stateGrid.append([QState(frontState) for _ in range(columns)]) frontState.setInitialState(stateGrid[0][0]) selectionItem.setPos(pad.iconAt(0, 0).pos()) for y in range(rows): for x in range(columns): state = stateGrid[y][x] rightTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Right, state) leftTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Left, state) downTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Down, state) upTransition = QKeyEventTransition(self, QEvent.KeyPress, Qt.Key_Up, state) rightTransition.setTargetState(stateGrid[y][(x + 1) % columns]) leftTransition.setTargetState(stateGrid[y][((x - 1) + columns) % columns]) downTransition.setTargetState(stateGrid[(y + 1) % rows][x]) upTransition.setTargetState(stateGrid[((y - 1) + rows) % rows][x]) icon = pad.iconAt(x, y) state.assignProperty(xRotation, "angle", -icon.x() / 6.0) state.assignProperty(yRotation, "angle", icon.y() / 6.0) state.assignProperty(selectionItem, "x", icon.x()) state.assignProperty(selectionItem, "y", icon.y()) frontState.assignProperty(icon, "visible", True) backState.assignProperty(icon, "visible", False) setIconVisibleAnimation = QPropertyAnimation(icon, b'visible') setIconVisibleAnimation.setDuration(0) setVariablesSequence.addAnimation(setIconVisibleAnimation) scene = QGraphicsScene(self) scene.setBackgroundBrush(QBrush(QPixmap(":/images/blue_angle_swirl.jpg"))) scene.setItemIndexMethod(QGraphicsScene.NoIndex) scene.addItem(pad) scene.setSceneRect(scene.itemsBoundingRect()) self.setScene(scene) sbr = splash.boundingRect() splash.setPos(-sbr.width() / 2, scene.sceneRect().top() - 2) frontState.assignProperty(splash, "y", splash.y() - 100.0) scene.addItem(splash) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setMinimumSize(50, 50) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) self.setCacheMode(QGraphicsView.CacheBackground) self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing) if QGLFormat.hasOpenGL(): self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers))) stateMachine.start()
# Centered. centeredState.assignProperty(item, 'pos', QPointF()) # Ui. view = View(scene) view.setWindowTitle("Animated Tiles") view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate) view.setBackgroundBrush(QBrush(bgPix)) view.setCacheMode(QGraphicsView.CacheBackground) view.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) view.show() states = QStateMachine() states.addState(rootState) states.setInitialState(rootState) rootState.setInitialState(centeredState) group = QParallelAnimationGroup() for i, item in enumerate(items): anim = QPropertyAnimation(item, b'pos') anim.setDuration(750 + i * 25) anim.setEasingCurve(QEasingCurve.InOutBack) group.addAnimation(anim) trans = rootState.addTransition(ellipseButton.pressed, ellipseState) trans.addAnimation(group) trans = rootState.addTransition(figure8Button.pressed, figure8State) trans.addAnimation(group) trans = rootState.addTransition(randomButton.pressed, randomState)
class LifeCycle(object): def __init__(self, stickMan, keyReceiver): self.m_stickMan = stickMan self.m_keyReceiver = keyReceiver # Create animation group to be used for all transitions. self.m_animationGroup = QParallelAnimationGroup() stickManNodeCount = self.m_stickMan.nodeCount() self._pas = [] for i in range(stickManNodeCount): pa = QPropertyAnimation(self.m_stickMan.node(i), 'pos') self._pas.append(pa) self.m_animationGroup.addAnimation(pa) # Set up intial state graph. self.m_machine = QStateMachine() self.m_machine.addDefaultAnimation(self.m_animationGroup) self.m_alive = QState(self.m_machine) self.m_alive.setObjectName('alive') # Make it blink when lightning strikes before entering dead animation. lightningBlink = QState(self.m_machine) lightningBlink.assignProperty(self.m_stickMan.scene(), 'backgroundBrush', Qt.white) lightningBlink.assignProperty(self.m_stickMan, 'penColor', Qt.black) lightningBlink.assignProperty(self.m_stickMan, 'fillColor', Qt.white) lightningBlink.assignProperty(self.m_stickMan, 'isDead', True) timer = QTimer(lightningBlink) timer.setSingleShot(True) timer.setInterval(100) lightningBlink.entered.connect(timer.start) lightningBlink.exited.connect(timer.stop) self.m_dead = QState(self.m_machine) self.m_dead.assignProperty(self.m_stickMan.scene(), 'backgroundBrush', Qt.black) self.m_dead.assignProperty(self.m_stickMan, 'penColor', Qt.white) self.m_dead.assignProperty(self.m_stickMan, 'fillColor', Qt.black) self.m_dead.setObjectName('dead') # Idle state (sets no properties). self.m_idle = QState(self.m_alive) self.m_idle.setObjectName('idle') self.m_alive.setInitialState(self.m_idle) # Lightning strikes at random. self.m_alive.addTransition(LightningStrikesTransition(lightningBlink)) lightningBlink.addTransition(timer.timeout, self.m_dead) self.m_machine.setInitialState(self.m_alive) def setDeathAnimation(self, fileName): deathAnimation = self.makeState(self.m_dead, fileName) self.m_dead.setInitialState(deathAnimation) def start(self): self.m_machine.start() def addActivity(self, fileName, key): state = self.makeState(self.m_alive, fileName) self.m_alive.addTransition( KeyPressTransition(self.m_keyReceiver, key, state)) def makeState(self, parentState, animationFileName): topLevel = QState(parentState) animation = Animation() file = QFile(animationFileName) if file.open(QIODevice.ReadOnly): animation.load(file) frameCount = animation.totalFrames() previousState = None for i in range(frameCount): animation.setCurrentFrame(i) frameState = QState(topLevel) nodeCount = animation.nodeCount() for j in range(nodeCount): frameState.assignProperty(self.m_stickMan.node(j), 'pos', animation.nodePos(j)) frameState.setObjectName('frame %d' % i) if previousState is None: topLevel.setInitialState(frameState) else: previousState.addTransition(previousState.propertiesAssigned, frameState) previousState = frameState previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState()) return topLevel
state5 = createGeometryState(button1, QRect(100, 100, 50, 50), button2, QRect(150, 100, 50, 50), button3, QRect(100, 150, 50, 50), button4, QRect(150, 150, 50, 50), group) state6 = createGeometryState(button1, QRect(50, 50, 50, 50), button2, QRect(200, 50, 50, 50), button3, QRect(50, 200, 50, 50), button4, QRect(200, 200, 50, 50), group) state7 = createGeometryState(button1, QRect(0, 0, 50, 50), button2, QRect(250, 0, 50, 50), button3, QRect(0, 250, 50, 50), button4, QRect(250, 250, 50, 50), group) group.setInitialState(state1) animationGroup = QParallelAnimationGroup() anim = QPropertyAnimation(button4, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) animationGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup) subGroup.addPause(100) anim = QPropertyAnimation(button3, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) subGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup)
scene.addItem(p2) scene.addItem(p3) scene.addItem(p4) window = QGraphicsView(scene) window.setFrameStyle(0) window.setAlignment(Qt.AlignLeft | Qt.AlignTop) window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) machine = QStateMachine() machine.setGlobalRestorePolicy(QStateMachine.RestoreProperties) group = QState(machine) selectedRect = QRect(86, 86, 128, 128) idleState = QState(group) group.setInitialState(idleState) objects = [p1, p2, p3, p4] createStates(objects, selectedRect, group) createAnimations(objects, machine) machine.setInitialState(group) machine.start() window.resize(300, 300) window.show() sys.exit(app.exec_())
class SetupMachine(QStateMachine): """ Setup game state machine """ action_complete = pyqtSignal() # emitted when action completed def __init__(self, scene): super(SetupMachine, self).__init__() self.st_code = qstates.States(scene, self) self.rootState, self.waitState, self.setupState, self.loadState = None, None, None, None self.saveState, self.solveState, self.stepState, self.clearState = None, None, None, None self.playState, self.checkState, self.hintState, self.restartState = None, None, None, None self.printState, self.quitState = None, None buttons = scene.buttons.buttons self.set_states() self.set_signal_transitions() self.set_button_transitions(buttons) states = self.assign_name() self.assign_visibility(states, buttons) self.assign_enabled(states, buttons) self.set_structure() self.set_connections() self.start() # start state machine def set_states(self): """ Create state machine states """ self.rootState = QState() # Initial setup states self.waitState = QState(self.rootState) self.setupState = QState(self.rootState) self.loadState = QState(self.rootState) self.saveState = QState(self.rootState) self.solveState = QState(self.rootState) self.stepState = QState(self.rootState) self.clearState = QState(self.rootState) self.playState = QState(self.rootState) self.checkState = QState(self.rootState) self.hintState = QState(self.rootState) self.restartState = QState(self.rootState) self.printState = QState(self.rootState) # End state self.quitState = QFinalState() def set_signal_transitions(self): """ pyqtSignal transitions from states """ self.setupState.addTransition(self.action_complete, self.waitState) self.solveState.addTransition(self.action_complete, self.waitState) self.stepState.addTransition(self.action_complete, self.waitState) self.loadState.addTransition(self.action_complete, self.waitState) self.saveState.addTransition(self.action_complete, self.waitState) self.clearState.addTransition(self.action_complete, self.waitState) self.hintState.addTransition(self.action_complete, self.waitState) self.restartState.addTransition(self.action_complete, self.waitState) self.printState.addTransition(self.action_complete, self.waitState) self.checkState.addTransition(self.action_complete, self.waitState) def set_button_transitions(self, buttons): """ Button transitions from states """ self.waitState.addTransition(buttons["setupButton"].pressed, self.setupState) self.setupState.addTransition(buttons["setupButton"].pressed, self.waitState) self.waitState.addTransition(buttons["solveButton"].pressed, self.solveState) self.waitState.addTransition(buttons["stepButton"].pressed, self.stepState) self.waitState.addTransition(buttons["loadButton"].pressed, self.loadState) self.waitState.addTransition(buttons["saveButton"].pressed, self.saveState) self.waitState.addTransition(buttons["clearButton"].pressed, self.clearState) self.waitState.addTransition(buttons["playButton"].pressed, self.playState) self.playState.addTransition(buttons["playButton"].pressed, self.waitState) self.waitState.addTransition(buttons["hintButton"].pressed, self.hintState) self.hintState.addTransition(buttons["hintButton"].pressed, self.waitState) self.waitState.addTransition(buttons["restartButton"].pressed, self.restartState) self.waitState.addTransition(buttons["printButton"].pressed, self.printState) self.waitState.addTransition(buttons["checkButton"].pressed, self.checkState) self.checkState.addTransition(buttons["checkButton"].pressed, self.checkState) self.rootState.addTransition(buttons["quitButton"].pressed, self.quitState) def assign_name(self): """ Assign name to property 'state' for each state """ states = {} self.rootState.assignProperty(self, "state", "root") states["root"] = self.rootState self.waitState.assignProperty(self, "state", "wait") states["wait"] = self.waitState self.setupState.assignProperty(self, "state", "setup") states["setup"] = self.setupState self.loadState.assignProperty(self, "state", "load") states["load"] = self.loadState self.saveState.assignProperty(self, "state", "save") states["save"] = self.saveState self.clearState.assignProperty(self, "state", "clear") states["clear"] = self.clearState self.solveState.assignProperty(self, "state", "solve") states["solve"] = self.solveState self.stepState.assignProperty(self, "state", "step") states["step"] = self.stepState self.playState.assignProperty(self, "state", "play") states["play"] = self.playState self.hintState.assignProperty(self, "state", "hint") states["hint"] = self.hintState self.restartState.assignProperty(self, "state", "restart") states["restart"] = self.restartState self.printState.assignProperty(self, "state", "print") states["print"] = self.printState self.checkState.assignProperty(self, "state", "check") states["check"] = self.checkState return states @staticmethod def assign_visibility(states, buttons): """ Assign visibility property for each button in each state """ visibility = { "wait": [ "setupButton", "checkButton", "loadButton", "saveButton", "clearButton", "playButton", "printButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "load": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "save": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "setup": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "solve": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "step": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "play": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "hint": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "print": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "check": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ] } for name, state in states.items(): button_list = [] if name in visibility: button_list = visibility[name] for k, b in buttons.items(): if k in button_list: state.assignProperty(b, "visible", "True") else: state.assignProperty(b, "visible", "False") @staticmethod def assign_enabled(states, buttons): """ Assign enabled property for each button in each state """ enabled = { "wait": [ "setupButton", "checkButton", "loadButton", "saveButton", "clearButton", "playButton", "printButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "load": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "save": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "setup": [ "setupButton", "loadButton", "saveButton", "printButton", "clearButton", "quitButton", "hintButton", "restartButton" ], "solve": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "step": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "play": [ "checkButton", "saveButton", "playButton", "printButton", "clearButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "hint": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "print": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ], "check": [ "setupButton", "checkButton", "loadButton", "saveButton", "printButton", "clearButton", "playButton", "solveButton", "stepButton", "quitButton", "hintButton", "restartButton" ] } for name, state in states.items(): button_list = [] if name in enabled: button_list = enabled[name] for k, b in buttons.items(): if k in button_list: state.assignProperty(b, "enabled", "True") else: state.assignProperty(b, "enabled", "False") def set_structure(self): """ Set initial anf final states """ self.addState(self.rootState) self.addState(self.quitState) self.setInitialState(self.rootState) self.rootState.setInitialState(self.waitState) self.finished.connect(self.end_m) def set_connections(self): """ Set enter and exit connections for states """ self.waitState.entered.connect(self.st_code.s_enter_wait) self.waitState.exited.connect(self.st_code.s_exit_wait) self.setupState.entered.connect(self.st_code.s_enter_setup) self.setupState.exited.connect(self.st_code.s_exit_setup) self.loadState.entered.connect(self.st_code.s_enter_load) self.loadState.exited.connect(self.st_code.s_exit_load) self.saveState.entered.connect(self.st_code.s_enter_save) self.saveState.exited.connect(self.st_code.s_exit_save) self.solveState.entered.connect(self.st_code.s_enter_solve) self.solveState.exited.connect(self.st_code.s_exit_solve) self.stepState.entered.connect(self.st_code.s_enter_step) self.stepState.exited.connect(self.st_code.s_exit_step) self.clearState.entered.connect(self.st_code.s_enter_clear) self.clearState.exited.connect(self.st_code.s_exit_clear) self.playState.entered.connect(self.st_code.s_enter_play) self.playState.exited.connect(self.st_code.s_exit_play) self.hintState.entered.connect(self.st_code.s_enter_hint) self.hintState.exited.connect(self.st_code.s_exit_hint) self.restartState.entered.connect(self.st_code.s_enter_restart) self.restartState.exited.connect(self.st_code.s_exit_restart) self.printState.entered.connect(self.st_code.s_enter_print) self.printState.exited.connect(self.st_code.s_exit_print) self.checkState.entered.connect(self.st_code.s_enter_check) self.checkState.exited.connect(self.st_code.s_exit_check) @staticmethod def end_m(): """ State machine quit """ sys.exit(0)