saiki987/js_ui_samples

state machine

Opened this issue · 0 comments

from transitions import Machine

class 物質(object):
def 状態(self):
return self.state_map[self.state]

物体 = 物質()

states=['固体', '液体', '気体', 'プラズマ']

And some transitions between states. We're lazy, so we'll leave out

the inverse phase transitions (freezing, condensation, etc.).

transitions = [
['融解', '固体', '液体'],
['蒸発', '液体', '気体'],
['昇華', '固体', '気体'],
['イオン化', '気体', 'プラズマ'],
]

Initialize

machine = Machine(物体, states=states, transitions=transitions, initial='液体')

Now 物体 maintains state...

物体.state

And that state can change...

物体.蒸発()
物体.state

二酸化炭素

class CO2(物質):
state_map = {
'固体': 'ドライアイス',
'液体': '液体',
'気体': '気体',
'プラズマ': 'プラズマ',
}

二酸化炭素 = CO2()
Machine(二酸化炭素, states=states, transitions=transitions, initial='固体')

変化前 = 二酸化炭素.状態()
二酸化炭素.昇華()
変化後 = 二酸化炭素.状態()

f'{変化前}が昇華して{変化後}になりました。'

グラフ化

import io
from transitions.extensions import GraphMachine
from IPython.display import Image, display
from graphviz.graphs import Digraph

文字化け対応

https://github.com/pytransitions/transitions/blob/f3e01de336d24005b8c4abb012185a89af9727d9/transitions/extensions/diagrams.py#L77

GraphMachine.style_attributes['node']['default']['fontname'] = 'MS Gothic'
GraphMachine.style_attributes['graph']['default']['fontname'] = 'MS Gothic'
GraphMachine.style_attributes['edge']['default']['fontname'] = 'MS Gothic'

class グラフ化可能物質():
# graph object is created by the machine
def show_graph(self, **kwargs):
stream = io.BytesIO()
graph: Digraph = self.get_graph(**kwargs)
graph.draw(stream, prog='dot', format='png')
print(type(graph))
display(Image(stream.getvalue()))

model = グラフ化可能物質()
machine = GraphMachine(model=model, states=states, transitions=transitions,
show_auto_transitions=True, initial='固体')

machine.add_ordered_transitions(trigger='次の相', loop=True)

machine.auto_transitions_markup = False
model.show_graph()