Debian Codegraph @

texmf-dist/source/latex/wargame/utils/wgexport.py

raw
1 #!/usr/bin/env python
2 # Script collected from other scripts
3 #
4 # ../vassal/vassal.py
5 # latexexporter.py
6 # main.py
7 #
8 # ====================================================================
9 # From ../vassal/vassal.py
10 # Script collected from other scripts
11 #
12 # ../common/singleton.py
13 # ../common/verbose.py
14 # ../common/verboseguard.py
15 # base.py
16 # element.py
17 # globalkey.py
18 # gameelements.py
19 # mapelements.py
20 # globalproperty.py
21 # turn.py
22 # documentation.py
23 # player.py
24 # chessclock.py
25 # widget.py
26 # grid.py
27 # zone.py
28 # board.py
29 # map.py
30 # chart.py
31 # command.py
32 # trait.py
33 # withtraits.py
34 # traits/area.py
35 # traits/dynamicproperty.py
36 # traits/globalproperty.py
37 # traits/prototype.py
38 # traits/place.py
39 # traits/report.py
40 # traits/calculatedproperty.py
41 # traits/restrictcommand.py
42 # traits/label.py
43 # traits/layer.py
44 # traits/globalcommand.py
45 # traits/globalhotkey.py
46 # traits/nostack.py
47 # traits/deselect.py
48 # traits/restrictaccess.py
49 # traits/rotate.py
50 # traits/stack.py
51 # traits/mark.py
52 # traits/mask.py
53 # traits/trail.py
54 # traits/delete.py
55 # traits/sendto.py
56 # traits/moved.py
57 # traits/skel.py
58 # traits/submenu.py
59 # traits/basic.py
60 # traits/trigger.py
61 # traits/nonrect.py
62 # traits/click.py
63 # game.py
64 # buildfile.py
65 # moduledata.py
66 # save.py
67 # vsav.py
68 # vmod.py
69 # upgrade.py
70 # exporter.py
71 #
72 # ====================================================================
73 # From ../common/singleton.py
74 # ====================================================================
75 class Singleton(type):
76 '''Meta base class for singletons'''
77 _instances = {}
78 def __call__(cls, *args, **kwargs):
79 '''Create the singleton object or returned existing
80
81 Parameters
82 ----------
83 args : tuple
84 Arguments
85 kwargs : dict
86 Keyword arguments
87 '''
88 if cls not in cls._instances:
89 cls._instances[cls] = \
90 super(Singleton, cls).__call__(*args, **kwargs)
91 return cls._instances[cls]
92
93 #
94 # EOF
95 #
96 # ====================================================================
97 # From ../common/verbose.py
98 # --------------------------------------------------------------------
99
100 class Verbose(metaclass=Singleton):
101 def __init__(self,verbose=False):
102 '''Singleton for writing message to screen, contigent on setting
103
104 Parameters
105 ----------
106 verbose : bool
107 Whether to show messages or not
108 '''
109 self._indent = ''
110 self._verbose = verbose
111
112 def setVerbose(self,verbose):
113 '''Set whether to print or not
114
115 Parameters
116 ----------
117 verbose : bool
118 Whether to show messages or not
119 '''
120 self._verbose = verbose
121
122 @property
123 def verbose(self):
124 '''Test if this is verbose'''
125 return self._verbose
126
127 def message(self,*args,**kwargs):
128 '''Write messsage if verbose
129
130 Parameters
131 ----------
132 args : tuple
133 Arguments
134 kwargs : dict
135 Keyword arguments
136 '''
137 if not self._verbose: return
138 if not kwargs.pop('noindent', False):
139 print(self._indent,end='')
140 print(*args,**kwargs)
141
142 def incr(self):
143 '''Increment indention'''
144 self._indent += ' '
145
146 def decr(self):
147 '''Decrement indention'''
148 if len(self._indent) > 0:
149 self._indent = self._indent[:-1]
150
151 #
152 # EOF
153 #
154 # ====================================================================
155 # From ../common/verboseguard.py
156 # --------------------------------------------------------------------
157
158 class VerboseGuard:
159 def __init__(self,*args,**kwargs):
160 '''A guard pattern that increases verbose indention
161
162 This is a context manager. The arguments passed are used for
163 an initial message, before increasinig indention.
164
165 Parameters
166 ----------
167 args : tuple
168 Arguments
169 kwargs : dict
170 Keyword arguments
171 '''
172 Verbose().message(*args,**kwargs)
173
174 def __bool_(self):
175 '''Test if verbose'''
176 return Verbose().verbose
177
178 def __enter__(self):
179 '''Enter context'''
180 Verbose().incr()
181 return self
182
183 def __exit__(self,*args):
184 '''Exit context'''
185 Verbose().decr()
186
187 def __call__(self,*args,**kwargs):
188 '''Write a message at current indention level
189
190 Parameters
191 ----------
192 args : tuple
193 Arguments
194 kwargs : dict
195 Keyword arguments
196 '''
197 Verbose().message(*args,**kwargs)
198
199 #
200 # EOF
201 #
202 # ====================================================================
203 # From base.py
204 # ====================================================================
205 # Key encoding
206 SHIFT = 65
207 CTRL = 130
208 ALT = 520
209 CTRL_SHIFT = CTRL+SHIFT
210 ALT_SHIFT = ALT+SHIFT
211 NONE = '\ue004'
212 NONE_MOD = 0
213
214 # --------------------------------------------------------------------
215 def key(let,mod=CTRL):
216
217 '''Encode a key sequence
218
219 Parameters
220 ----------
221 let : str
222 Key code (Letter)
223 mod : int
224 Modifier mask
225 '''
226 return f'{ord(let)},{mod}'
227
228 # --------------------------------------------------------------------
229 #
230 def hexcolor(s):
231 if isinstance(s,str):
232 s = s.replace('0x','')
233 if len(s) == 3:
234 r, g, b = [int(si,16)/16 for si in s]
235 elif len(s) == 6:
236 r = int(s[0:2],16) / 256
237 g = int(s[2:4],16) / 256
238 b = int(s[4:6],16) / 256
239 else:
240 raise RuntimeError('3 or 6 hexadecimal digits for color string')
241 elif isinstance(s,int):
242 r = ((s >> 16) & 0xFF) / 256
243 g = ((s >> 8) & 0xFF) / 256
244 b = ((s >> 0) & 0xFF) / 256
245 else:
246 raise RuntimeError('Hex colour must be string or integer')
247
248 return rgb(int(r*256),int(g*256),int(b*256))
249
250 # --------------------------------------------------------------------
251 # Colour encoding
252 def rgb(r,g,b):
253 '''Encode RGB colour
254
255 Parameters
256 ----------
257 r : int
258 Red channel
259 g : int
260 Green channel
261 b : int
262 Blue channel
263
264 Returns
265 -------
266 colour : str
267 RGB colour as a string
268 '''
269 return ','.join([str(r),str(g),str(b)])
270
271 # --------------------------------------------------------------------
272 def rgba(r,g,b,a):
273 '''Encode RGBA colour
274
275 Parameters
276 ----------
277 r : int
278 Red channel
279 g : int
280 Green channel
281 b : int
282 Blue channel
283 a : int
284 Alpha channel
285
286 Returns
287 -------
288 colour : str
289 RGBA colour as a string
290 '''
291 return ','.join([str(r),str(g),str(b),str(a)])
292
293 # --------------------------------------------------------------------
294 def dumpTree(node,ind=''):
295 '''Dump the tree of nodes
296
297 Parameters
298 ----------
299 node : xml.dom.Node
300 Node to dump
301 ind : str
302 Current indent
303 '''
304 print(f'{ind}{node}')
305 for c in node.childNodes:
306 dumpTree(c,ind+' ')
307
308 # --------------------------------------------------------------------
309 def registerElement(cls):
310
311 Element.known_tags[cls.TAG] = cls
312
313
314 #
315 # EOF
316 #
317 # ====================================================================
318 # From element.py
319
320 # ====================================================================
321 class Element:
322 BUILD = 'VASSAL.build.'
323 MODULE = BUILD + 'module.'
324 WIDGET = BUILD + 'widget.'
325 MAP = MODULE + 'map.'
326 PICKER = MAP + 'boardPicker.'
327 BOARD = PICKER + 'board.'
328 known_tags = {}
329
330 def __init__(self,parent,tag,node=None,**kwargs):
331 '''Create a new element
332
333 Parameters
334 ----------
335 parent : Element
336 Parent element to add this element to
337 tag : str
338 Element tag
339 node : xml.dom.Node
340 If not None, then read attributes from that. Otherwise
341 set elements according to kwargs
342 kwargs : dict
343 Attribute keys and values. Only used if node is None
344 '''
345 if parent is not None:
346 self._root = parent._root
347 self._node = (node if node is not None else
348 parent.addNode(tag,**kwargs))
349 else:
350 self._root = None
351 self._node = None
352
353 # ----------------------------------------------------------------
354 # Attributes
355 def __contains__(self,key):
356 '''Check if element has attribute key'''
357 return self.hasAttribute(key)
358
359 def __getitem__(self,key):
360 '''Get attribute key value'''
361 return self.getAttribute(key)
362
363 def __setitem__(self,key,value):
364 '''Set attribute key value'''
365 self.setAttribute(key,value)
366
367 def hasAttribute(self,k):
368 '''Check if element has attribute '''
369 return self._node.hasAttribute(k)
370
371 def getAttribute(self,k):
372 '''Get attribute key value'''
373 return self._node.getAttribute(k)
374
375 def setAttribute(self,k,v):
376 '''Set attribute key value'''
377 self._node.setAttribute(k,str(v).lower()
378 if isinstance(v,bool) else str(v))
379
380 def setAttributes(self,**kwargs):
381 '''Set attributes to dictionary key and value'''
382 for k,v in kwargs.items():
383 self.setAttribute(k,v)
384
385 def getAttributes(self):
386 '''Get attributes as dict'''
387 return self._node.attributes
388
389 # ----------------------------------------------------------------
390 # Plain nodes
391 def getChildren(self):
392 '''Get child nodes (xml.dom.Node)'''
393 return self._node.childNodes
394
395 # ----------------------------------------------------------------
396 # Getters
397 #
398 # First generics
399 def getAsDict(self,tag='',key=None,enable=True):
400 '''Get elements with a specific tag as a dictionary
401 where the key is given by attribute key'''
402 cont = self._node.getElementsByTagName(tag)
403 if not enable or key is None:
404 return cont
405
406 return {e.getAttribute(key): e for e in cont}
407
408 def getAsOne(self,tag='',single=True):
409 '''Get elements with a specific tag, as a list.
410 If single is true, then assume we only have one such
411 child element, or fail.'''
412 cont = self._node.getElementsByTagName(tag)
413 if single and len(cont) != 1:
414 return None
415 return cont
416
417 def getElementsByKey(self,cls,key='',asdict=True):
418 '''Get elments of a specific class as a dictionary,
419 where the key is set by the key attribute.'''
420 cont = self.getAsDict(cls.TAG,key,asdict)
421 if cont is None: return None
422
423 if not asdict: return [cls(self,node=n) for n in cont]
424
425 return {k : cls(self,node=n) for k, n in cont.items()}
426
427 def getAllElements(self,cls,single=True):
428 '''Get elements with a specific tag, as a list. If single is
429 true, then assume we only have one such child element, or
430 fail.
431
432 '''
433 cont = self.getAsOne(cls.TAG,single=single)
434 if cont is None: return None
435 return [cls(self,node=n) for n in cont]
436
437 def getSpecificElements(self,cls,key,*names,asdict=True):
438 '''Get all elements of specific class and that has the
439 attribute key, and the attribute value is in names
440
441 '''
442 cont = self.getAsOne(cls.TAG,single=False)
443 cand = [cls(self,node=n) for n in cont
444 if n.getAttribute(key) in names]
445 if asdict:
446 return {c[key] : c for c in cand}
447 return cand
448
449 def getParent(self,cls=None,checkTag=True):
450 if self._node.parentNode is None:
451 return None
452 if cls is None:
453 cls = self.getTagClass(self._node.parentNode.tagName)
454 checkTag = False
455 if cls is None:
456 return None
457 if checkTag and self._node.parentNode.tagName != cls.TAG:
458 return None
459 return cls(self,node=self._node.parentNode)
460
461 def getParentOfClass(self,cls):
462 '''Searches back until we find the parent with the right
463 class, or none
464 '''
465 try:
466 iter(cls)
467 except:
468 cls = [cls]
469 t = {c.TAG: c for c in cls}
470 p = self._node.parentNode
471 while p is not None:
472 c = t.get(p.tagName,None)
473 if c is not None: return c(self,node=p)
474 p = p.parentNode
475 return None
476
477 def getTagClass(self,tag):
478 '''Get class corresponding to the tag'''
479 if tag not in self.known_tags: return None;
480 return self.known_tags[tag]
481
482 # ----------------------------------------------------------------
483 # Adders
484 def addNode(self,tag,**attr):
485 '''Add a note to this element
486
487 Parameters
488 ----------
489 tag : str
490 Node tag name
491 attr : dict
492 Attributes to set
493 '''
494 e = self._root.createElement(tag)
495 if self._node: self._node.appendChild(e)
496
497 for k, v in attr.items():
498 e.setAttribute(k,str(v).lower() if isinstance(v,bool) else str(v))
499
500 return e
501
502 def addText(self,text):
503 '''Add a text child node to an element'''
504 t = self._root.createTextNode(text)
505 self._node.appendChild(t)
506 return t
507
508 def getText(self):
509 '''Get contained text node content'''
510 if self._node.firstChild is None or \
511 self._node.firstChild.nodeType != self._node.firstChild.TEXT_NODE:
512 return ''
513 return self._node.firstChild.nodeValue
514
515
516 def add(self,cls,**kwargs):
517 '''Add an element and return wrapped in cls object'''
518 return cls(self,node=None,**kwargs)
519
520 def append(self,elem):
521 '''Append and element'''
522 if self._node.appendChild(elem._node):
523 return elem
524 return False
525
526 # ----------------------------------------------------------------
527 def remove(self,elem):
528 '''Remove an element'''
529 try:
530 self._node.removeChild(elem._node)
531 except:
532 return None
533 return elem
534 # ----------------------------------------------------------------
535 def insertBefore(self,toadd,ref):
536 '''Insert an element before another element'''
537 try:
538 self._node.insertBefore(toadd._node,ref._node)
539 except:
540 return None
541 return toadd
542
543 # --------------------------------------------------------------------
544 class DummyElement(Element):
545 def __init__(self,parent,node=None,**kwargs):
546 '''A dummy element we can use to select elements of different
547 classes
548
549 '''
550 super(DummyElement,self).__init__(parent,'Dummy',node=node)
551
552 # --------------------------------------------------------------------
553 class ToolbarElement(Element):
554 def __init__(self,
555 parent,
556 tag,
557 node = None,
558 name = '', # Toolbar element name
559 tooltip = '', # Tool tip
560 text = '', # Button text
561 icon = '', # Button icon,
562 hotkey = '', # Named key or key stroke
563 canDisable = False,
564 propertyGate = '',
565 disabledIcon = '',
566 **kwargs):
567 '''Base class for toolbar elements.
568
569 Parameters
570 ----------
571 parent : Element
572 Parent element if any
573 tag : str
574 Element tag
575 node : XMLNode
576 Possible node - when reading back
577 name : str
578 Name of element (user reminder). If not set, and tooltip is set,
579 set to tooltip
580 toolttip : str
581 Tool tip when hovering. If not set, and name is set, then
582 use name as tooltip.
583 text : str
584 Text of button
585 icon : str
586 Image path for button image
587 hotkey : str
588 Named key or key-sequence
589 canDisable : bool
590 If true, then the element can be disabled
591 propertyGate : str
592 Name of a global property. When this property is `true`,
593 then this element is _disabled_. Note that this _must_ be
594 the name of a property - it cannot be a BeanShell
595 expression.
596 disabledIcon : str
597 Path to image to use when the element is disabled.
598 kwargs : dict
599 Other attributes to set on the element
600 '''
601 if name == '' and tooltip != '': name = tooltip
602 if name != '' and tooltip == '': tooltip = name
603
604 # Build arguments for super class
605 args = {
606 'node': node,
607 'name': name,
608 'icon': icon,
609 'tooltip': tooltip,
610 'hotkey': hotkey,
611 'canDisable': canDisable,
612 'propertyGate': propertyGate,
613 'disabledIcon': disabledIcon }
614 bt = kwargs.pop('buttonText',None)
615 # If the element expects buttonText attribute, then do not set
616 # the text attribute - some elements interpret that as a
617 # legacy name attribute,
618 if bt is not None:
619 args['buttonText'] = bt
620 else:
621 args['text'] = text
622 args.update(kwargs)
623
624 super(ToolbarElement,self).__init__(parent,
625 tag,
626 **args)
627 # print('Attributes\n','\n'.join([f'- {k}="{v}"' for k,v in self._node.attributes.items()]))
628
629 #
630 # EOF
631 #
632 # ====================================================================
633 # From globalkey.py
634
635 # --------------------------------------------------------------------
636 class GlobalKey(ToolbarElement):
637 SELECTED = 'MAP|false|MAP|||||0|0||true|Selected|true|EQUALS'
638 def __init__(self,
639 parent,
640 tag,
641 node = None,
642 name = '',
643 icon = '',
644 tooltip = '',
645 buttonHotkey = '',
646 buttonText = '',
647 canDisable = False,
648 propertyGate = '',
649 disabledIcon = '',
650 # Local
651 hotkey = '',
652 deckCount = '-1',
653 filter = '',
654 reportFormat = '',
655 reportSingle = False,
656 singleMap = True,
657 target = SELECTED):
658 '''
659 Parameters
660 ----------
661 - tag The XML tag to use
662 - parent Parent node
663 - node Optionally existing node
664 - name Name of key
665 - buttonHotkey Key in "global" scope
666 - hotkey Key to send to targeted pieces
667 - buttonText Text on button
668 - canDisable If true, disabled when propertyGate is true
669 - deckCount Number of decks (-1 is all)
670 - filter Which units to target
671 - propertyGate When true, disable
672 - reportFormat Chat message
673 - reportSingle Also show single piece reports
674 - singleMap Only originating map if True
675 - target Preselection filter (default selected pieces)
676 - tooltip Hover-over message
677 - icon Image to use as icon
678
679 Default targets are selected units
680 '''
681
682 super(GlobalKey,self).\
683 __init__(parent,
684 tag,
685 node = node,
686 name = name,
687 icon = icon,
688 tooltip = tooltip,
689 buttonHotkey = buttonHotkey, # This hot key
690 buttonText = buttonText,
691 canDisable = canDisable,
692 propertyGate = propertyGate,
693 disabledIcon = disabledIcon,
694 hotkey = hotkey, # Target hot key
695 deckCount = deckCount,
696 filter = filter,
697 reportFormat = reportFormat,
698 reportSingle = reportSingle,
699 singleMap = singleMap,
700 target = target)
701 #
702 # EOF
703 #
704 # ====================================================================
705 # From gameelements.py
706
707 # --------------------------------------------------------------------
708 class GameElementService:
709 def getGame(self):
710 return self.getParentOfClass(Game)
711
712 # --------------------------------------------------------------------
713 class GameElement(Element,GameElementService):
714 def __init__(self,game,tag,node=None,**kwargs):
715 super(GameElement,self).__init__(game,tag,node=node,**kwargs)
716
717 # --------------------------------------------------------------------
718 class Notes(ToolbarElement,GameElementService):
719 TAG = Element.MODULE+'NotesWindow'
720 def __init__(self,elem,node=None,
721 name = 'Notes', # Toolbar element name
722 tooltip = 'Show notes window', # Tool tip
723 text = '', # Button text
724 icon = '/images/notes.gif', # Button icon,
725 hotkey = key('N',ALT), # Named key or key stroke
726 canDisable = False,
727 propertyGate = '',
728 disabledIcon = '',
729 description = ''):
730 super(Notes,self).__init__(elem,self.TAG,
731 node = node,
732 name = name,
733 tooltip = tooltip,
734 text = text,
735 icon = icon,
736 hotkey = hotkey,
737 canDisable = canDisable,
738 propertyGate = propertyGate,
739 disabledIcon = disabledIcon,
740 description = description)
741 def encode(self):
742 return ['NOTES\t\\','PNOTES']
743
744 registerElement(Notes)
745
746 # --------------------------------------------------------------------
747 class PredefinedSetup(GameElement):
748 TAG = Element.MODULE+'PredefinedSetup'
749 def __init__(self,elem,node=None,
750 name = '',
751 file = '',
752 useFile = False,
753 isMenu = False,
754 description = ''):
755 useFile = ((useFile or not isMenu) and
756 (file is not None and len(file) > 0))
757 if file is None: file = ''
758 super(PredefinedSetup,self).__init__(elem,self.TAG,node=node,
759 name = name,
760 file = file,
761 useFile = useFile,
762 isMenu = isMenu,
763 description = description)
764 def addPredefinedSetup(self,**kwargs):
765 '''Add a `PredefinedSetup` element to this
766
767 Parameters
768 ----------
769 kwargs : dict
770 Dictionary of attribute key-value pairs
771
772 Returns
773 -------
774 element : PredefinedSetup
775 The added element
776 '''
777 return self.add(PredefinedSetup,**kwargs)
778 def getPredefinedSetups(self,asdict=True):
779 '''Get all PredefinedSetup element(s) from this
780
781 Parameters
782 ----------
783 asdict : bool
784 If `True`, return a dictonary that maps key to `PredefinedSetup` elements. If `False`, return a list of all PredefinedSetup` children.
785
786 Returns
787 -------
788 children : dict or list
789 Dictionary or list of `PredefinedSetup` children
790 '''
791 return self.getElementsByKey(PredefinedSetup,'name',asdict)
792
793
794
795
796 registerElement(PredefinedSetup)
797
798 # --------------------------------------------------------------------
799 class GlobalTranslatableMessages(GameElement):
800 TAG=Element.MODULE+'properties.GlobalTranslatableMessages'
801 def __init__(self,elem,node=None):
802 '''Translations
803
804 Parameters
805 ----------
806 doc : Element
807 Parent
808 node : xml.dom.Element
809 Node to read state from
810 '''
811 super(GlobalTranslatableMessages,self).\
812 __init__(elem,self.TAG,node=node)
813
814 registerElement(GlobalTranslatableMessages)
815
816 # --------------------------------------------------------------------
817 class Language(GameElement):
818 TAG = 'VASSAL.i18n.Language'
819 def __init__(self,elem,node=None,**kwargs):
820 super(Languate,self).__init__(sele,self.TAG,node=none,**kwargs)
821
822 registerElement(Language)
823
824 # --------------------------------------------------------------------
825 class Chatter(GameElement):
826 TAG=Element.MODULE+'Chatter'
827 def __init__(self,elem,node=None,**kwargs):
828 '''Chat
829
830 Parameters
831 ----------
832 doc : Element
833 Parent
834 node : xml.dom.Element
835 Node to read state from
836 kwargs : dict
837 Attributes
838 '''
839 super(Chatter,self).__init__(elem,self.TAG,node=node,**kwargs)
840
841 registerElement(Chatter)
842
843 # --------------------------------------------------------------------
844 class KeyNamer(GameElement):
845 TAG=Element.MODULE+'KeyNamer'
846 def __init__(self,elem,node=None,**kwargs):
847 '''Key namer (or help menu)
848
849 Parameters
850 ----------
851 doc : Element
852 Parent
853 node : xml.dom.Element
854 Node to read state from
855 kwargs : dict
856 Attributes
857 '''
858 super(KeyNamer,self).__init__(elem,self.TAG,node=node,**kwargs)
859
860 registerElement(KeyNamer)
861
862
863 # --------------------------------------------------------------------
864 # <VASSAL.build.module.GlobalOptions
865 # autoReport="Always"
866 # centerOnMove="Use Preferences Setting"
867 # chatterHTMLSupport="Always"
868 # hotKeysOnClosedWindows="Always"
869 # inventoryForAll="Never"
870 # nonOwnerUnmaskable="Always"
871 # playerIdFormat="$PlayerName$"
872 # promptString="Opponents can unmask pieces"
873 # sendToLocationMoveTrails="Always"
874 # storeLeadingZeroIntegersAsStrings="true">
875 # <option name="stepIcon">/images/StepForward16.gif</option>
876 # <option name="stepHotKey">39,130</option>
877 # <option name="undoIcon">/images/Undo16.gif</option>
878 # <option name="undoHotKey">90,130</option>
879 # <option name="serverControlsIcon">/images/connect.gif</option>
880 # <option name="serverControlsHotKey">65,195</option>
881 # <option name="debugControlsIcon"/>
882 # <option name="debugControlsHotKey">68,195</option>
883 # </VASSAL.build.module.GlobalOptions>
884 class GlobalOptions(GameElement):
885 NEVER = 'Never'
886 ALWAYS = 'Always'
887 PROMPT = 'Use Preferences Setting'
888 TAG = Element.MODULE+'GlobalOptions'
889 def __init__(self,doc,node=None,
890 autoReport = PROMPT,
891 centerOnMove = PROMPT,
892 chatterHTMLSupport = ALWAYS,
893 hotKeysOnClosedWindows = NEVER,
894 inventoryForAll = ALWAYS,
895 nonOwnerUnmaskable = PROMPT,
896 playerIdFormat = "$playerName$",
897 promptString = "Opponents can unmask pieces",
898 sendToLocationMoveTrails = NEVER,
899 storeLeadingZeroIntegersAsStrings = False,
900 description = 'Global options',
901 dragThreshold = 10):
902 '''Set global options on the module
903
904 Parameters
905 ----------
906 doc : Element
907 Parent
908 node : xml.dom.Element
909 Node to read state from
910
911 autoReport : str='always'
912 centerOnMove : str Option
913 chatterHTMLSupport : str='never'
914 hotKeysOnClosedWindows : str='never'
915 inventoryForAll : str='always'
916 nonOwnerUnmaskable : str='never'
917 playerIdFormat : str='$PlayerName$'
918 promptString : str=?
919 sendToLocationMoveTrails : bool=false
920 storeLeadingZeroIntegersAsStrings : bool=False
921 '''
922 super(GlobalOptions,self).\
923 __init__(doc,self.TAG,node=node,
924 autoReport = autoReport,
925 centerOnMove = centerOnMove,
926 chatterHTMLSupport = chatterHTMLSupport,
927 hotKeysOnClosedWindows = hotKeysOnClosedWindows,
928 inventoryForAll = inventoryForAll,
929 nonOwnerUnmaskable = nonOwnerUnmaskable,
930 playerIdFormat = playerIdFormat,
931 promptString = promptString,
932 sendToLocationMoveTrails = sendToLocationMoveTrails,
933 storeLeadingZeroIntegersAsStrings = storeLeadingZeroIntegersAsStrings,
934 dragThreshold = dragThreshold,
935 description = description)
936
937 def addOption(self,**kwargs):
938 '''Add a `Option` element to this
939
940 Options known
941 - stepIcon - image file name (/images/StepForward16.gif)
942 - stepHotKey - key
943 - undoIcon - image file name (/images/Undo16.gif)
944 - undoHotKey - key
945 - serverControlsIcon - image file name (/images/connect.gif)
946 - serverControlsHotKey - key
947 - debugControlsIcon - image file name
948 - debugControlsHotKey - key
949
950
951 Parameters
952 ----------
953 kwargs : dict
954 Dictionary of attribute key-value pairs
955
956 Returns
957 -------
958 element : Option
959 The added element
960 '''
961 return self.add(Option,**kwargs)
962 def getOptions(self):
963 return self.getElementsByKey(Option,'name')
964
965 def addPreference(self,cls,**kwargs):
966 return self.add(cls,**kwargs)
967
968 def addIntPreference(self,**kwargs):
969 return self.add(IntPreference,**kwargs)
970
971 def addFloatPreference(self,**kwargs):
972 return self.add(FloatPreference,**kwargs)
973
974 def addBoolPreference(self,**kwargs):
975 return self.add(BoolPreference,**kwargs)
976
977 def addStrPreference(self,**kwargs):
978 return self.add(StrPreference,**kwargs)
979
980 def addTextPreference(self,**kwargs):
981 return self.add(TextPreference,**kwargs)
982
983 def addEnumPreference(self,**kwargs):
984 return self.add(EnumPreference,**kwargs)
985
986 def getIntPreferences(self):
987 return self.getElementsByKey(IntPreference,'name')
988
989 def getFloatPreferences(self):
990 return self.getElementsByKey(FloatPreference,'name')
991
992 def getBoolPreferences(self):
993 return self.getElementsByKey(BoolPreference,'name')
994
995 def getStrPreferences(self):
996 return self.getElementsByKey(StrPreference,'name')
997
998 def getTextPreferences(self):
999 return self.getElementsByKey(TextPreference,'name')
1000
1001 def getEnumPreferences(self):
1002 return self.getElementsByKey(EnumPreference,'name')
1003
1004 def getPreferences(self):
1005 retd = {}
1006 for cls in [IntPreference,
1007 FloatPreference,
1008 BoolPreference,
1009 StrPreference,
1010 TextPreference,
1011 EnumPreference]:
1012 retd.update(self.getElementsByKey(cls,'name'))
1013
1014 return retd
1015
1016 registerElement(GlobalOptions)
1017
1018 # --------------------------------------------------------------------
1019 class Option(Element):
1020 TAG = 'option'
1021 def __init__(self,doc,node=None,name='',value=''):
1022 super(Option,self).__init__(doc,tag=self.TAG,node=node,name=name)
1023 self.addText(value)
1024
1025 def getGlobalOptions(self):
1026 return self.getParent(GlobalOptions)
1027
1028 registerElement(Option)
1029
1030 # --------------------------------------------------------------------
1031 class Preference(Element):
1032 PREFS = 'VASSAL.preferences.'
1033 def __init__(self,
1034 doc,
1035 tag,
1036 node = None,
1037 name = '',
1038 default = '',
1039 desc = '',
1040 tab = '',
1041 **kwargs):
1042 '''Add a preference
1043
1044 Parameters
1045 ----------
1046 name : str
1047 Name of property
1048 default : str
1049 Default value
1050 desc : str
1051 Description
1052 tab : str
1053 Preference tab to put in to
1054 '''
1055 super(Preference,self).__init__(doc,
1056 tag = tag,
1057 node = node,
1058 name = name,
1059 default = default,
1060 desc = desc,
1061 tab = tab)
1062
1063 def getGlobalOptions(self):
1064 return self.getParent(GlobalOptions)
1065
1066 # --------------------------------------------------------------------
1067 class IntPreference(Preference):
1068 TAG = Preference.PREFS+'IntegerPreference'
1069 def __init__(self,
1070 doc,
1071 node = None,
1072 name = '',
1073 default = 0,
1074 desc = '',
1075 tab = ''):
1076 super(IntPreference,self).__init__(doc,
1077 tag = self.TAG,
1078 node = node,
1079 name = name,
1080 default = str(default),
1081 desc = desc,
1082 tab = tab)
1083
1084 registerElement(IntPreference)
1085
1086 # --------------------------------------------------------------------
1087 class FloatPreference(Preference):
1088 TAG = Preference.PREFS+'DoublePreference'
1089 def __init__(self,
1090 doc,
1091 node = None,
1092 name = '',
1093 default = 0.,
1094 desc = '',
1095 tab = ''):
1096 super(FloatPreference,self).__init__(doc,
1097 tag = self.TAG,
1098 node = node,
1099 name = name,
1100 default = str(default),
1101 desc = desc,
1102 tab = tab)
1103
1104 registerElement(FloatPreference)
1105
1106 # --------------------------------------------------------------------
1107 class BoolPreference(Preference):
1108 TAG = Preference.PREFS+'BooleanPreference'
1109 def __init__(self,
1110 doc,
1111 node = None,
1112 name = '',
1113 default = False,
1114 desc = '',
1115 tab = ''):
1116 super(BoolPreference,self).__init__(doc,
1117 tag = self.TAG,
1118 node = node,
1119 name = name,
1120 default = ('true' if default
1121 else 'false'),
1122 desc = desc,
1123 tab = tab)
1124
1125 registerElement(BoolPreference)
1126
1127 # --------------------------------------------------------------------
1128 class StrPreference(Preference):
1129 TAG = Preference.PREFS+'StringPreference'
1130 def __init__(self,
1131 doc,
1132 node = None,
1133 name = '',
1134 default = '',
1135 desc = '',
1136 tab = ''):
1137 super(StrPreference,self).__init__(doc,
1138 tag = self.TAG,
1139 node = node,
1140 name = name,
1141 default = default,
1142 desc = desc,
1143 tab = tab)
1144
1145 registerElement(StrPreference)
1146
1147 # --------------------------------------------------------------------
1148 class TextPreference(Preference):
1149 TAG = Preference.PREFS+'TextPreference'
1150 def __init__(self,
1151 doc,
1152 node = None,
1153 name = '',
1154 default = '',
1155 desc = '',
1156 tab = ''):
1157 super(TextPreference,self).__init__(doc,
1158 tag = self.TAG,
1159 node = node,
1160 name = name,
1161 default = (default
1162 .replace('\n','&#10;')),
1163 desc = desc,
1164 tab = tab)
1165
1166 registerElement(TextPreference)
1167
1168 # --------------------------------------------------------------------
1169 class EnumPreference(Preference):
1170 TAG = Preference.PREFS+'EnumPreference'
1171 def __init__(self,
1172 doc,
1173 node = None,
1174 name = '',
1175 values = [],
1176 default = '',
1177 desc = '',
1178 tab = ''):
1179 ce = lambda v : str(v).replace(',',r'\,')
1180 sl = [ce(v) for v in values]
1181 df = ce(v)
1182 assert df in sl, \
1183 f'Default value "{default}" not in list {":".join(values)}'
1184 super(EnumPreference,self).__init__(doc,
1185 tag = self.TAG,
1186 node = node,
1187 name = name,
1188 default = df,
1189 desc = desc,
1190 tab = tab,
1191 list = sl)
1192
1193
1194 registerElement(EnumPreference)
1195
1196
1197 # --------------------------------------------------------------------
1198 # CurrentMap == &quot;Board&quot;
1199 class Inventory(ToolbarElement,GameElementService):
1200 TAG = Element.MODULE+'Inventory'
1201 def __init__(self,doc,node=None,
1202 name = '',
1203 icon = '/images/inventory.gif',
1204 text = '',
1205 tooltip = 'Show inventory of all pieces',
1206 hotkey = key('I',ALT),
1207 canDisable = False,
1208 propertyGate = '',
1209 disabledIcon = '',
1210 centerOnPiece = True,
1211 drawPieces = True,
1212 foldersOnly = False,
1213 forwardKeystroke = True,
1214 groupBy = '',
1215 include = '{}',
1216 launchFunction = 'functionHide',
1217 leafFormat = '$PieceName$',
1218 nonLeafFormat = '$PropertyValue$',
1219 pieceZoom = '0.33',
1220 pieceZoom2 = '0.5',
1221 pieceZoom3 = '0.6',
1222 refreshHotkey = key('I',ALT_SHIFT),
1223 showMenu = True,
1224 sides = '',
1225 sortFormat = '$PieceName$',
1226 sortPieces = True,
1227 sorting = 'alpha',
1228 zoomOn = False):
1229 super(Inventory,self).__init__(doc,self.TAG,node=node,
1230 canDisable = canDisable,
1231 centerOnPiece = centerOnPiece,
1232 disabledIcon = disabledIcon,
1233 drawPieces = drawPieces,
1234 foldersOnly = foldersOnly,
1235 forwardKeystroke = forwardKeystroke,
1236 groupBy = groupBy,
1237 hotkey = hotkey,
1238 icon = icon,
1239 include = include,
1240 launchFunction = launchFunction,
1241 leafFormat = leafFormat,
1242 name = name,
1243 nonLeafFormat = nonLeafFormat,
1244 pieceZoom = pieceZoom,
1245 pieceZoom2 = pieceZoom2,
1246 pieceZoom3 = pieceZoom3,
1247 propertyGate = propertyGate,
1248 refreshHotkey = refreshHotkey,
1249 showMenu = showMenu,
1250 sides = sides,
1251 sortFormat = sortFormat,
1252 sortPieces = sortPieces,
1253 sorting = sorting,
1254 text = text,
1255 tooltip = tooltip,
1256 zoomOn = zoomOn)
1257
1258 registerElement(Inventory)
1259
1260 # --------------------------------------------------------------------
1261 class Prototypes(GameElement):
1262 TAG = Element.MODULE+'PrototypesContainer'
1263 def __init__(self,game,node=None,**kwargs):
1264 super(Prototypes,self).\
1265 __init__(game,self.TAG,node=node,**kwargs)
1266
1267 def addPrototype(self,**kwargs):
1268 '''Add a `Prototype` element to this
1269
1270 Parameters
1271 ----------
1272 kwargs : dict
1273 Dictionary of attribute key-value pairs
1274
1275 Returns
1276 -------
1277 element : Prototype
1278 The added element
1279 '''
1280 return self.add(Prototype,**kwargs)
1281 def getPrototypes(self,asdict=True):
1282 '''Get all Prototype element(s) from this
1283
1284 Parameters
1285 ----------
1286 asdict : bool
1287 If `True`, return a dictonary that maps key to `Prototype` elements. If `False`, return a list of all Prototype` children.
1288
1289 Returns
1290 -------
1291 children : dict or list
1292 Dictionary or list of `Prototype` children
1293 '''
1294 return self.getElementsByKey(Prototype,'name',asdict=asdict)
1295
1296 registerElement(Prototypes)
1297
1298 # --------------------------------------------------------------------
1299 class DiceButton(ToolbarElement,GameElementService):
1300 TAG=Element.MODULE+'DiceButton'
1301 def __init__(self,elem,node=None,
1302 name = '1d6',
1303 tooltip = 'Roll a 1d6',
1304 text = '1d6',
1305 icon = '/images/die.gif',
1306 hotkey = key('6',ALT),
1307 canDisable = False,
1308 propertyGate = '',
1309 disabledIcon = '',
1310 addToTotal = 0,
1311 keepCount = 1,
1312 keepDice = False,
1313 keepOption = '>',
1314 lockAdd = False,
1315 lockDice = False,
1316 lockPlus = False,
1317 lockSides = False,
1318 nDice = 1,
1319 nSides = 6,
1320 plus = 0,
1321 prompt = False,
1322 reportFormat = '$name$ = $result$',
1323 reportTotal = False,
1324 sortDice = False):
1325 super(DiceButton,self).\
1326 __init__(elem,self.TAG,node=node,
1327 addToTotal = addToTotal,
1328 canDisable = canDisable,
1329 disabledIcon = disabledIcon,
1330 hotkey = hotkey,
1331 icon = icon,
1332 keepCount = keepCount,
1333 keepDice = keepDice,
1334 keepOption = keepOption,
1335 lockAdd = lockAdd,
1336 lockDice = lockDice,
1337 lockPlus = lockPlus,
1338 lockSides = lockSides,
1339 nDice = nDice,
1340 nSides = nSides,
1341 name = name,
1342 plus = plus,
1343 prompt = prompt,
1344 propertyGate = propertyGate,
1345 reportFormat = reportFormat,
1346 reportTotal = reportTotal,
1347 sortDice = sortDice,
1348 text = text,
1349 tooltip = tooltip)
1350
1351 registerElement(DiceButton)
1352
1353 # --------------------------------------------------------------------
1354 class GameMassKey(GlobalKey,GameElementService):
1355 TAG = Element.MODULE+'GlobalKeyCommand'
1356 def __init__(self,map,node=None,
1357 name = '',
1358 buttonText = '',
1359 tooltip = '',
1360 icon = '',
1361 canDisable = False,
1362 propertyGate = '',
1363 disabledIcon = '',
1364 buttonHotkey = '',
1365 hotkey = '',
1366 deckCount = '-1',
1367 filter = '',
1368 reportFormat = '',
1369 reportSingle = False,
1370 singleMap = True,
1371 target = GlobalKey.SELECTED):
1372 '''Default targets are selected units'''
1373 super(GameMassKey,self).\
1374 __init__(map,
1375 self.TAG,
1376 node = node,
1377 name = name,
1378 buttonHotkey = buttonHotkey, # This hot key
1379 hotkey = hotkey, # Target hot key
1380 buttonText = buttonText,
1381 canDisable = canDisable,
1382 deckCount = deckCount,
1383 filter = filter,
1384 propertyGate = propertyGate,
1385 reportFormat = reportFormat,
1386 reportSingle = reportSingle,
1387 singleMap = singleMap,
1388 target = target,
1389 tooltip = tooltip,
1390 icon = icon)
1391
1392 registerElement(GameMassKey)
1393
1394 # --------------------------------------------------------------------
1395 class StartupMassKey(GlobalKey,GameElementService):
1396 TAG = Element.MODULE+'StartupGlobalKeyCommand'
1397 FIRST_LAUNCH = 'firstLaunchOfSession'
1398 EVERY_LAUNCH = 'everyLaunchOfSession'
1399 START_GAME = 'startOfGameOnly'
1400 def __init__(self,
1401 map,
1402 node = None,
1403 name = '',
1404 buttonHotkey = '',
1405 hotkey = '',
1406 buttonText = '',
1407 canDisable = False,
1408 deckCount = '-1',
1409 filter = '',
1410 propertyGate = '',
1411 reportFormat = '',
1412 reportSingle = False,
1413 singleMap = True,
1414 target = GlobalKey.SELECTED,
1415 tooltip = '',
1416 icon = '',
1417 whenToApply = EVERY_LAUNCH):
1418 '''Default targets are selected units'''
1419 super(StartupMassKey,self).\
1420 __init__(map,
1421 self.TAG,
1422 node = node,
1423 name = name,
1424 buttonHotkey = buttonHotkey, # This hot key
1425 hotkey = hotkey, # Target hot key
1426 buttonText = buttonText,
1427 canDisable = canDisable,
1428 deckCount = deckCount,
1429 filter = filter,
1430 propertyGate = propertyGate,
1431 reportFormat = reportFormat,
1432 reportSingle = reportSingle,
1433 singleMap = singleMap,
1434 target = target,
1435 tooltip = tooltip,
1436 icon = icon)
1437 if node is None:
1438 self['whenToApply'] = whenToApply
1439
1440 registerElement(StartupMassKey)
1441
1442 # --------------------------------------------------------------------
1443 class Menu(GameElement):
1444 TAG = Element.MODULE+'ToolbarMenu'
1445 def __init__(self,
1446 game,
1447 node = None,
1448 name = '',
1449 tooltip = '',
1450 text = '', # Menu name
1451 canDisable = False,
1452 propertyGate = '',
1453 disabledIcon = '',
1454 description = '',
1455 hotkey = '',
1456 icon = '',
1457 menuItems = []):
1458 if len(description) <= 0 and len(tooltip) > 0:
1459 description = tooltip
1460 if len(tooltip) <= 0 and len(description) > 0:
1461 tooltip = description
1462 super(Menu,self).\
1463 __init__(game,
1464 self.TAG,
1465 node = node,
1466 name = name,
1467 canDisable = canDisable,
1468 description = description,
1469 disabledIcon = disabledIcon,
1470 hotkey = hotkey,
1471 icon = icon,
1472 menuItems = ','.join(menuItems),
1473 propertyGate = propertyGate,
1474 text = text,
1475 tooltip = tooltip)
1476
1477 registerElement(Menu)
1478
1479
1480 # --------------------------------------------------------------------
1481 class SymbolicDice(GameElement):
1482 TAG = Element.MODULE+'SpecialDiceButton'
1483 def __init__(self,
1484 game,
1485 node = None,
1486 canDisable = False,
1487 disabledIcon = '',
1488 hotkey = key('6',ALT),
1489 name = "Dice", # GP prefix
1490 text = '', # Text on button
1491 icon = '/images/die.gif', # Icon on button
1492 format = '{name+": "+result1}', # Report
1493 tooltip = 'Die roll', # Help
1494 propertyGate = '', # Property to disable when T
1495 resultButton = False, # Result on button?
1496 resultChatter = True, # Result in Chatter?
1497 resultWindow = False, # Result window?
1498 backgroundColor = rgb(0xdd,0xdd,0xdd), # Window background
1499 windowTitleResultFormat = "$name$", # Window title
1500 windowX = '67', # Window size
1501 windowY = '65',
1502 doHotkey = False,
1503 doLoop = False,
1504 doReport = False,
1505 doSound = False,
1506 hideWhenDisabled = False,
1507 hotkeys = '',
1508 index = False,
1509 indexProperty = '',
1510 indexStart = 1,
1511 indexStep = 1,
1512 loopCount = 1,
1513 loopType = 'counted',
1514 postLoopKey = '',
1515 reportFormat = '',
1516 soundClip = '',
1517 untilExpression = '',
1518 whileExpression = ''
1519 ):
1520 super(SymbolicDice,self).\
1521 __init__(game,
1522 self.TAG,
1523 node = node,
1524 canDisable = canDisable,
1525 disabledIcon = disabledIcon,
1526 hotkey = hotkey,
1527 name = name,
1528 text = text,
1529 icon = icon,
1530 format = format,
1531 tooltip = tooltip,
1532 propertyGate = propertyGate,
1533 resultButton = resultButton,
1534 resultChatter = resultChatter,
1535 resultWindow = resultWindow,
1536 backgroundColor = backgroundColor,
1537 windowTitleResultFormat = windowTitleResultFormat,
1538 windowX = windowX,
1539 windowY = windowY,
1540 doHotkey = doHotkey,
1541 doLoop = doLoop,
1542 doReport = doReport,
1543 doSound = doSound,
1544 hideWhenDisabled = hideWhenDisabled,
1545 hotkeys = hotkeys,
1546 index = index,
1547 indexProperty = indexProperty,
1548 indexStart = indexStart,
1549 indexStep = indexStep,
1550 loopCount = loopCount,
1551 loopType = loopType,
1552 postLoopKey = postLoopKey,
1553 reportFormat = reportFormat,
1554 soundClip = soundClip,
1555 untilExpression = untilExpression,
1556 whileExpression = whileExpression)
1557
1558
1559 def addDie(self,**kwargs):
1560 return self.add(SpecialDie,**kwargs)
1561
1562 def getSymbolicDice(self):
1563 return self.getParent(SymbolicDice)
1564
1565 registerElement(SymbolicDice)
1566
1567
1568 # --------------------------------------------------------------------
1569 class SpecialDie(GameElement):
1570 TAG = Element.MODULE+'SpecialDie'
1571 def __init__(self,
1572 symbolic, # Symblic dice
1573 node = None,
1574 name = '', # Name of dice (no GP)
1575 report = '{name+": "+result}',
1576 faces = None):
1577 super(SpecialDie,self).\
1578 __init__(symbolic,
1579 self.TAG,
1580 node = node,
1581 name = name,
1582 report = report)
1583 if node is not None or faces is None:
1584 return
1585 if isinstance(faces,list):
1586 faces = {i+1: f for i,f in enumerate(faces)}
1587 for v,f in faces:
1588 self.addFace(text = str(v), value = v, icon = f)
1589
1590 def addFace(self,**kwargs):
1591 self.add(DieFace,**kwargs)
1592
1593 def getSymbolicDice(self):
1594 return self.getParent(SymbolicDice)
1595
1596 def getFaces(self):
1597 return self.getAllElements(DieFace,single=False)
1598
1599 registerElement(SpecialDie)
1600
1601 # --------------------------------------------------------------------
1602 class DieFace(GameElement):
1603 TAG = Element.MODULE+'SpecialDieFace'
1604 def __init__(self,
1605 special, # Special dice
1606 node, # existing node
1607 icon = '', # graphical representation
1608 text = '', # Text representation
1609 value = 0): # Value representation
1610 super(DieFace,self).\
1611 __init__(special,
1612 self.TAG,
1613 node = node,
1614 icon = icon,
1615 text = text,
1616 value = value)
1617
1618 def getSpecialDie(self):
1619 return self.getParent(SpecialDie)
1620
1621 registerElement(DieFace)
1622
1623 #
1624 # EOF
1625 #
1626 # ====================================================================
1627 # From mapelements.py
1628
1629 # --------------------------------------------------------------------
1630 class MapElementService:
1631 def getMap(self):
1632 '''Get map - either a Map or WidgetMap'''
1633 return self.getParentOfClass([WidgetMap,Map])
1634 # if self._parent is None:
1635 # return None
1636 #
1637 # if 'WidgetMap' in self._parent.tagName:
1638 # return self.getParent(WidgetMap)
1639 #
1640 # return self.getParent(Map)
1641 def getGame(self):
1642 m = self.getMap()
1643 if m is not None: return m.getGame()
1644 return None
1645
1646 # --------------------------------------------------------------------
1647 class MapElement(Element,MapElementService):
1648 def __init__(self,map,tag,node=None,**kwargs):
1649 super(MapElement,self).__init__(map,tag,node=node,**kwargs)
1650
1651
1652 # --------------------------------------------------------------------
1653 class PieceLayers(MapElement):
1654 TAG=Element.MAP+'LayeredPieceCollection'
1655 def __init__(self,map,node=None,
1656 property = 'PieceLayer',
1657 description = '',
1658 layerOrder = []):
1659 super(PieceLayers,self).__init__(map,self.TAG,node=node,
1660 property = property,
1661 description = description,
1662 layerOrder = ','.join(layerOrder))
1663
1664 def addControl(self,**kwargs):
1665 '''Add `LayerControl` element to this
1666
1667 Parameters
1668 ----------
1669 kwargs : dict
1670 Dictionary of attribute key-value pairs
1671
1672 Returns
1673 -------
1674 element : LayerControl
1675 The added element
1676 '''
1677 return self.add(LayerControl,**kwargs)
1678 def getControls(self,asdict=True):
1679 '''Get all `LayerControl` element(s) from this
1680
1681 Parameters
1682 ----------
1683 asdict : bool
1684 If `True`, return a dictonary that maps name to
1685 `LayerControl` elements. If `False`, return a list of all
1686 `LayerControl` children.
1687
1688 Returns
1689 -------
1690 children : dict or list
1691 Dictionary or list of `LayerControl` children
1692
1693 '''
1694 return self.getElementsByKey(LayerControl,'name',asdict)
1695
1696 registerElement(PieceLayers)
1697
1698 # --------------------------------------------------------------------
1699 class LayerControl(MapElement):
1700 TAG=Element.MAP+'LayerControl'
1701 CYCLE_UP='Rotate Layer Order Up'
1702 CYCLE_DOWN='Rotate Layer Order Down'
1703 ENABLE='Make Layer Active'
1704 DISABLE='Make Layer Inactive'
1705 TOGGLE='Switch Layer between Active and Inactive'
1706 RESET='Reset All Layers'
1707 def __init__(self,col,node=None,
1708 name = '',
1709 tooltip = '',
1710 text = '',
1711 hotkey = '',
1712 icon = '',
1713 canDisable = False,
1714 propertyGate = '', #Property name, disable when property false
1715 disabledIcon = '',
1716 command = TOGGLE,
1717 skip = False,
1718 layers = [],
1719 description = ''):
1720 super(LayerControl,self).__init__(col,self.TAG,node=node,
1721 name = name,
1722 tooltip = tooltip,
1723 text = text,
1724 buttonText = text,
1725 hotkey = hotkey,
1726 icon = icon,
1727 canDisable = canDisable,
1728 propertyGate = propertyGate,
1729 disabledIcon = disabledIcon,
1730 command = command,
1731 skip = skip,
1732 layers = ','.join(layers),
1733 description = description)
1734
1735 def getLayers(self):
1736 '''Get map - either a Map or WidgetMap'''
1737 return self.getParentOfClass([PieceLayers])
1738
1739 registerElement(LayerControl)
1740
1741
1742 # --------------------------------------------------------------------
1743 class LineOfSight(MapElement):
1744 TAG=Element.MAP+'LOS_Thread'
1745 ROUND_UP = 'Up'
1746 ROUND_DOWN = 'Down'
1747 ROUND_NEAREST = 'Nearest whole number'
1748 FROM_LOCATION = 'FromLocation'
1749 TO_LOCATION = 'ToLocation'
1750 CHECK_COUNT = 'NumberOfLocationsChecked'
1751 CHECK_LIST = 'AllLocationsChecked'
1752 RANGE = 'Range'
1753 NEVER = 'Never'
1754 ALWAYS = 'Always'
1755 WHEN_PERSISTENT = 'When persistent'
1756 CTRL_CLICK = 'Cltr-Click & Drag'
1757
1758 def __init__(self,map,
1759 node=None,
1760 threadName = 'LOS',
1761 hotkey = key('L',ALT),
1762 tooltip = 'Trace line of sight',
1763 iconName = '/images/thread.gif', #'los-icon.png',
1764 label = '',
1765 snapLOS = False,
1766 snapStart = True,
1767 snapEnd = True,
1768 report = (f'{{"Range from "+{FROM_LOCATION}'
1769 f'+" to "+{TO_LOCATION}+" is "'
1770 f'+{RANGE}+" (via "+{CHECK_LIST}+")"}}'),
1771 persistent = CTRL_CLICK,
1772 persistentIconName = '/images/thread.gif',
1773 globl = ALWAYS,
1774 losThickness = 3,
1775 threadColor = rgb(255,0,0),
1776 drawRange = True,
1777 # rangeBg = rgb(255,255,255),
1778 # rangeFg = rgb(0,0,0),
1779 rangeScale = 0,
1780 hideCounters = True,
1781 hideOpacity = 50,
1782 round = ROUND_UP,
1783 canDisable = False,
1784 propertyGate = '',
1785 disabledIcon = ''):
1786 '''Make Line of Sight interface
1787
1788 Parameters
1789 ----------
1790 threadName : str
1791 Name of interface
1792 hotkey : str
1793 Start LOS key
1794 tooltip : str
1795 Tool tip text
1796 iconName : str
1797 Path to button icon
1798 label : str
1799 Button text
1800 snapLOS : bool
1801 Wether to snap both ends
1802 snapStart : bool
1803 Snap to start
1804 snapEnd: bool
1805 Snap to end
1806 report : str
1807 Report format
1808 persistent : str
1809 When persistent
1810 persistentIconName : str
1811 Icon when persistent(?)
1812 globl : str
1813 Visisble to opponents
1814 losThickness : int
1815 Thickness in pixels
1816 losColor : str
1817 Colour of line
1818 drawRange : bool
1819 Draw the range next to LOST thread
1820 rangeBg : str
1821 Range backgroung colour
1822 rangeFg : str
1823 Range foregrond colour
1824 rangeScale : int
1825 Scale of range - pixels per unit
1826 round : str
1827 How to round range
1828 hideCounters :bool
1829 If true, hide counters while making thread
1830 hideOpacity : int
1831 Opacity of hidden counters (percent)
1832 canDisable : bool
1833 IF true, then can be hidden
1834 propertyGate : str
1835 Name of property. When that property is TRUE, then the
1836 interface is disabled. Must be a property name, not an expression.
1837 disabledIcon : str
1838 Icon to use when disabled
1839 '''
1840 super(LineOfSight,self).__init__(map,self.TAG,
1841 node = node,
1842 threadName = threadName,
1843 hotkey = hotkey,
1844 tooltip = tooltip,
1845 iconName = iconName,
1846 label = label,
1847 snapLOS = snapLOS,
1848 snapStart = snapStart,
1849 snapEnd = snapEnd,
1850 report = report,
1851 persistent = persistent,
1852 persistentIconName = persistentIconName,
1853 losThickness = losThickness,
1854 threadColor = threadColor,
1855 drawRange = drawRange,
1856 #rangeBg = rangeBg,
1857 #rangeFg = rangeFg,
1858 rangeScale = rangeScale,
1859 hideCounters = hideCounters,
1860 hideOpacity = hideOpacity,
1861 round = round,
1862 canDisable = canDisable,
1863 propertyGate = propertyGate,
1864 disabledIcon = disabledIcon)
1865 self.setAttribute('global',globl)
1866
1867
1868 registerElement(LineOfSight)
1869
1870 # --------------------------------------------------------------------
1871 class StackMetrics(MapElement):
1872 TAG=Element.MAP+'StackMetrics'
1873 def __init__(self,map,node=None,
1874 bottom = key('(',0),
1875 down = key('%',0),
1876 top = key('&',0),
1877 up = key("'",0),
1878 disabled = False,
1879 exSepX = 6, # Expanded (after double click)
1880 exSepY = 18, # Expanded (after double click)
1881 unexSepX = 8, # Compact
1882 unexSepY = 16): # Compact
1883 super(StackMetrics,self).__init__(map,self.TAG,node=node,
1884 bottom = bottom,
1885 disabled = disabled,
1886 down = down,
1887 exSepX = exSepX,
1888 exSepY = exSepY,
1889 top = top,
1890 unexSepX = unexSepX,
1891 unexSepY = unexSepY,
1892 up = up)
1893
1894 registerElement(StackMetrics)
1895
1896 # --------------------------------------------------------------------
1897 class ImageSaver(MapElement):
1898 TAG=Element.MAP+'ImageSaver'
1899 def __init__(self,map,node=None,
1900 buttonText = '',
1901 canDisable = False,
1902 hotkey = '',
1903 icon = '/images/camera.gif',
1904 propertyGate = '',
1905 tooltip = 'Save map as PNG image'):
1906 super(ImageSaver,self).__init__(map,self.TAG,node=node,
1907 buttonText = buttonText,
1908 canDisable = canDisable,
1909 hotkey = hotkey,
1910 icon = icon,
1911 propertyGate = propertyGate,
1912 tooltip = tooltip)
1913
1914 registerElement(ImageSaver)
1915
1916 # --------------------------------------------------------------------
1917 class TextSaver(MapElement):
1918 TAG=Element.MAP+'TextSaver'
1919 def __init__(self,map,node=None,
1920 buttonText = '',
1921 canDisable = False,
1922 hotkey = '',
1923 icon = '/images/camera.gif',
1924 propertyGate = '',
1925 tooltip = 'Save map as text'):
1926 super(TextSaver,self).__init__(map,self.TAG,node=node,
1927 buttonText = buttonText,
1928 canDisable = canDisable,
1929 hotkey = hotkey,
1930 icon = icon,
1931 propertyGate = propertyGate,
1932 tooltip = tooltip)
1933
1934 registerElement(TextSaver)
1935
1936 # --------------------------------------------------------------------
1937 class ForwardToChatter(MapElement):
1938 TAG=Element.MAP+'ForwardToChatter'
1939 def __init__(self,map,node=None,**kwargs):
1940 super(ForwardToChatter,self).__init__(map,self.TAG,node=node,**kwargs)
1941
1942 registerElement(ForwardToChatter)
1943
1944 # --------------------------------------------------------------------
1945 class MenuDisplayer(MapElement):
1946 TAG=Element.MAP+'MenuDisplayer'
1947 def __init__(self,map,node=None,**kwargs):
1948 super(MenuDisplayer,self).__init__(map,self.TAG,node=node,**kwargs)
1949
1950 registerElement(MenuDisplayer)
1951
1952 # --------------------------------------------------------------------
1953 class MapCenterer(MapElement):
1954 TAG=Element.MAP+'MapCenterer'
1955 def __init__(self,map,node=None,**kwargs):
1956 super(MapCenterer,self).__init__(map,self.TAG,node=node,**kwargs)
1957
1958 registerElement(MapCenterer)
1959
1960 # --------------------------------------------------------------------
1961 class StackExpander(MapElement):
1962 TAG=Element.MAP+'StackExpander'
1963 def __init__(self,map,node=None,**kwargs):
1964 super(StackExpander,self).__init__(map,self.TAG,node=node,**kwargs)
1965
1966 registerElement(StackExpander)
1967
1968 # --------------------------------------------------------------------
1969 class PieceMover(MapElement):
1970 TAG=Element.MAP+'PieceMover'
1971 def __init__(self,map,node=None,**kwargs):
1972 super(PieceMover,self).__init__(map,self.TAG,node=node,**kwargs)
1973
1974 registerElement(PieceMover)
1975
1976 # --------------------------------------------------------------------
1977 class SelectionHighlighters(MapElement):
1978 TAG=Element.MAP+'SelectionHighlighters'
1979 def __init__(self,map,node=None,**kwargs):
1980 super(SelectionHighlighters,self).\
1981 __init__(map,self.TAG,node=node,**kwargs)
1982
1983 registerElement(SelectionHighlighters)
1984
1985 # --------------------------------------------------------------------
1986 class KeyBufferer(MapElement):
1987 TAG=Element.MAP+'KeyBufferer'
1988 def __init__(self,map,node=None,**kwargs):
1989 super(KeyBufferer,self).__init__(map,self.TAG,node=node,**kwargs)
1990
1991 registerElement(KeyBufferer)
1992
1993 # --------------------------------------------------------------------
1994 class HighlightLastMoved(MapElement):
1995 TAG=Element.MAP+'HighlightLastMoved'
1996 def __init__(self,map,node=None,
1997 color = rgb(255,0,0),
1998 enabled = True,
1999 thickness = 2):
2000 super(HighlightLastMoved,self).__init__(map,self.TAG,node=node,
2001 color = color,
2002 enabled = enabled,
2003 thickness = thickness)
2004
2005 registerElement(HighlightLastMoved)
2006
2007 # --------------------------------------------------------------------
2008 class CounterDetailViewer(MapElement):
2009 TAG=Element.MAP+'CounterDetailViewer'
2010 TOP_LAYER = 'from top-most layer only'
2011 ALL_LAYERS = 'from all layers'
2012 INC_LAYERS = 'from listed layers only'
2013 EXC_LAYERS = 'from layers other than those listed'
2014 FILTER = 'by using a property filter'
2015 def __init__(self,map,node=None,
2016 borderWidth = 0,
2017 centerAll = False,
2018 centerText = False,
2019 combineCounterSummary = False,
2020 counterReportFormat = '',
2021 delay = 700,
2022 description = '',
2023 display = TOP_LAYER,
2024 emptyHexReportForma = '$LocationName$',
2025 enableHTML = True,
2026 extraTextPadding = 0,
2027 bgColor = None,
2028 fgColor = rgb(0,0,0),
2029 fontSize = 11,
2030 graphicsZoom = 1.0,# Zoom on counters
2031 hotkey = key('\n'),
2032 layerList = '',
2033 minDisplayPieces = 2,
2034 propertyFilter = '',
2035 showDeck = False,
2036 showDeckDepth = 1,
2037 showDeckMasked = False,
2038 showMoveSelectde = False,
2039 showNoStack = False,
2040 showNonMovable = False,
2041 showOverlap = False,
2042 showgraph = True,
2043 showgraphsingle = False,
2044 showtext = True,
2045 showtextsingle = False,
2046 stretchWidthSummary = False,
2047 summaryReportFormat = '$LocationName$',
2048 unrotatePieces = False,
2049 version = 3,
2050 verticalOffset = 2,
2051 verticalTopText = 0,
2052 zoomlevel = 1.0,
2053 stopAfterShowing = False): # showTerrain attributes
2054
2055 bg = '' if bgColor is None else bgColor
2056 fg = '' if fgColor is None else fgColor
2057 super(CounterDetailViewer,self)\
2058 .__init__(map,self.TAG,node=node,
2059 borderWidth = borderWidth,
2060 centerAll = centerAll,
2061 centerText = centerText,
2062 combineCounterSummary = combineCounterSummary,
2063 counterReportFormat = counterReportFormat,
2064 delay = delay,
2065 description = description,
2066 display = display,
2067 emptyHexReportForma = emptyHexReportForma,
2068 enableHTML = enableHTML,
2069 extraTextPadding = extraTextPadding,
2070 bgColor = bg,
2071 fgColor = fg,
2072 fontSize = fontSize,
2073 graphicsZoom = graphicsZoom,
2074 hotkey = hotkey,
2075 layerList = layerList,
2076 minDisplayPieces = minDisplayPieces,
2077 propertyFilter = propertyFilter,
2078 showDeck = showDeck,
2079 showDeckDepth = showDeckDepth,
2080 showDeckMasked = showDeckMasked,
2081 showMoveSelectde = showMoveSelectde,
2082 showNoStack = showNoStack,
2083 showNonMovable = showNonMovable,
2084 showOverlap = showOverlap,
2085 showgraph = showgraph,
2086 showgraphsingle = showgraphsingle,
2087 showtext = showtext,
2088 showtextsingle = showtextsingle,
2089 stretchWidthSummary = stretchWidthSummary,
2090 summaryReportFormat = summaryReportFormat,
2091 unrotatePieces = unrotatePieces,
2092 version = version,
2093 verticalOffset = verticalOffset,
2094 verticalTopText = verticalTopText,
2095 zoomlevel = zoomlevel,
2096 stopAfterShowing = stopAfterShowing)
2097
2098 registerElement(CounterDetailViewer)
2099
2100 # --------------------------------------------------------------------
2101 class GlobalMap(MapElement):
2102 TAG=Element.MAP+'GlobalMap'
2103 def __init__(self,map,node=None,
2104 buttonText = '',
2105 color = rgb(255,0,0),
2106 hotkey = key('O',CTRL_SHIFT),
2107 icon = '/images/overview.gif',
2108 scale = 0.2,
2109 tooltip = 'Show/Hide overview window'):
2110 super(GlobalMap,self).\
2111 __init__(map,self.TAG,node=node,
2112 buttonText = buttonText,
2113 color = color,
2114 hotkey = hotkey,
2115 icon = icon,
2116 scale = scale,
2117 tooltip = 'Show/Hide overview window')
2118
2119 registerElement(GlobalMap)
2120
2121 # --------------------------------------------------------------------
2122 class Zoomer(MapElement):
2123 TAG = Element.MAP+'Zoomer'
2124 def __init__(self,map,node=None,
2125 inButtonText = '',
2126 inIconName = '/images/zoomIn.gif',
2127 inTooltip = 'Zoom in',
2128 outButtonText = '',
2129 outIconName = '/images/zoomOut.gif',
2130 outTooltip = 'Zoom out',
2131 pickButtonText = '',
2132 pickIconName = '/images/zoom.png',
2133 pickTooltip = 'Select Zoom',
2134 zoomInKey = key('=',CTRL_SHIFT),
2135 zoomLevels = [0.2,0.25,0.333,0.4,0.5,
2136 0.555,0.625,0.75,1.0,1.25,1.6],
2137 zoomOutKey = key('-'),
2138 zoomPickKey = key('='),
2139 zoomStart = 3):
2140
2141 '''Zoom start is counting from the back (with default zoom levels,
2142 and zoom start, the default zoom is 1'''
2143 lvls = ','.join([str(z) for z in zoomLevels])
2144 super(Zoomer,self).\
2145 __init__(map,self.TAG,node=node,
2146 inButtonText = inButtonText,
2147 inIconName = inIconName,
2148 inTooltip = inTooltip,
2149 outButtonText = outButtonText,
2150 outIconName = outIconName,
2151 outTooltip = outTooltip,
2152 pickButtonText = pickButtonText,
2153 pickIconName = pickIconName,
2154 pickTooltip = pickTooltip,
2155 zoomInKey = zoomInKey,
2156 zoomLevels = lvls,
2157 zoomOutKey = zoomOutKey,
2158 zoomPickKey = zoomPickKey,
2159 zoomStart = zoomStart)
2160
2161 registerElement(Zoomer)
2162
2163 # --------------------------------------------------------------------
2164 class HidePiecesButton(MapElement):
2165 TAG=Element.MAP+'HidePiecesButton'
2166 def __init__(self,map,node=None,
2167 buttonText = '',
2168 hiddenIcon = '/images/globe_selected.gif',
2169 hotkey = key('O'),
2170 showingIcon = '/images/globe_unselected.gif',
2171 tooltip = 'Hide all pieces on this map'):
2172 super(HidePiecesButton,self).\
2173 __init__(map,self.TAG,node=node,
2174 buttonText = buttonText,
2175 hiddenIcon = hiddenIcon,
2176 hotkey = hotkey,
2177 showingIcon = showingIcon,
2178 tooltip = tooltip)
2179
2180 registerElement(HidePiecesButton)
2181
2182 # --------------------------------------------------------------------
2183 class MassKey(GlobalKey,MapElementService):
2184 TAG = Element.MAP+'MassKeyCommand'
2185 def __init__(self,map,node=None,
2186 name = '',
2187 buttonHotkey = '',
2188 hotkey = '',
2189 buttonText = '',
2190 canDisable = False,
2191 deckCount = '-1',
2192 filter = '',
2193 propertyGate = '',
2194 reportFormat = '',
2195 reportSingle = False,
2196 singleMap = True,
2197 target = GlobalKey.SELECTED,
2198 tooltip = '',
2199 icon = ''):
2200 '''Default targets are selected units'''
2201 super(MassKey,self).\
2202 __init__(map,self.TAG,node=node,
2203 name = name,
2204 buttonHotkey = buttonHotkey, # This hot key
2205 hotkey = hotkey, # Target hot key
2206 buttonText = buttonText,
2207 canDisable = canDisable,
2208 deckCount = deckCount,
2209 filter = filter,
2210 propertyGate = propertyGate,
2211 reportFormat = reportFormat,
2212 reportSingle = reportSingle,
2213 singleMap = singleMap,
2214 target = target,
2215 tooltip = tooltip,
2216 icon = icon)
2217
2218 registerElement(MassKey)
2219
2220 # --------------------------------------------------------------------
2221 class Flare(MapElement):
2222 TAG=Element.MAP+'Flare'
2223 def __init__(self,map,node=None,
2224 circleColor = rgb(255,0,0),
2225 circleScale = True,
2226 circleSize = 100,
2227 flareKey = 'keyAlt',
2228 flareName = 'Map Flare',
2229 flarePulses = 6,
2230 flarePulsesPerSec = 3,
2231 reportFormat = ''):
2232 super(Flare,self).__init__(map,self.TAG,node=node,
2233 circleColor = circleColor,
2234 circleScale = circleScale,
2235 circleSize = circleSize,
2236 flareKey = flareKey,
2237 flareName = flareName,
2238 flarePulses = flarePulses,
2239 flarePulsesPerSec = flarePulsesPerSec,
2240 reportFormat = '')
2241
2242 registerElement(Flare)
2243
2244 # --------------------------------------------------------------------
2245 class AtStart(MapElement):
2246 TAG = Element.MODULE+'map.SetupStack'
2247 def __init__(self,map,
2248 node = None,
2249 name = '',
2250 location = '',
2251 useGridLocation = True,
2252 owningBoard = '',
2253 x = 0,
2254 y = 0):
2255 '''Pieces are existing PieceSlot elements
2256
2257
2258 Parameters
2259 ----------
2260 node : xml.minidom.Node
2261 Existing node or None
2262 name : str
2263 Name of node
2264 location : str
2265 Where the at-start element is put if `useGridLocation`
2266 useGridLocation : bool
2267 If true, use maps grid
2268 owningBoard : str
2269 Board that owns the at-start (can be empty)
2270 x : float
2271 Coordinate (ignored if `useGridLocation`)
2272 y : float
2273 Coordinate (ignored if `useGridLocation`)
2274 '''
2275 super(AtStart,self).\
2276 __init__(map,self.TAG,node=node,
2277 name = name,
2278 location = location,
2279 owningBoard = owningBoard,
2280 useGridLocation = useGridLocation,
2281 x = x,
2282 y = y)
2283
2284 def addPieces(self,*pieces):
2285 '''Add a `Pieces` element to this
2286
2287 Parameters
2288 ----------
2289 kwargs : dict
2290 Dictionary of attribute key-value pairs
2291
2292 Returns
2293 -------
2294 element : Pieces
2295 The added element
2296 '''
2297 # copy pieces here
2298 copies = []
2299 for p in pieces:
2300 c = self.addPiece(p)
2301 if c is not None:
2302 copies.append(c)
2303 return copies
2304
2305 def addPiece(self,piece):
2306 '''Add a `Piece` element to this
2307
2308 Parameters
2309 ----------
2310 kwargs : dict
2311 Dictionary of attribute key-value pairs
2312
2313 Returns
2314 -------
2315 element : Piece
2316 The added element
2317 '''
2318 if not isinstance(piece,PieceSlot):
2319 print(f'Trying to add {type(piece)} to AtStart')
2320 return None
2321
2322 p = piece.clone(self)
2323 # self._node.appendChild(p._node)
2324 return p
2325
2326 def getPieces(self,asdict=True):
2327 '''Get all Piece element(s) from this
2328
2329 Parameters
2330 ----------
2331 asdict : bool
2332 If `True`, return a dictonary that maps key to `Piece`
2333 elements. If `False`, return a list of all Piece`
2334 children.
2335
2336 Returns
2337 -------
2338 children : dict or list
2339 Dictionary or list of `Piece` children
2340
2341 '''
2342 return self.getElementsByKey(PieceSlot,'entryName',asdict)
2343
2344 registerElement(AtStart)
2345
2346 #
2347 # EOF
2348 #
2349 # ====================================================================
2350 # From globalproperty.py
2351
2352 # --------------------------------------------------------------------
2353 class GlobalProperties(Element):
2354 TAG = Element.MODULE+'properties.GlobalProperties'
2355 def __init__(self,elem,node=None,**named):
2356 super(GlobalProperties,self).__init__(elem,self.TAG,node=node)
2357
2358 for n, p in named:
2359 self.addProperty(n, **p)
2360
2361 def getGame(self):
2362 return self.getParent(Game)
2363 def addProperty(self,**kwargs):
2364 '''Add a `Property` element to this
2365
2366 Parameters
2367 ----------
2368 kwargs : dict
2369 Dictionary of attribute key-value pairs
2370
2371 Returns
2372 -------
2373 element : Property
2374 The added element
2375 '''
2376 return GlobalProperty(self,node=None,**kwargs)
2377 def getProperties(self):
2378 return getElementsByKey(GlobalProperty,'name')
2379
2380 registerElement(GlobalProperties)
2381
2382 # --------------------------------------------------------------------
2383 class GlobalProperty(Element):
2384 TAG = Element.MODULE+'properties.GlobalProperty'
2385 def __init__(self,elem,node=None,
2386 name = '',
2387 initialValue = '',
2388 isNumeric = False,
2389 min = "null",
2390 max = "null",
2391 wrap = False,
2392 description = ""):
2393 super(GlobalProperty,self).__init__(elem,self.TAG,
2394 node = node,
2395 name = name,
2396 initialValue = initialValue,
2397 isNumeric = isNumeric,
2398 min = min,
2399 max = max,
2400 wrap = wrap,
2401 description = description)
2402
2403 def getGlobalProperties(self):
2404 return self.getParent(GlobalProperties)
2405
2406 registerElement(GlobalProperty)
2407
2408 #
2409 # EOF
2410 #
2411 # ====================================================================
2412 # From turn.py
2413
2414 # --------------------------------------------------------------------
2415 class TurnLevel(Element):
2416 def __init__(self,elem,tag,node=None,**kwargs):
2417 super(TurnLevel,self).__init__(elem,tag,node=node,**kwargs)
2418
2419 def addLevel(self,counter=None,phases=None):
2420 '''Add a `Level` element to this
2421
2422 Parameters
2423 ----------
2424 kwargs : dict
2425 Dictionary of attribute key-value pairs
2426
2427 Returns
2428 -------
2429 element : Level
2430 The added element
2431 '''
2432 if counter is None and phases is None:
2433 return self
2434
2435 t = TurnCounter if counter is not None else TurnList
2436 o = counter if counter is not None else phases
2437
2438 subcounter = o.pop('counter',None)
2439 subphases = o.pop('phases',None)
2440
2441 s = t(self,node=None,**o)
2442
2443 return s.addLevel(subcounter, subphases)
2444
2445 def getUp(self):
2446 return self.getParent(TurnLevel)
2447 def addCounter(self,**kwargs):
2448 '''Add a `Counter` element to this
2449
2450 Parameters
2451 ----------
2452 kwargs : dict
2453 Dictionary of attribute key-value pairs
2454
2455 Returns
2456 -------
2457 element : Counter
2458 The added element
2459 '''
2460 return self.add(self,TurnCounter,**kwargs)
2461 def addList(self,**kwargs):
2462 '''Add a `List` element to this
2463
2464 Parameters
2465 ----------
2466 kwargs : dict
2467 Dictionary of attribute key-value pairs
2468
2469 Returns
2470 -------
2471 element : List
2472 The added element
2473 '''
2474 return self.add(self,TurnList,**kwargs)
2475 def getCounter(self):
2476 return self.getAllElements(TurnCounter)
2477 def getList(self):
2478 return self.getAllElements(TurnList)
2479
2480 # --------------------------------------------------------------------
2481 class TurnTrack(TurnLevel):
2482 TAG = Element.MODULE+'turn.TurnTracker'
2483 def __init__(self,elem,node=None,
2484 name = '',
2485 buttonText = 'Turn',
2486 hotkey = '',
2487 icon = '',
2488 length = -1,
2489 lengthStyle = 'Maximum',
2490 nexthotkey = key('T',ALT),
2491 plusButtonSize = 22,
2492 prevhotkey = key('T',ALT_SHIFT),
2493 reportFormat = 'Turn updated from $oldTurn$ to $newTurn$',
2494 turnButtonHeight = 22,
2495 fwdOnly = True,
2496 turnFormat = None,
2497 counter = None,
2498 phases = None):
2499 levels = (counter if counter is not None else
2500 phases if phases is not None else None)
2501 if levels is not None:
2502 lvl = 1
2503 lvls = [f'$level{lvl}$']
2504 sub = levels
2505 while True:
2506 sub = sub.get('counter',sub.get('phases',None))
2507 if sub is None:
2508 break
2509 lvl += 1
2510 lvls.append(f'$level{lvl}$')
2511
2512 turnFormat = ' '.join(lvls)
2513
2514 if turnFormat is None:
2515 turnFormat = '$level1$ $level2$ $level3$ $level4$'
2516
2517 super(TurnTrack,self).__init__(elem, self.TAG,
2518 node = node,
2519 name = name,
2520 buttonText = buttonText,
2521 hotkey = hotkey,
2522 icon = icon,
2523 length = length,
2524 lengthStyle = lengthStyle,
2525 nexthotkey = nexthotkey,
2526 plusButtonSize = plusButtonSize,
2527 prevhotkey = prevhotkey,
2528 reportFormat = reportFormat,
2529 turnButtonHeight = turnButtonHeight,
2530 turnFormat = turnFormat)
2531
2532 self.addLevel(counter=counter, phases=phases)
2533
2534 def getGame(self):
2535 return self.getParent(Game)
2536 def getLists(self,asdict=True):
2537 '''Get all List element(s) from this
2538
2539 Parameters
2540 ----------
2541 asdict : bool
2542 If `True`, return a dictonary that maps key to `List`
2543 elements. If `False`, return a list of all List`
2544 children.
2545
2546 Returns
2547 -------
2548 children : dict or list
2549 Dictionary or list of `List` children
2550
2551 '''
2552 return self.getElementsByKey(TurnList,'property',asdict=asdict)
2553 def getCounters(self,asdict=True):
2554 '''Get all Counter element(s) from this
2555
2556 Parameters
2557 ----------
2558 asdict : bool
2559 If `True`, return a dictonary that maps key to `Counter`
2560 elements. If `False`, return a list of all Counter`
2561 children.
2562
2563 Returns
2564 -------
2565 children : dict or list
2566 Dictionary or list of `Counter` children
2567
2568 '''
2569 return self.getElementsByKey(TurnCounter,'property',asdict=asdict)
2570 def addHotkey(self,**kwargs):
2571 '''Add a `Hotkey` element to this
2572
2573 Parameters
2574 ----------
2575 kwargs : dict
2576 Dictionary of attribute key-value pairs
2577
2578 Returns
2579 -------
2580 element : Hotkey
2581 The added element
2582 '''
2583 return self.add(TurnGlobalHotkey,**kwargs)
2584 def getHotkeys(self,asdict):
2585 return self.getElementsByKey(TurnGlobalHotkey,'name',asdict=asdict)
2586 def encode(self):
2587 ret = f'TURN{self["name"]}\t'
2588
2589 return []
2590
2591 registerElement(TurnTrack)
2592
2593 # --------------------------------------------------------------------
2594 class TurnCounter(TurnLevel):
2595 TAG = Element.MODULE+"turn.CounterTurnLevel"
2596 def __init__(self,elem,node=None,
2597 property = '',
2598 start = 1,
2599 incr = 1,
2600 loop = False,
2601 loopLimit = -1,
2602 turnFormat = "$value$"):
2603 super(TurnCounter,self).__init__(elem,self.TAG,node=node,
2604 property = property,
2605 start = start,
2606 incr = incr,
2607 loop = loop,
2608 loopLimit = loopLimit,
2609 turnFormat = turnFormat)
2610
2611 registerElement(TurnCounter)
2612
2613 # --------------------------------------------------------------------
2614 class TurnList(TurnLevel):
2615 TAG = Element.MODULE+"turn.ListTurnLevel"
2616 def __init__(self,elem,node=None,
2617 property = '',
2618 names = [],
2619 configFirst = False,
2620 configList = False,
2621 turnFormat = '$value$'):
2622 super(TurnList,self).\
2623 __init__(elem,self.TAG,node=node,
2624 property = property,
2625 list = ','.join([str(p) for p in names]),
2626 configFirst = configFirst,
2627 configList = configList,
2628 turnFormat = turnFormat)
2629
2630 registerElement(TurnList)
2631
2632 # --------------------------------------------------------------------
2633 class TurnGlobalHotkey(Element):
2634 TAG = Element.MODULE+'turn.TurnGlobalHotkey'
2635 def __init__(self,elem,
2636 node = None,
2637 hotkey = '',
2638 match = '{true}',
2639 reportFormat = '',
2640 name = ''):
2641 '''Global key activated by turn change
2642
2643 Parameters
2644 ----------
2645 doc : Element
2646 Parent
2647 node : xml.dom.Element
2648 Node to read state from
2649 hotkey : str
2650 What to send (global command)
2651 match : str
2652 When to send
2653 reportFormat : str
2654 What to what
2655 name : str
2656 A free form name
2657 '''
2658 super(TurnGlobalHotkey,self).__init__(elem,self.TAG,
2659 node = node,
2660 hotkey = hotkey,
2661 match = match,
2662 reportFormat = reportFormat,
2663 name = name)
2664
2665 def getTurnTrack(self):
2666 '''Get the turn track'''
2667 return self.getParent(TurnTrack)
2668
2669 registerElement(TurnGlobalHotkey)
2670
2671 #
2672 # EOF
2673 #
2674 # ====================================================================
2675 # From documentation.py
2676
2677 # ====================================================================
2678 def createKeyHelp(*args,**kwargs):
2679 '''Creates a help file with key-bindings
2680
2681 See Documentation.createKeyHelp
2682 '''
2683 return Documentation.createKeyHelp(*args,**kwargs)
2684
2685 # --------------------------------------------------------------------
2686 class Documentation(GameElement):
2687 TAG=Element.MODULE+'Documentation'
2688 def __init__(self,doc,node=None,**kwargs):
2689 '''Documentation (or help menu)
2690
2691 Parameters
2692 ----------
2693 doc : Element
2694 Parent
2695 node : xml.dom.Element
2696 Node to read state from
2697 kwargs : dict
2698 Attributes
2699 '''
2700 super(Documentation,self).__init__(doc,self.TAG,node=node,**kwargs)
2701
2702 def addAboutScreen(self,**kwargs):
2703 '''Add a `AboutScreen` element to this
2704
2705 Parameters
2706 ----------
2707 kwargs : dict
2708 Dictionary of attribute key-value pairs
2709
2710 Returns
2711 -------
2712 element : AboutScreen
2713 The added element
2714 '''
2715 return self.add(AboutScreen,**kwargs)
2716 def addHelpFile(self,**kwargs):
2717 '''Add a `HelpFile` element to this
2718
2719 Parameters
2720 ----------
2721 kwargs : dict
2722 Dictionary of attribute key-value pairs
2723
2724 Returns
2725 -------
2726 element : HelpFile
2727 The added element
2728 '''
2729 return self.add(HelpFile,**kwargs)
2730 def addBrowserHelpFile(self,**kwargs):
2731 '''Add a `BrowserHelpFile` element to this
2732
2733 Parameters
2734 ----------
2735 kwargs : dict
2736 Dictionary of attribute key-value pairs
2737
2738 Returns
2739 -------
2740 element : BrowserHelpFile
2741 The added element
2742 '''
2743 return self.add(HelpBrowserFile,**kwargs)
2744 def addBrowserPDFFile(self,**kwargs):
2745 '''Add a `BrowserPDFFile` element to this
2746
2747 Parameters
2748 ----------
2749 kwargs : dict
2750 Dictionary of attribute key-value pairs
2751
2752 Returns
2753 -------
2754 element : BrowserPDFFile
2755 The added element
2756 '''
2757 return self.add(BrowserPDFFile,**kwargs)
2758 def addTutorial(self,**kwargs):
2759 '''Add a `Tutorial` element to this
2760
2761 Parameters
2762 ----------
2763 kwargs : dict
2764 Dictionary of attribute key-value pairs
2765
2766 Returns
2767 -------
2768 element : Tutorial
2769 The added element
2770 '''
2771 return self.add(Tutorial,**kwargs)
2772 def getAboutScreens(self):
2773 return self.getElementsByKey(AboutScreen,'title')
2774 def getHelpFiles(self):
2775 return self.getElementsByKey(HelpFile,'title')
2776 def getBrowserHelpFiles(self):
2777 return self.getElementsByKey(BrowserHelpFile,'title')
2778 def getBrowserPDFFiles(self):
2779 return self.getElementsByKey(BrowserPDFFile,'title')
2780 def getTutorials(self):
2781 return self.getElementsByKey(Tutorial,'name')
2782
2783 @classmethod
2784 def createKeyHelp(cls,keys,title='',version=''):
2785 '''Creates a help file with key-bindings
2786
2787 Parameters
2788 ----------
2789 keys : list of list of str
2790 List of key-binding documentation
2791 title : str
2792 Title of help file
2793 version : str
2794 Version number
2795
2796 Returns
2797 -------
2798 txt : str
2799 File content
2800 '''
2801 txt = f'''
2802 <html>
2803 <body>
2804 <h1>{title} (Version {version}) Key bindings</h1>
2805 <table>
2806 <tr><th>Key</th><th>Where</th><th>Effect</th></tr>'''
2807
2808 for key, where, description in keys:
2809 txt += (f'<tr><td>{key}</td>'
2810 f'<td>{where}</td>'
2811 f'<td>{description}</td></tr>')
2812
2813 txt += '''
2814 </table>
2815 </body>
2816 </html>'''
2817
2818 return txt
2819
2820 registerElement(Documentation)
2821
2822 # --------------------------------------------------------------------
2823 class AboutScreen(Element):
2824 TAG = Element.MODULE+'documentation.AboutScreen'
2825 def __init__(self,doc,node=None,title='',fileName=""):
2826 '''Create an about screen element that shows image
2827
2828 Parameters
2829 ----------
2830 doc : Element
2831 Parent
2832 node : xml.dom.Element
2833 Node to read state from
2834 title : str
2835 Entry title
2836 fileName : str
2837 Internal file name
2838 '''
2839 super(AboutScreen,self).__init__(doc,
2840 self.TAG,
2841 node = node,
2842 fileName = fileName,
2843 title = title)
2844 def getDocumentation(self):
2845 '''Get Parent element'''
2846 return self.getParent(Documentation)
2847
2848 registerElement(AboutScreen)
2849
2850 # --------------------------------------------------------------------
2851 class BrowserPDFFile(Element):
2852 TAG = Element.MODULE+'documentation.BrowserPDFFile'
2853 def __init__(self,doc,node=None,title='',pdfFile=''):
2854 '''Create help menu item that opens an embedded PDF
2855
2856 Parameters
2857 ----------
2858 doc : Element
2859 Parent
2860 node : xml.dom.Element
2861 Node to read state from
2862 title : str
2863 Entry title
2864 pdfFile : str
2865 Internal file name
2866 '''
2867 super(BrowserPDFFile,self).__init__(doc,self.TAG,
2868 node = node,
2869 pdfFile = pdfFile,
2870 title = title)
2871 def getDocumentation(self):
2872 '''Get Parent element'''
2873 return self.getParent(Documentation)
2874
2875 registerElement(BrowserPDFFile)
2876
2877 # --------------------------------------------------------------------
2878 class HelpFile(Element):
2879 TAG = Element.MODULE+'documentation.HelpFile'
2880 ARCHIVE = 'archive'
2881 def __init__(self,doc,node=None,
2882 title='',
2883 fileName='',
2884 fileType=ARCHIVE):
2885 '''Create a help menu entry that opens an embeddded file
2886
2887 Parameters
2888 ----------
2889 doc : Element
2890 Parent
2891 node : xml.dom.Element
2892 Node to read state from
2893 title : str
2894 Entry title
2895 fileName : str
2896 Internal file name
2897 fileType : str
2898 How to find the file
2899 '''
2900 super(HelpFile,self).__init__(doc,self.TAG,node=node,
2901 fileName = fileName,
2902 fileType = fileType,
2903 title = title)
2904
2905 def getDocumentation(self):
2906 '''Get Parent element'''
2907 return self.getParent(Documentation)
2908
2909 registerElement(HelpFile)
2910
2911 # --------------------------------------------------------------------
2912 class BrowserHelpFile(Element):
2913 TAG = Element.MODULE+'documentation.BrowserHelpFile'
2914 def __init__(self,doc,node=None,
2915 title='',
2916 startingPage='index.html'):
2917 '''Create a help menu entry that opens an embeddded HTML
2918 page (with possible sub-pages) file
2919
2920 Parameters
2921 ----------
2922 doc : Element
2923 Parent
2924 node : xml.dom.Element
2925 Node to read state from
2926 title : str
2927 Entry title
2928 startingPage : str
2929 which file to start at
2930 '''
2931 super(BrowserHelpFile,self).__init__(doc,self.TAG,node=node,
2932 startingPage=startingPage,
2933 title=title)
2934
2935 def getDocumentation(self):
2936 '''Get Parent element'''
2937 return self.getParent(Documentation)
2938
2939 registerElement(BrowserHelpFile)
2940
2941 # --------------------------------------------------------------------
2942 class Tutorial(Element):
2943 TAG = Element.MODULE+'documentation.Tutorial'
2944 def __init__(self,doc,node=None,
2945 name = 'Tutorial',
2946 logfile = 'tutorial.vlog',
2947 promptMessage = 'Load the tutorial?',
2948 welcomeMessage = 'Press "Step forward" (PnDn) to step through the tutorial',
2949 launchOnStartup = True):
2950 '''Add a help menu item that loads the tutorial
2951
2952 Also adds the start-up option to run the tutorial
2953
2954
2955 Parameters
2956 ----------
2957 doc : Element
2958 Parent
2959 node : xml.dom.Element
2960 Node to read state from
2961 name : str
2962 Name of entry
2963 logfile : str
2964 Internal file name
2965 promptMessage : str
2966 What to show
2967 launchOnStartup : bool
2968 By default, launch tutorial first time running module
2969 '''
2970 super(Tutorial,self).__init__(doc,self.TAG,node=node,
2971 name = name,
2972 logfile = logfile,
2973 promptMessage = promptMessage,
2974 welcomeMessage = welcomeMessage,
2975 launchOnStartup = launchOnStartup)
2976
2977 def getDocumentation(self):
2978 '''Get Parent element'''
2979 return self.getParent(Documentation)
2980
2981 registerElement(Tutorial)
2982
2983
2984 #
2985 # EOF
2986 #
2987 # ====================================================================
2988 # From player.py
2989
2990 # --------------------------------------------------------------------
2991 class PlayerRoster(GameElement):
2992 TAG = Element.MODULE+'PlayerRoster'
2993 def __init__(self,doc,node=None,buttonKeyStroke='',
2994 buttonText='Retire',
2995 buttonToolTip='Switch sides, become observer, or release faction'):
2996 '''Add a player roster to the module
2997
2998 Parameters
2999 ----------
3000 doc : Element
3001 Parent
3002 node : xml.dom.Element
3003 Node to read state from
3004 buttonText : str
3005 Text on button
3006 buttonTooltip : str
3007 Tool tip to show when hovering over button
3008 '''
3009 super(PlayerRoster,self).__init__(doc,self.TAG,node=node,
3010 buttonKeyStroke = buttonKeyStroke,
3011 buttonText = buttonText,
3012 buttonToolTip = buttonToolTip)
3013 def addSide(self,name):
3014 '''Add a `Side` element to this
3015
3016 Parameters
3017 ----------
3018 kwargs : dict
3019 Dictionary of attribute key-value pairs
3020
3021 Returns
3022 -------
3023 element : Side
3024 The added element
3025 '''
3026 return self.add(PlayerSide,name=name)
3027 def getSides(self):
3028 '''Get all sides'''
3029 return self.getAllElements(PlayerSide,False)
3030 def encode(self):
3031 '''Encode for save'''
3032 return ['PLAYER\ta\ta\t<observer>']
3033
3034 registerElement(PlayerRoster)
3035
3036 # --------------------------------------------------------------------
3037 class PlayerSide(Element):
3038 TAG = 'entry'
3039 def __init__(self,doc,node=None,name=''):
3040 '''Adds a side to the player roster
3041
3042 Parameters
3043 ----------
3044 doc : Element
3045 Parent
3046 node : xml.dom.Element
3047 Node to read state from
3048 name : str
3049 Name of side
3050 '''
3051 super(PlayerSide,self).__init__(doc,self.TAG,node=node)
3052 if node is None:
3053 self.addText(name)
3054
3055 def getPlayerRoster(self):
3056 '''Get Parent element'''
3057 return self.getParent(PlayerRoster)
3058
3059 registerElement(PlayerSide)
3060
3061
3062 #
3063 # EOF
3064 #
3065 # ====================================================================
3066 # From chessclock.py
3067
3068 # ====================================================================
3069 class ChessClock(Element):
3070 TAG=Element.MODULE+'chessclockcontrol.ChessClock'
3071 def __init__(self,
3072 doc,
3073 node = None,
3074 icon = '',
3075 description = '',
3076 side = '',
3077 tooltip = 'Individual clock control',
3078 buttonText = '',
3079 startHotkey = '',
3080 stopHotkey = '',
3081 tickingBackgroundColor = rgb(255,255,0),
3082 tickingFontColor = rgb(0,0,0),
3083 tockingFontColor = rgb(51,51,51)):
3084 '''Individual clock for a side
3085
3086 When the clock is running, the background colour may be
3087 changed, and the colour of the numbers alternate between
3088 `tickingFontColor` and `tockingFontColor`.
3089
3090 Parameters
3091 ----------
3092 doc : Element
3093 Parent element
3094 node : xml.dom.Element
3095 Read from this node
3096 icon : str
3097 File name of button icon
3098 description : str
3099 Note on this clock
3100 side : str
3101 Name of side this clock belongs to
3102 tooltop : str
3103 Hover help text
3104 buttonText : str
3105 Text on button
3106 startHotkey : str (key code)
3107 Key or command to start timer
3108 stopHotkey : str (key code)
3109 Key or command to stop timer
3110 tickingBackgroundColor : str (color)
3111 Background color of time display when clock is running
3112 tickingFontColor : str (color)
3113 First color of numbers in display when clock is running.
3114 tockingFontColor : str (color)
3115 Second color of numbers in display when clock is running.
3116 '''
3117 super(ChessClock,self).__init__(#ChessClock
3118 doc,
3119 self.TAG,
3120 node = node,
3121 icon = icon,
3122 description = description,
3123 side = side,
3124 tooltip = tooltip,
3125 buttonText = buttonText,
3126 startHotkey = startHotkey,
3127 stopHotkey = stopHotkey,
3128 tickingBackgroundColor = tickingBackgroundColor,
3129 tickingFontColor = tickingFontColor,
3130 tockingFontColor = tockingFontColor)
3131
3132 def getControl(self):
3133 '''Get Parent element'''
3134 return self.getParent(ChessClockControl)
3135
3136 registerElement(ChessClock)
3137
3138 # ====================================================================
3139 class ChessClockControl(GameElement):
3140 TAG=Element.MODULE+'ChessClockControl'
3141 ALWAYS = 'Always'
3142 AUTO = 'Auto'
3143 NEVER = 'Never'
3144 def __init__(self,
3145 doc,
3146 node = None,
3147 name = 'Chess clock',
3148 description = '',
3149 buttonIcon = 'chess_clock.png',
3150 buttonText = '',
3151 buttonTooltip = 'Show/stop/hide chess clocks',
3152 showHotkey = key('U',ALT),
3153 pauseHotkey = key('U',CTRL_SHIFT),
3154 nextHotkey = key('U'),
3155 startOpponentKey = '',
3156 showTenths = AUTO,
3157 showSeconds = AUTO,
3158 showHours = AUTO,
3159 showDays = AUTO,
3160 allowReset = False,
3161 addClocks = True):
3162 '''A set of chess clocs
3163
3164 Parameters
3165 ----------
3166 doc : Element
3167 Parent
3168 node : xml.dom.Element
3169 Node to read state from
3170 name : str
3171 Name of clock control
3172 description : str
3173 Note on the chess clocks control
3174 buttonIcon : str
3175 Icon file name for button (chess_clock.png)
3176 buttonText : str
3177 Text on button
3178 buttonTooltip : str
3179 Hower help
3180 showHotkey : str (key code)
3181 Show or hide interface hot key
3182 nextHotkey : str (key code)
3183 Start the next clock hot key
3184 pauseHotkey : str (key code)
3185 Pause all clocks hot key
3186 startOpponentKey : str (key code)
3187 Start opponens clock
3188 showTenths : one of AUTO, ALWAYS, NEVER
3189 Whether to show tenths of seconds
3190 showSeconds : one of AUTO, ALWAYS, NEVER
3191 Whether to show seconds in clock
3192 showHours : one of AUTO, ALWAYS, NEVER
3193 Whether to show hours in clock
3194 showDays : one of AUTO, ALWAYS, NEVER
3195 Whether to show days in clock
3196 allowReset : boolean
3197 If true, allow manual reset of all clocks
3198 '''
3199 super(ChessClockControl,self).__init__(# ChessclockControl
3200 doc,
3201 self.TAG,
3202 node = node,
3203 name = name,
3204 description = description,
3205 buttonIcon = buttonIcon,
3206 buttonText = buttonText,
3207 buttonTooltip = buttonTooltip,
3208 showHotkey = showHotkey,
3209 pauseHotkey = pauseHotkey,
3210 nextHotkey = nextHotkey,
3211 startOpponentKey = startOpponentKey,
3212 showTenths = showTenths,
3213 showSeconds = showSeconds,
3214 showHours = showHours,
3215 showDays = showDays,
3216 allowReset = allowReset)
3217 print(node,addClocks)
3218 if node is not None or not addClocks:
3219 return
3220
3221 print('--- Will add clocks')
3222 game = self.getGame()
3223 roster = game.getPlayerRoster()[0]
3224 sides = roster.getSides()
3225 for side in sides:
3226 name = side.getText()
3227 self.addClock(side = name,
3228 tooltip = f'Clock for {name}',
3229 buttonText = name,
3230 startHotkey = key('U'),
3231 stopHotkey = key('U'))
3232
3233 def addClock(self,**kwargs):
3234 '''Add a clock element to this
3235
3236 Parameters
3237 ----------
3238 kwargs : dict
3239 Dictionary of attribute key-value pairs
3240
3241 Returns
3242 -------
3243 element : AboutScreen
3244 The added element
3245 '''
3246 return self.add(ChessClock,**kwargs)
3247 def getClocks(self,asdict=True):
3248 '''Return dictionary of clocs'''
3249 return self.getElementsByKey(ChessClock,'side',asdict)
3250
3251 registerElement(ChessClockControl)
3252
3253 #
3254 # EOF
3255 #
3256 # ====================================================================
3257 # From widget.py
3258
3259 # --------------------------------------------------------------------
3260 class WidgetElement:
3261 def __init__(self):
3262 pass
3263
3264 def addTabs(self,**kwargs):
3265 '''Add a `Tabs` element to this
3266
3267 Parameters
3268 ----------
3269 kwargs : dict
3270 Dictionary of attribute key-value pairs
3271
3272 Returns
3273 -------
3274 element : Tabs
3275 The added element
3276 '''
3277 return self.add(TabWidget,**kwargs)
3278 def addCombo(self,**kwargs):
3279 '''Add a drop-down menu to this
3280
3281 Parameters
3282 ----------
3283 Dictionary of attribute key-value pairs
3284
3285 Returns
3286 -------
3287 element : Combo
3288 The added element
3289 '''
3290 return self.add(ComboWidget,**kwargs)
3291 def addPanel(self,**kwargs):
3292 '''Add a `Panel` element to this
3293
3294 Parameters
3295 ----------
3296 kwargs : dict
3297 Dictionary of attribute key-value pairs
3298
3299 Returns
3300 -------
3301 element : Panel
3302 The added element
3303 '''
3304 return self.add(PanelWidget,**kwargs)
3305 def addList(self,**kwargs):
3306 '''Add a `List` element to this
3307
3308 Parameters
3309 ----------
3310 kwargs : dict
3311 Dictionary of attribute key-value pairs
3312
3313 Returns
3314 -------
3315 element : List
3316 The added element
3317 '''
3318 return self.add(ListWidget,**kwargs)
3319 def addMapWidget(self,**kwargs):
3320 '''Add a `MapWidget` element to this
3321
3322 Parameters
3323 ----------
3324 kwargs : dict
3325 Dictionary of attribute key-value pairs
3326
3327 Returns
3328 -------
3329 element : MapWidget
3330 The added element
3331 '''
3332 return self.add(MapWidget,**kwargs)
3333 def addChart(self,**kwargs):
3334 '''Add a `Chart` element to this
3335
3336 Parameters
3337 ----------
3338 kwargs : dict
3339 Dictionary of attribute key-value pairs
3340
3341 Returns
3342 -------
3343 element : Chart
3344 The added element
3345 '''
3346 return self.add(Chart,**kwargs)
3347 def addPieceSlot(self,**kwargs):
3348 '''Add a `PieceSlot` element to this
3349
3350 Parameters
3351 ----------
3352 kwargs : dict
3353 Dictionary of attribute key-value pairs
3354
3355 Returns
3356 -------
3357 element : PieceSlot
3358 The added element
3359 '''
3360 return self.add(PieceSlot,**kwargs)
3361 def addPiece(self,piece):
3362 '''Add a `Piece` element to this
3363
3364 Parameters
3365 ----------
3366 kwargs : dict
3367 Dictionary of attribute key-value pairs
3368
3369 Returns
3370 -------
3371 element : Piece
3372 The added element
3373 '''
3374 if not isinstance(piece,PieceSlot):
3375 print(f'Trying to add {type(piece)} to ListWidget')
3376 return None
3377
3378 p = piece.clone(self)
3379 return p
3380 def getTabs(self,asdict=True):
3381 '''Get all Tab element(s) from this
3382
3383 Parameters
3384 ----------
3385 asdict : bool
3386 If `True`, return a dictonary that maps key to `Tab` elements. If `False`, return a list of all Tab` children.
3387
3388 Returns
3389 -------
3390 children : dict or list
3391 Dictionary or list of `Tab` children
3392 '''
3393 return self.getElementsByKey(TabWidget,'entryName',asdict)
3394 def getCombos(self,asdict=True):
3395 '''Get all Combo element(s) from this
3396
3397 Parameters
3398 ----------
3399 asdict : bool
3400 If `True`, return a dictonary that maps key to `Tab` elements. If `False`, return a list of all Tab` children.
3401
3402 Returns
3403 -------
3404 children : dict or list
3405 Dictionary or list of `Tab` children
3406 '''
3407 return self.getElementsByKey(ComboWidget,'entryName',asdict)
3408 def getLists(self,asdict=True):
3409 '''Get all List element(s) from this
3410
3411 Parameters
3412 ----------
3413 asdict : bool
3414 If `True`, return a dictonary that maps key to `List` elements. If `False`, return a list of all List` children.
3415
3416 Returns
3417 -------
3418 children : dict or list
3419 Dictionary or list of `List` children
3420 '''
3421 return self.getElementsByKey(ListWidget,'entryName',asdict)
3422 def getPanels(self,asdict=True):
3423 '''Get all Panel element(s) from this
3424
3425 Parameters
3426 ----------
3427 asdict : bool
3428 If `True`, return a dictonary that maps key to `Panel` elements. If `False`, return a list of all Panel` children.
3429
3430 Returns
3431 -------
3432 children : dict or list
3433 Dictionary or list of `Panel` children
3434 '''
3435 return self.getElementsByKey(PanelWidget,'entryName',asdict)
3436 def getMapWidgets(self,asdict=True):
3437 '''Get all MapWidget element(s) from this
3438
3439 Parameters
3440 ----------
3441 asdict : bool
3442 If `True`, return a dictonary that maps key to `MapWidget` elements. If `False`, return a list of all MapWidget` children.
3443
3444 Returns
3445 -------
3446 children : dict or list
3447 Dictionary or list of `MapWidget` children
3448 '''
3449 return self.getElementsByKey(MapWidget,'entryName',asdict)
3450 def getCharts(self,asdict=True):
3451 '''Get all Chart element(s) from this
3452
3453 Parameters
3454 ----------
3455 asdict : bool
3456 If `True`, return a dictonary that maps key to `Chart` elements. If `False`, return a list of all Chart` children.
3457
3458 Returns
3459 -------
3460 children : dict or list
3461 Dictionary or list of `Chart` children
3462 '''
3463 return self.getElementsByKey(Chart,'chartName',asdict)
3464 def getPieceSlots(self,asdict=True):
3465 '''Get all PieceSlot element(s) from this
3466
3467 Parameters
3468 ----------
3469 asdict : bool
3470 If `True`, return a dictonary that maps key to `PieceSlot` elements. If `False`, return a list of all PieceSlot` children.
3471
3472 Returns
3473 -------
3474 children : dict or list
3475 Dictionary or list of `PieceSlot` children
3476 '''
3477 return self.getElementsByKey(PieceSlot,'entryName',asdict)
3478
3479 # --------------------------------------------------------------------
3480 class PieceWindow(GameElement,WidgetElement):
3481 TAG=Element.MODULE+'PieceWindow'
3482 def __init__(self,elem,node=None,
3483 name = '',
3484 defaultWidth = 0,
3485 hidden = False,
3486 hotkey = key('C',ALT),
3487 scale = 1.,
3488 text = '',
3489 tooltip = 'Show/hide piece window',
3490 icon = '/images/counter.gif'):
3491 super(PieceWindow,self).__init__(elem,self.TAG,node=node,
3492 name = name,
3493 defaultWidth = defaultWidth,
3494 hidden = hidden,
3495 hotkey = hotkey,
3496 scale = scale,
3497 text = text,
3498 tooltip = tooltip,
3499 icon = icon)
3500
3501 registerElement(PieceWindow)
3502
3503 # --------------------------------------------------------------------
3504 class ComboWidget(Element,WidgetElement):
3505 TAG=Element.WIDGET+'BoxWidget'
3506 def __init__(self,elem,node=None,entryName='',width=0,height=0):
3507 super(ComboWidget,self).__init__(elem,
3508 self.TAG,
3509 node = node,
3510 entryName = entryName,
3511 width = width,
3512 height = height)
3513
3514 registerElement(ComboWidget)
3515
3516 # --------------------------------------------------------------------
3517 class TabWidget(Element,WidgetElement):
3518 TAG=Element.WIDGET+'TabWidget'
3519 def __init__(self,elem,node=None,entryName=''):
3520 super(TabWidget,self).__init__(elem,
3521 self.TAG,
3522 node = node,
3523 entryName = entryName)
3524
3525 registerElement(TabWidget)
3526
3527 # --------------------------------------------------------------------
3528 class ListWidget(Element,WidgetElement):
3529 TAG=Element.WIDGET+'ListWidget'
3530 def __init__(self,elem,node = None,
3531 entryName = '',
3532 height = 0,
3533 width = 300,
3534 scale = 1.,
3535 divider = 150):
3536 super(ListWidget,self).__init__(elem,self.TAG,node=node,
3537 entryName = entryName,
3538 height = height,
3539 width = width,
3540 scale = scale,
3541 divider = divider)
3542
3543 registerElement(ListWidget)
3544
3545 # --------------------------------------------------------------------
3546 class PanelWidget(Element,WidgetElement):
3547 TAG=Element.WIDGET+'PanelWidget'
3548 def __init__(self,elem,node=None,
3549 entryName = '',
3550 fixed = False,
3551 nColumns = 1,
3552 vert = False):
3553 super(PanelWidget,self).__init__(elem,self.TAG,node=node,
3554 entryName = entryName,
3555 fixed = fixed,
3556 nColumns = nColumns,
3557 vert = vert)
3558
3559 registerElement(PanelWidget)
3560
3561 # --------------------------------------------------------------------
3562 class MapWidget(Element):
3563 TAG=Element.WIDGET+'MapWidget'
3564 def __init__(self,elem,node=None,entryName=''):
3565 super(MapWidget,self).__init__(elem,self.TAG,
3566 node = node,
3567 entryName = entryName)
3568
3569 def addWidgetMap(self,**kwargs):
3570 '''Add a `WidgetMap` element to this
3571
3572 Parameters
3573 ----------
3574 kwargs : dict
3575 Dictionary of attribute key-value pairs
3576
3577 Returns
3578 -------
3579 element : WidgetMap
3580 The added element
3581 '''
3582 return self.add(WidgetMap,**kwargs)
3583 def getWidgetMaps(self,asdict=True):
3584 '''Get all WidgetMap element(s) from this
3585
3586 Parameters
3587 ----------
3588 asdict : bool
3589 If `True`, return a dictonary that maps key to `WidgetMap` elements. If `False`, return a list of all WidgetMap` children.
3590
3591 Returns
3592 -------
3593 children : dict or list
3594 Dictionary or list of `WidgetMap` children
3595 '''
3596 return self.getElementsByKey(WidgetMap,'mapName',asdict=asdict)
3597
3598 registerElement(MapWidget)
3599
3600 #
3601 # EOF
3602 #
3603 # ====================================================================
3604 # From grid.py
3605
3606 # --------------------------------------------------------------------
3607 HEX_WIDTH = 88.50779626676963
3608 HEX_HEIGHT = 102.2
3609 RECT_WIDTH = 80
3610 RECT_HEIGHT = 80
3611 # --------------------------------------------------------------------
3612 class BaseGrid(Element):
3613 def __init__(self,zone,tag,node=None,
3614 color = rgb(0,0,0),
3615 cornersLegal = False,
3616 dotsVisible = False,
3617 dx = HEX_WIDTH, # Meaning seems reversed!
3618 dy = HEX_HEIGHT,
3619 edgesLegal = False,
3620 sideways = False,
3621 snapTo = True,
3622 visible = True,
3623 x0 = 0,
3624 y0 = 32):
3625 super(BaseGrid,self).__init__(zone,tag,node=node,
3626 color = color,
3627 cornersLegal = cornersLegal,
3628 dotsVisible = dotsVisible,
3629 dx = dx,
3630 dy = dy,
3631 edgesLegal = edgesLegal,
3632 sideways = sideways,
3633 snapTo = snapTo,
3634 visible = visible,
3635 x0 = x0,
3636 y0 = y0)
3637 def getZone(self):
3638 z = self.getParent(Zone)
3639 return z
3640 def getZonedGrid(self):
3641 z = self.getZone()
3642 if z is not None:
3643 return z.getZonedGrid()
3644 return None
3645 def getBoard(self):
3646 z = self.getZonedGrid()
3647 if z is not None:
3648 return z.getBoard()
3649 return self.getParent(Board)
3650 def getPicker(self):
3651 z = self.getBoard()
3652 if z is not None:
3653 return z.getPicker()
3654 return None
3655 def getMap(self):
3656 b = self.getPicker()
3657 if b is not None:
3658 return b.getMap()
3659 return None
3660 def getNumbering(self):
3661 pass
3662 def getLocation(self,loc):
3663 numbering = self.getNumbering()
3664 if numbering is None or len(numbering) < 1:
3665 return None
3666
3667 return numbering[0].getLocation(loc)
3668
3669 # --------------------------------------------------------------------
3670 class BaseNumbering(Element):
3671 def __init__(self,grid,tag,node=None,
3672 color = rgb(255,0,0),
3673 first = 'H',
3674 fontSize = 24,
3675 hDescend = False,
3676 hDrawOff = 0,
3677 hLeading = 1,
3678 hOff = 0,
3679 hType = 'A',
3680 locationFormat = '$gridLocation$',
3681 rotateText = 0,
3682 sep = '',
3683 stagger = True,
3684 vDescend = False,
3685 vDrawOff = 32,
3686 vLeading = 0,
3687 vOff = 0,
3688 vType = 'N',
3689 visible = True):
3690 super(BaseNumbering,self).__init__(grid,tag,node=node,
3691 color = color,
3692 first = first,
3693 fontSize = fontSize,
3694 hDescend = hDescend,
3695 hDrawOff = hDrawOff,
3696 hLeading = hLeading,
3697 hOff = hOff,
3698 hType = hType,
3699 locationFormat = locationFormat,
3700 rotateText = rotateText,
3701 sep = sep,
3702 stagger = stagger,
3703 vDescend = vDescend,
3704 vDrawOff = vDrawOff,
3705 vLeading = vLeading,
3706 vOff = vOff,
3707 vType = vType,
3708 visible = visible)
3709 def getGrid(self): return getParent(BaseGrid)
3710
3711 def _getMatcher(self,tpe,leading):
3712 if tpe == 'A':
3713 return \
3714 '-?(?:A+|B+|C+|D+|E+|F+|G+|H+|I+|' + \
3715 'J+|K+|L+|M+|N+|O+|P+|Q+|R+|S+|T+|' + \
3716 'U+|V+|W+|X+|Y+|Z+)'
3717
3718 return f'-?[0-9]{{{int(leading)+1},}}'
3719
3720 def _getIndex(self,name,tpe):
3721 if tpe == 'A':
3722 negative = name.startswith('-')
3723 if negative:
3724 name = name[1:]
3725
3726 value = 0
3727 for num,let in enumerate(name):
3728 if not let.isupper():
3729 continue
3730 if num < len(name) - 1:
3731 value += 26
3732 else:
3733 value += ord(let)-ord('A')
3734
3735 if negative:
3736 value *= -1
3737
3738 return value
3739
3740 return int(name)
3741
3742 def _getCenter(self,col,row):
3743 '''Convert col and row index to picture coordinates'''
3744 print('Dummy GetCenter')
3745 pass
3746
3747 def getLocation(self,loc):
3748 '''Get picture coordinates from grid location'''
3749 from re import match
3750
3751 first = self['first']
3752 vType = self['vType']
3753 hType = self['hType']
3754 vOff = int(self['vOff'])
3755 hOff = int(self['hOff'])
3756 colPat = self._getMatcher(hType,self['hLeading'])
3757 rowPat = self._getMatcher(vType,self['vLeading'])
3758 patts = ((colPat,rowPat) if first == 'H' else (rowPat,colPat))
3759 colGrp = 1 if first == 'H' else 2
3760 rowGrp = 2 if first == 'H' else 1
3761 patt = ''.join([f'({p})' for p in patts])
3762 matched = match(patt,loc)
3763 if not matched:
3764 return None
3765
3766 rowStr = matched[rowGrp]
3767 colStr = matched[colGrp]
3768 rowNum = self._getIndex(rowStr,vType)
3769 colNum = self._getIndex(colStr,hType)
3770
3771 return self._getCenter(colNum-hOff, rowNum-vOff);
3772
3773
3774 # --------------------------------------------------------------------
3775 class HexGrid(BaseGrid):
3776 TAG = Element.BOARD+'HexGrid'
3777 def __init__(self,zone,node=None,**kwargs):
3778 super(HexGrid,self).__init__(zone,self.TAG,node=node,**kwargs)
3779
3780 def addNumbering(self,**kwargs):
3781 '''Add a `Numbering` element to this
3782
3783 Parameters
3784 ----------
3785 kwargs : dict
3786 Dictionary of attribute key-value pairs
3787
3788 Returns
3789 -------
3790 element : Numbering
3791 The added element
3792 '''
3793 return self.add(HexNumbering,**kwargs)
3794 def getNumbering(self):
3795 return self.getAllElements(HexNumbering)
3796 def getDeltaX(self):
3797 return float(self['dx'])
3798 def getDeltaY(self):
3799 return float(self['dy'])
3800 def getXOffset(self):
3801 return int(self['x0'])
3802 def getYOffset(self):
3803 return int(self['y0'])
3804 def getMaxRows(self):
3805 from math import floor
3806 height = self.getZone().getHeight()
3807 return floor(height / self.getDeltaX() + .5)
3808 def getMaxCols(self):
3809 from math import floor
3810 width = self.getZone().getWidth()
3811 return floor(width / self.getDeltaY() + .5)
3812
3813 registerElement(HexGrid)
3814
3815 # --------------------------------------------------------------------
3816 class SquareGrid(BaseGrid):
3817 TAG = Element.BOARD+'SquareGrid'
3818 def __init__(self,zone,node=None,
3819 dx = RECT_WIDTH,
3820 dy = RECT_HEIGHT,
3821 edgesLegal = False,
3822 x0 = 0,
3823 y0 = int(0.4*RECT_HEIGHT),
3824 **kwargs):
3825 super(SquareGrid,self).__init__(zone,self.TAG,node=node,
3826 dx = dx,
3827 dy = dy,
3828 edgesLegal = edgesLegal,
3829 x0 = x0,
3830 y0 = y0,
3831 **kwargs)
3832 def addNumbering(self,**kwargs):
3833 '''Add a `Numbering` element to this
3834
3835 Parameters
3836 ----------
3837 kwargs : dict
3838 Dictionary of attribute key-value pairs
3839
3840 Returns
3841 -------
3842 element : Numbering
3843 The added element
3844 '''
3845 return self.add(SquareNumbering,**kwargs)
3846 def getNumbering(self):
3847 return self.getAllElements(SquareNumbering)
3848 def getDeltaX(self):
3849 return float(self['dx'])
3850 def getDeltaY(self):
3851 return float(self['dy'])
3852 def getXOffset(self):
3853 return int(self['x0'])
3854 def getYOffset(self):
3855 return int(self['y0'])
3856 def getMaxRows(self):
3857 from math import floor
3858 height = self.getZone().getHeight()
3859 return floor(height / self.getDeltaY() + .5)
3860 def getMaxCols(self):
3861 from math import floor
3862 width = self.getZone().getWidth()
3863 return floor(width / self.getDeltaX() + .5)
3864
3865 registerElement(SquareGrid)
3866
3867 # --------------------------------------------------------------------
3868 class HexNumbering(BaseNumbering):
3869 TAG = Element.BOARD+'mapgrid.HexGridNumbering'
3870 def __init__(self,grid,node=None,**kwargs):
3871 super(HexNumbering,self).__init__(grid,self.TAG,node=node,**kwargs)
3872 def getGrid(self):
3873 g = self.getParent(HexGrid)
3874 return g
3875
3876 def _getCenter(self,col,row):
3877 '''Convert col and row index to picture coordinates'''
3878 from math import floor
3879
3880 stagger = self['stagger'] == 'true'
3881 sideways = self.getGrid()['sideways'] == 'true'
3882 hDesc = self['hDescend'] == 'true'
3883 vDesc = self['vDescend'] == 'true'
3884 xOff = self.getGrid().getXOffset()
3885 yOff = self.getGrid().getYOffset()
3886 hexW = self.getGrid().getDeltaX()
3887 hexH = self.getGrid().getDeltaY()
3888 zxOff = self.getGrid().getZone().getXOffset()
3889 zyOff = self.getGrid().getZone().getYOffset()
3890 maxRows = self.getGrid().getMaxRows()
3891 maxCols = self.getGrid().getMaxCols()
3892 # print(f' Col: {col}')
3893 # print(f' Row: {row}')
3894 # print(f' Stagger: {stagger}')
3895 # print(f' Sideways: {sideways}')
3896 # print(f' hDesc: {hDesc}')
3897 # print(f' vDesc: {vDesc}')
3898 # print(f' maxRows: {maxRows}')
3899 # print(f' maxCols: {maxCols}')
3900
3901 if sideways:
3902 maxRows, maxCols = maxCols, maxRows
3903
3904 if stagger:
3905 if sideways:
3906 if col % 2 != 0:
3907 row += 1 if hDesc else -1
3908 else:
3909 if col % 2 != 0:
3910 row += 1 if vDesc else -1
3911
3912 if hDesc:
3913 col = maxCols - col
3914 if vDesc:
3915 row = maxRows - row
3916
3917 x = col * hexW + xOff
3918 y = row * hexH + yOff + (hexH/2 if col % 2 != 0 else 0)
3919
3920 x = int(floor(x + .5))
3921 y = int(floor(y + .5))
3922 if sideways:
3923 # print(f'Swap coordinates because {sideways}')
3924 x, y = y, x
3925
3926 return x,y
3927
3928 registerElement(HexNumbering)
3929
3930 # --------------------------------------------------------------------
3931 class SquareNumbering(BaseNumbering):
3932 TAG = Element.BOARD+'mapgrid.SquareGridNumbering'
3933 def __init__(self,grid,node=None,hType='N',**kwargs):
3934 super(SquareNumbering,self).__init__(grid,self.TAG,node=node,
3935 hType=hType,**kwargs)
3936 def getGrid(self):
3937 return self.getParent(SquareGrid)
3938
3939 def getCenter(self,col,row):
3940 hDesc = self['hDescend'] == 'true'
3941 vDesc = self['vDescend'] == 'true'
3942 xOff = self.getGrid().getXOffset()
3943 yOff = self.getGrid().getYOffset()
3944 squareW = self.getGrid().getDeltaX()
3945 squareH = self.getGrid().getDeltaY()
3946 maxRows = self.getGrid().getMaxRows()
3947 maxCols = self.getGrid().getMaxCols()
3948
3949 if vDesc: row = maxRows - row
3950 if hDesc: col = maxCols - col
3951
3952 x = col * squareW + xOff
3953 y = row * squareH + yOff
3954
3955 return x,y
3956
3957 registerElement(SquareNumbering)
3958
3959 # --------------------------------------------------------------------
3960 class RegionGrid(Element):
3961 TAG = Element.BOARD+'RegionGrid'
3962 def __init__(self,zone,node=None,snapto=True,fontsize=9,visible=True):
3963 super(RegionGrid,self).__init__(zone,self.TAG,node=node,
3964 snapto = snapto,
3965 fontsize = fontsize,
3966 visible = visible)
3967
3968 def getZone(self):
3969 return self.getParent(Zone)
3970 def getZoneGrid(self):
3971 z = self.getZone()
3972 if z is not None:
3973 return z.getBoard()
3974 return None
3975 def getBoard(self):
3976 z = self.getZonedGrid()
3977 if z is not None:
3978 return z.getBoard()
3979 return self.getParent(Board)
3980 def getMap(self):
3981 b = self.getBoard()
3982 if b is not None:
3983 return b.getMap()
3984 return None
3985 def getRegions(self):
3986 return self.getElementsByKey(Region,'name')
3987 def checkName(self,name):
3988 '''Get unique name'''
3989 poss = len([e for e in self.getRegions()
3990 if e == name or e.startswith(name+'_')])
3991 if poss == 0:
3992 return name
3993
3994 return name + f'_{poss}'
3995 def addRegion(self,**kwargs):
3996 '''Add a `Region` element to this
3997
3998 Parameters
3999 ----------
4000 kwargs : dict
4001 Dictionary of attribute key-value pairs
4002
4003 Returns
4004 -------
4005 element : Region
4006 The added element
4007 '''
4008 return self.add(Region,**kwargs)
4009 def getLocation(self,loc):
4010 for r in self.getRegions().values():
4011 if loc == r['name']:
4012 return int(r['originx']),int(r['originy'])
4013
4014 return None
4015
4016 registerElement(RegionGrid)
4017
4018 # --------------------------------------------------------------------
4019 class Region(Element):
4020 TAG = Element.BOARD+'Region'
4021 def __init__(self,grid,node=None,
4022 name = '',
4023 originx = 0,
4024 originy = 0,
4025 alsoPiece = True,
4026 piece = None,
4027 prefix = ''):
4028 fullName = name + ("@"+prefix if len(prefix) else "")
4029 realName = grid.checkName(fullName) if node is None else fullName
4030 super(Region,self).__init__(grid,
4031 self.TAG,
4032 node = node,
4033 name = realName,
4034 originx = originx,
4035 originy = originy)
4036
4037 if node is None and alsoPiece:
4038 m = self.getMap()
4039 b = self.getBoard()
4040 if m is not None and b is not None:
4041 if piece is None:
4042 g = m.getGame()
4043 pieces = g.getSpecificPieces(name,asdict=False)
4044 piece = pieces[0] if len(pieces) > 0 else None
4045
4046 if piece is not None:
4047 # bname = m['mapName']
4048 bname = b['name']
4049 #print(f'Adding at-start name={name} location={realName} '
4050 # f'owning board={bname}')
4051 a = m.addAtStart(name = name,
4052 location = realName,
4053 useGridLocation = True,
4054 owningBoard = bname,
4055 x = 0,
4056 y = 0)
4057 p = a.addPiece(piece)
4058 if p is None:
4059 print(f'EEE Failed to add piece {name} ({piece}) to add-start {a}')
4060 #if p is not None:
4061 # print(f'Added piece {name} in region')
4062 #else:
4063 # print(f'Could not find piece {name}')
4064
4065 def getGrid(self):
4066 return self.getParent(RegionGrid)
4067 def getZone(self):
4068 g = self.getGrid()
4069 if g is not None:
4070 return g.getZone()
4071 return None
4072 def getZonedGrid(self):
4073 z = self.getZone()
4074 if z is not None:
4075 return z.getZonedGrid()
4076 return None
4077 def getBoard(self):
4078 z = self.getZonedGrid()
4079 if z is not None:
4080 return z.getBoard()
4081 return self.getParent(Board)
4082 def getPicker(self):
4083 z = self.getBoard()
4084 if z is not None:
4085 return z.getPicker()
4086 return None
4087 def getMap(self):
4088 b = self.getPicker()
4089 if b is not None:
4090 return b.getMap()
4091 return None
4092
4093 registerElement(Region)
4094
4095 #
4096 # EOF
4097 #
4098 # ====================================================================
4099 # From zone.py
4100
4101 # --------------------------------------------------------------------
4102 class ZonedGrid(Element):
4103 TAG=Element.BOARD+'ZonedGrid'
4104 def __init__(self,board,node=None):
4105 super(ZonedGrid,self).__init__(board,self.TAG,node=node)
4106
4107 def getBoard(self):
4108 b = self.getParent(Board)
4109 # print(f'Get Board of Zoned: {b}')
4110 return b
4111 def getPicker(self):
4112 z = self.getBoard()
4113 if z is not None:
4114 return z.getPicker()
4115 return None
4116 def getMap(self):
4117 z = self.getPicker()
4118 if z is not None:
4119 return z.getMap()
4120 return None
4121 def addHighlighter(self,**kwargs):
4122 '''Add a `Highlighter` element to this
4123
4124 Parameters
4125 ----------
4126 kwargs : dict
4127 Dictionary of attribute key-value pairs
4128
4129 Returns
4130 -------
4131 element : Highlighter
4132 The added element
4133 '''
4134 return self.add(ZonedGridHighlighter,**kwargs)
4135 def getHighlighters(self,single=True):
4136 '''Get all or a sole `ZonedGridHighlighter` element(s) from this
4137
4138 Parameters
4139 ----------
4140 single : bool
4141 If `True`, there can be only one `Highligter` child, otherwise fail.
4142 If `False` return all `Highligter` children in this element
4143
4144 Returns
4145 -------
4146 children : list
4147 List of `Highligter` children (even if `single=True`)
4148 '''
4149 return self.getAllElements(ZonedGridHighlighter,single=single)
4150 def addZone(self,**kwargs):
4151 '''Add a `Zone` element to this
4152
4153 Parameters
4154 ----------
4155 kwargs : dict
4156 Dictionary of attribute key-value pairs
4157
4158 Returns
4159 -------
4160 element : Zone
4161 The added element
4162 '''
4163 return self.add(Zone,**kwargs)
4164 def getZones(self,asdict=True):
4165 '''Get all Zone element(s) from this
4166
4167 Parameters
4168 ----------
4169 asdict : bool
4170 If `True`, return a dictonary that maps key to `Zone` elements. If `False`, return a list of all Zone` children.
4171
4172 Returns
4173 -------
4174 children : dict or list
4175 Dictionary or list of `Zone` children
4176 '''
4177 return self.getElementsByKey(Zone,'name',asdict=asdict)
4178
4179 registerElement(ZonedGrid)
4180
4181 # --------------------------------------------------------------------
4182 class ZonedGridHighlighter(Element):
4183 TAG=Element.BOARD+'mapgrid.ZonedGridHighlighter'
4184 def __init__(self,zoned,node=None):
4185 super(ZonedGridHighlighter,self).__init__(zoned,self.TAG,node=node)
4186 def getZonedGrid(self): return self.getParent(ZonedGrid)
4187
4188 def addZoneHighlight(self,**kwargs):
4189 '''Add a `ZoneHighlight` element to this
4190
4191 Parameters
4192 ----------
4193 kwargs : dict
4194 Dictionary of attribute key-value pairs
4195
4196 Returns
4197 -------
4198 element : ZoneHighlight
4199 The added element
4200 '''
4201 return self.add(ZoneHighlight,**kwargs)
4202 def getZoneHighlights(self,asdict=True):
4203 '''Get all ZoneHighlight element(s) from this
4204
4205 Parameters
4206 ----------
4207 asdict : bool
4208 If `True`, return a dictonary that maps key to `Zone` elements. If `False`, return a list of all Zone` children.
4209
4210 Returns
4211 -------
4212 children : dict or list
4213 Dictionary or list of `Zone` children
4214 '''
4215 return self.getElementsByKey(ZoneHighlight,'name',asdict=asdict)
4216
4217 registerElement(ZonedGridHighlighter)
4218
4219 # --------------------------------------------------------------------
4220 class ZoneHighlight(Element):
4221 TAG=Element.BOARD+'mapgrid.ZoneHighlight'
4222 FULL='Entire Zone',
4223 BORDER='Zone Border',
4224 PLAIN='Plain',
4225 STRIPED='Striped'
4226 CROSS='Crosshatched',
4227 TILES='Tiled Image'
4228 def __init__(self,
4229 highlighters,
4230 node = None,
4231 name = '',
4232 color = rgb(255,0,0),
4233 coverage = FULL,
4234 width = 1,
4235 style = PLAIN,
4236 image = '',
4237 opacity = 50):
4238 super(ZoneHighlight,self).__init__(highlighters,
4239 self.TAG,
4240 node = node,
4241 name = name,
4242 color = color,
4243 coverage = coverage,
4244 width = width,
4245 style = style,
4246 image = image,
4247 opacity = int(opacity))
4248 def getZonedGridHighlighter(self):
4249 return self.getParent(ZonedGridHighlighter)
4250
4251
4252 registerElement(ZoneHighlight)
4253
4254
4255 # --------------------------------------------------------------------
4256 class ZoneProperty(Element):
4257 TAG = Element.MODULE+'properties.ZoneProperty'
4258 def __init__(self,zone,node=None,
4259 name = '',
4260 initialValue = '',
4261 isNumeric = False,
4262 min = "null",
4263 max = "null",
4264 wrap = False,
4265 description = ""):
4266 super(ZoneProperty,self).__init__(zone,self.TAG,
4267 node = node,
4268 name = name,
4269 initialValue = initialValue,
4270 isNumeric = isNumeric,
4271 min = min,
4272 max = max,
4273 wrap = wrap,
4274 description = description)
4275
4276 def getZone(self):
4277 return self.getParent(Zone)
4278
4279 registerElement(ZoneProperty)
4280
4281 # --------------------------------------------------------------------
4282 class Zone(Element):
4283 TAG = Element.BOARD+'mapgrid.Zone'
4284 def __init__(self,zoned,node=None,
4285 name = "",
4286 highlightProperty = "",
4287 locationFormat = "$gridLocation$",
4288 path = "0,0;976,0;976,976;0,976",
4289 useHighlight = False,
4290 useParentGrid = False):
4291 super(Zone,self).\
4292 __init__(zoned,self.TAG,node=node,
4293 name = name,
4294 highlightProperty = highlightProperty,
4295 locationFormat = locationFormat,
4296 path = path,
4297 useHighlight = useHighlight,
4298 useParentGrid = useParentGrid)
4299
4300 def getZonedGrid(self):
4301 z = self.getParent(ZonedGrid)
4302 # print(f'Get Zoned of Zone {self["name"]}: {z}')
4303 return z
4304
4305 def getBoard(self):
4306 z = self.getZonedGrid()
4307 if z is not None:
4308 return z.getBoard()
4309 return None
4310 def getPicker(self):
4311 z = self.getBoard()
4312 if z is not None:
4313 return z.getPicker()
4314 return None
4315 def getMap(self):
4316 z = self.getPicker()
4317 if z is not None:
4318 return z.getMap()
4319 return None
4320 def addHexGrid(self,**kwargs):
4321 '''Add a `HexGrid` element to this
4322
4323 Parameters
4324 ----------
4325 kwargs : dict
4326 Dictionary of attribute key-value pairs
4327
4328 Returns
4329 -------
4330 element : HexGrid
4331 The added element
4332 '''
4333 return self.add(HexGrid,**kwargs)
4334 def addSquareGrid(self,**kwargs):
4335 '''Add a `SquareGrid` element to this
4336
4337 Parameters
4338 ----------
4339 kwargs : dict
4340 Dictionary of attribute key-value pairs
4341
4342 Returns
4343 -------
4344 element : SquareGrid
4345 The added element
4346 '''
4347 return self.add(SquareGrid,**kwargs)
4348 def addRegionGrid(self,**kwargs):
4349 '''Add a `RegionGrid` element to this
4350
4351 Parameters
4352 ----------
4353 kwargs : dict
4354 Dictionary of attribute key-value pairs
4355
4356 Returns
4357 -------
4358 element : RegionGrid
4359 The added element
4360 '''
4361 return self.add(RegionGrid,**kwargs)
4362 def addProperty(self,**kwargs):
4363 '''Add a `Property` element to this
4364
4365 Parameters
4366 ----------
4367 kwargs : dict
4368 Dictionary of attribute key-value pairs
4369
4370 Returns
4371 -------
4372 element : Property
4373 The added element
4374 '''
4375 return self.add(ZoneProperty,**kwargs)
4376 def getHexGrids(self,single=True):
4377 '''Get all or a sole `HexGrid` element(s) from this
4378
4379 Parameters
4380 ----------
4381 single : bool
4382 If `True`, there can be only one `HexGrid` child, otherwise fail.
4383 If `False` return all `HexGrid` children in this element
4384
4385 Returns
4386 -------
4387 children : list
4388 List of `HexGrid` children (even if `single=True`)
4389 '''
4390 return self.getAllElements(HexGrid,single=single)
4391 def getSquareGrids(self,single=True):
4392 '''Get all or a sole `SquareGrid` element(s) from this
4393
4394 Parameters
4395 ----------
4396 single : bool
4397 If `True`, there can be only one `SquareGrid` child, otherwise fail.
4398 If `False` return all `SquareGrid` children in this element
4399
4400 Returns
4401 -------
4402 children : list
4403 List of `SquareGrid` children (even if `single=True`)
4404 '''
4405 return self.getAllElements(SquareGrid,single=single)
4406 def getRegionGrids(self,single=True):
4407 '''Get all or a sole `RegionGrid` element(s) from this
4408
4409 Parameters
4410 ----------
4411 single : bool
4412 If `True`, there can be only one `RegionGrid` child, otherwise fail.
4413 If `False` return all `RegionGrid` children in this element
4414
4415 Returns
4416 -------
4417 children : list
4418 List of `RegionGrid` children (even if `single=True`)
4419 '''
4420 return self.getAllElements(RegionGrid,single=single)
4421 def getGrids(self,single=True):
4422 '''Get all or a sole `Grid` element(s) from this
4423
4424 Parameters
4425 ----------
4426 single : bool
4427 If `True`, there can be only one `Grid` child, otherwise fail.
4428 If `False` return all `Grid` children in this element
4429
4430 Returns
4431 -------
4432 children : list
4433 List of `Grid` children (even if `single=True`)
4434 '''
4435 g = self.getHexGrids(single=single)
4436 if g is not None: return g
4437
4438 g = self.getSquareGrids(single=single)
4439 if g is not None: return g
4440
4441 g = self.getRegionGrids(single=single)
4442 if g is not None: return g
4443
4444 return g
4445 def getProperties(self):
4446 '''Get all `Property` element from this
4447
4448 Returns
4449 -------
4450 children : dict
4451 dict of `Property` children
4452 '''
4453 return getElementsByKey(ZoneProperty,'name')
4454
4455 def getPath(self):
4456 p = self['path'].split(';')
4457 r = []
4458 for pp in p:
4459 c = pp.split(',')
4460 r.append([int(c[0]),int(c[1])])
4461 return r
4462
4463 def getBB(self):
4464 from functools import reduce
4465 path = self.getPath()
4466 llx = reduce(lambda old,point:min(point[0],old),path,100000000000)
4467 lly = reduce(lambda old,point:min(point[1],old),path,100000000000)
4468 urx = reduce(lambda old,point:max(point[0],old),path,-1)
4469 ury = reduce(lambda old,point:max(point[1],old),path,-1)
4470 return llx,lly,urx,ury
4471 def getWidth(self):
4472 llx,_,urx,_ = self.getBB()
4473 return urx-llx
4474 def getHeight(self):
4475 _,lly,_,ury = self.getBB()
4476 return ury-lly
4477 def getXOffset(self):
4478 return self.getBB()[0]
4479 def getYOffset(self):
4480 return self.getBB()[1]
4481
4482 registerElement(Zone)
4483
4484 #
4485 # EOF
4486 #
4487 # ====================================================================
4488 # From board.py
4489
4490 # --------------------------------------------------------------------
4491 class BoardPicker(MapElement):
4492 TAG = Element.MAP+'BoardPicker'
4493 def __init__(self,doc,node=None,
4494 addColumnText = 'Add column',
4495 addRowText = 'Add row',
4496 boardPrompt = 'Select board',
4497 slotHeight = 125,
4498 slotScale = 0.2,
4499 slotWidth = 350,
4500 title = 'Choose Boards'):
4501 super(BoardPicker,self).__init__(doc,self.TAG,node=node,
4502 addColumnText = addColumnText,
4503 addRowText = addRowText,
4504 boardPrompt = boardPrompt,
4505 slotHeight = slotHeight,
4506 slotScale = slotScale,
4507 slotWidth = slotWidth,
4508 title = title)
4509
4510 def addSetup(self,**kwargs):
4511 '''Add a `Setup` element to this
4512
4513 Parameters
4514 ----------
4515 kwargs : dict
4516 Dictionary of attribute key-value pairs
4517
4518 Returns
4519 -------
4520 element : Setup
4521 The added element
4522 '''
4523 if 'mapName' not in kwargs:
4524 m = self.getMap()
4525 kwargs['mapName'] = m.getAttribute('mapName')
4526
4527 return self.add(Setup,**kwargs)
4528 def getSetups(self,single=False):
4529 '''Get all or a sole `Setup` element(s) from this
4530
4531 Parameters
4532 ----------
4533 single : bool
4534 If `True`, there can be only one `Setup` child, otherwise fail.
4535 If `False` return all `Setup` children in this element
4536
4537 Returns
4538 -------
4539 children : list
4540 List of `Setup` children (even if `single=True`)
4541 '''
4542 return self.getAllElements(Setup,single=single)
4543 def addBoard(self,**kwargs):
4544 '''Add a `Board` element to this
4545
4546 Parameters
4547 ----------
4548 kwargs : dict
4549 Dictionary of attribute key-value pairs
4550
4551 Returns
4552 -------
4553 element : Board
4554 The added element
4555 '''
4556 return self.add(Board,**kwargs)
4557 def getBoards(self,asdict=True):
4558 '''Get all Board element(s) from this
4559
4560 Parameters
4561 ----------
4562 asdict : bool
4563 If `True`, return a dictonary that maps key to `Board` elements. If `False`, return a list of all Board` children.
4564
4565 Returns
4566 -------
4567 children : dict or list
4568 Dictionary or list of `Board` children
4569 '''
4570 return self.getElementsByKey(Board,'name',asdict=asdict)
4571 def encode(self):
4572 setups = self.getSetups()
4573 if setups is not None and len(setups)>0:
4574 return [setups[0]._node.childNodes[0].nodeValue]
4575
4576 ret = []
4577 for bn in self.getBoards().keys():
4578 ret.append(bn+'BoardPicker\t'+bn+'\t0\t0')
4579
4580 return ret
4581
4582 registerElement(BoardPicker)
4583
4584 # --------------------------------------------------------------------
4585 class Setup(Element):
4586 TAG = 'setup'
4587 def __init__(self,picker,node=None,
4588 mapName = '',
4589 maxColumns = 1,
4590 boardNames = []):
4591 super(Setup,self).__init__(picker,self.TAG,node=node)
4592 col = 0
4593 row = 0
4594 lst = [f'{mapName}BoardPicker']
4595 for bn in boardNames:
4596 lst.extend([bn,str(col),str(row)])
4597 col += 1
4598 if col >= maxColumns:
4599 col = 0
4600 row += 1
4601
4602 txt = r' '.join(lst)
4603 self.addText(txt)
4604
4605 def getPicker(self): return self.getParent(BoardPicker)
4606
4607 registerElement(Setup)
4608
4609 # --------------------------------------------------------------------
4610 class Board(Element):
4611 TAG = Element.PICKER+'Board'
4612 def __init__(self,picker,node=None,
4613 name = '',
4614 image = '',
4615 reversible = False,
4616 color = rgb(255,255,255),
4617 width = 0,
4618 height = 0):
4619 super(Board,self).__init__(picker,self.TAG,node=node,
4620 image = image,
4621 name = name,
4622 reversible = reversible,
4623 color = color,
4624 width = width,
4625 height = height)
4626
4627 def getPicker(self): return self.getParent(BoardPicker)
4628 def getMap(self):
4629 z = self.getPicker()
4630 if z is not None:
4631 return z.getMap()
4632 return None
4633 def addZonedGrid(self,**kwargs):
4634 '''Add a `ZonedGrid` element to this
4635
4636 Parameters
4637 ----------
4638 kwargs : dict
4639 Dictionary of attribute key-value pairs
4640
4641 Returns
4642 -------
4643 element : ZonedGrid
4644 The added element
4645 '''
4646 return self.add(ZonedGrid,**kwargs)
4647 def getZonedGrids(self,single=True):
4648 '''Get all or a sole `ZonedGrid` element(s) from this
4649
4650 Parameters
4651 ----------
4652 single : bool
4653 If `True`, there can be only one `ZonedGrid` child, otherwise fail.
4654 If `False` return all `ZonedGrid` children in this element
4655
4656 Returns
4657 -------
4658 children : list
4659 List of `ZonedGrid` children (even if `single=True`)
4660 '''
4661 return self.getAllElements(ZonedGrid,single=single)
4662 def getZones(self,asdict=True):
4663 '''Get all Zone element(s) from this
4664
4665 Parameters
4666 ----------
4667 asdict : bool
4668 If `True`, return a dictonary that maps key to `Zone` elements. If `False`, return a list of all Zone` children.
4669
4670 Returns
4671 -------
4672 children : dict or list
4673 Dictionary or list of `Zone` children
4674 '''
4675 zoned = self.getZonedGrids(single=True)
4676 if zoned is None: return None
4677
4678 return zoned[0].getZones(asdict=asdict)
4679
4680 def getWidth(self):
4681 # print(f'Getting width of {self}: {self["width"]}')
4682 if 'width' in self and int(self['width']) != 0:
4683 return int(self['width'])
4684 return 0
4685
4686 def getHeight(self):
4687 # print(f'Getting height of {self}: {self["height"]}')
4688 if 'height' in self and int(self['height']) != 0:
4689 return int(self['height'])
4690 return 0
4691
4692 registerElement(Board)
4693
4694 #
4695 # EOF
4696 #
4697 # ====================================================================
4698 # From map.py
4699
4700 # --------------------------------------------------------------------
4701 class BaseMap(Element):
4702 def __init__(self,doc,tag,node=None,
4703 mapName = '',
4704 allowMultiple = 'false',
4705 backgroundcolor = rgb(255,255,255),
4706 buttonName = '',
4707 changeFormat = '$message$',
4708 color = rgb(0,0,0), # Selected pieces
4709 createFormat = '$pieceName$ created in $location$ *',
4710 edgeHeight = '0',
4711 edgeWidth = '0',
4712 hideKey = '',
4713 hotkey = key('M',ALT),
4714 icon = '/images/map.gif',
4715 launch = 'false',
4716 markMoved = 'Always',
4717 markUnmovedHotkey = '',
4718 markUnmovedIcon = '/images/unmoved.gif',
4719 markUnmovedReport = '',
4720 markUnmovedText = '',
4721 markUnmovedTooltip = 'Mark all pieces on this map as not moved',
4722 moveKey = '',
4723 moveToFormat = '$pieceName$ moves $previousLocation$ &rarr; $location$ *',
4724 moveWithinFormat = '$pieceName$ moves $previousLocation$ &rarr; $location$ *',
4725 showKey = '',
4726 thickness = '3'):
4727 '''Create a map
4728
4729 Parameters
4730 ----------
4731 doc : xml.minidom.Document
4732 Parent document
4733 tag : str
4734 XML tag
4735 node : xml.minidom.Node or None
4736 Existing node or None
4737 mapName : str
4738 Name of map
4739 allowMultiple : bool
4740 Allow multiple boards
4741 backgroundcolor : color
4742 Bckground color
4743 buttonName : str
4744 Name on button to show map = '',
4745 changeFormat :
4746 Message format to show on changes
4747 color : color
4748 Color of selected pieces
4749 createFormat : str
4750 Message format when creating a piece
4751 edgeHeight : int
4752 Height of edge (margin)
4753 edgeWidth : int
4754 Width of edge (margin)
4755 hideKey : Key
4756 Hot-key or key-command to hide map
4757 hotkey : Key
4758 Hot-key or key-command to show map
4759 icon : path
4760 Icon image
4761 launch : bool
4762 Show on launch
4763 markMoved : str
4764 Show moved
4765 markUnmovedHotkey : key
4766 Remove moved markers
4767 markUnmovedIcon : path
4768 Icon for unmoved
4769 markUnmovedReport : str
4770 Message when marking as unmoved
4771 markUnmovedText : str
4772 Text on button
4773 markUnmovedTooltip : str
4774 Tooltip on button
4775 moveKey : key
4776 Key to set moved marker
4777 moveToFormat : str
4778 Message format when moving
4779 moveWithinFormat : str
4780 Message when moving within map
4781 showKey : str,
4782 Key to show map
4783 thickness : int
4784 Thickness of line around selected pieces
4785 '''
4786 super(BaseMap,self).__init__(doc,tag,node=node,
4787 allowMultiple = allowMultiple,
4788 backgroundcolor = backgroundcolor,
4789 buttonName = buttonName,
4790 changeFormat = changeFormat,
4791 color = color,
4792 createFormat = createFormat,
4793 edgeHeight = edgeHeight,
4794 edgeWidth = edgeWidth,
4795 hideKey = hideKey,
4796 hotkey = hotkey,
4797 icon = icon,
4798 launch = launch,
4799 mapName = mapName,
4800 markMoved = markMoved,
4801 markUnmovedHotkey = markUnmovedHotkey,
4802 markUnmovedIcon = markUnmovedIcon,
4803 markUnmovedReport = markUnmovedReport,
4804 markUnmovedText = markUnmovedText,
4805 markUnmovedTooltip = markUnmovedTooltip,
4806 moveKey = moveKey,
4807 moveToFormat = moveToFormat,
4808 moveWithinFormat = moveWithinFormat,
4809 showKey = showKey,
4810 thickness = thickness)
4811
4812 def getGame(self):
4813 '''Get the game'''
4814 return self.getParentOfClass([Game])
4815 def addPicker(self,**kwargs):
4816 '''Add a `Picker` element to this
4817
4818 Parameters
4819 ----------
4820 kwargs : dict
4821 Dictionary of attribute key-value pairs
4822
4823 Returns
4824 -------
4825 element : Picker
4826 The added element
4827 '''
4828 return self.add(BoardPicker,**kwargs)
4829 def getBoardPicker(self,single=True):
4830 '''Get all or a sole `BoardPicker` element(s) from this
4831
4832 Parameters
4833 ----------
4834 single : bool
4835 If `True`, there can be only one `BoardPicker` child, otherwise fail.
4836 If `False` return all `BoardPicker` children in this element
4837
4838 Returns
4839 -------
4840 children : list
4841 List of `BoardPicker` children (even if `single=True`)
4842 '''
4843 return self.getAllElements(BoardPicker,single)
4844 def getPicker(self,single=True):
4845 '''Get all or a sole `BoardPicker` element(s) from this
4846
4847 Parameters
4848 ----------
4849 single : bool
4850 If `True`, there can be only one `BoardPicker` child, otherwise fail.
4851 If `False` return all `BoardPicker` children in this element
4852
4853 Returns
4854 -------
4855 children : list
4856 List of `BoardPicker` children (even if `single=True`)
4857 '''
4858 return self.getAllElements(BoardPicker,single)
4859 def getStackMetrics(self,single=True):
4860 '''Get all or a sole `StackMetric` element(s) from this
4861
4862 Parameters
4863 ----------
4864 single : bool
4865 If `True`, there can be only one `StackMetric` child, otherwise fail.
4866 If `False` return all `StackMetric` children in this element
4867
4868 Returns
4869 -------
4870 children : list
4871 List of `StackMetric` children (even if `single=True`)
4872 '''
4873 return self.getAllElements(StackMetrics,single)
4874 def getImageSaver(self,single=True):
4875 '''Get all or a sole `ImageSaver` element(s) from this
4876
4877 Parameters
4878 ----------
4879 single : bool
4880 If `True`, there can be only one `ImageSaver` child, otherwise fail.
4881 If `False` return all `ImageSaver` children in this element
4882
4883 Returns
4884 -------
4885 children : list
4886 List of `ImageSaver` children (even if `single=True`)
4887 '''
4888 return self.getAllElements(ImageSaver,single)
4889 def getTextSaver(self,single=True):
4890 '''Get all or a sole `TextSaver` element(s) from this
4891
4892 Parameters
4893 ----------
4894 single : bool
4895 If `True`, there can be only one `TextSaver` child, otherwise fail.
4896 If `False` return all `TextSaver` children in this element
4897
4898 Returns
4899 -------
4900 children : list
4901 List of `TextSaver` children (even if `single=True`)
4902 '''
4903 return self.getAllElements(TextSaver,single)
4904 def getForwardToChatter(self,single=True):
4905 '''Get all or a sole `ForwardToChatter` element(s) from this
4906
4907 Parameters
4908 ----------
4909 single : bool
4910 If `True`, there can be only one `ForwardToChatter` child, otherwise fail.
4911 If `False` return all `ForwardToChatter` children in this element
4912
4913 Returns
4914 -------
4915 children : list
4916 List of `ForwardToChatter` children (even if `single=True`)
4917 '''
4918 return self.getAllElements(ForwardToChatter,single)
4919 def getMenuDisplayer(self,single=True):
4920 '''Get all or a sole `MenuDi` element(s) from this
4921
4922 Parameters
4923 ----------
4924 single : bool
4925 If `True`, there can be only one `MenuDi` child, otherwise fail.
4926 If `False` return all `MenuDi` children in this element
4927
4928 Returns
4929 -------
4930 children : list
4931 List of `MenuDi` children (even if `single=True`)
4932 '''
4933 return self.getAllElements(MenuDisplayer,single)
4934 def getMapCenterer(self,single=True):
4935 '''Get all or a sole `MapCenterer` element(s) from this
4936
4937 Parameters
4938 ----------
4939 single : bool
4940 If `True`, there can be only one `MapCenterer` child, otherwise fail.
4941 If `False` return all `MapCenterer` children in this element
4942
4943 Returns
4944 -------
4945 children : list
4946 List of `MapCenterer` children (even if `single=True`)
4947 '''
4948 return self.getAllElements(MapCenterer,single)
4949 def getStackExpander(self,single=True):
4950 '''Get all or a sole `StackExpander` element(s) from this
4951
4952 Parameters
4953 ----------
4954 single : bool
4955 If `True`, there can be only one `StackExpander` child, otherwise fail.
4956 If `False` return all `StackExpander` children in this element
4957
4958 Returns
4959 -------
4960 children : list
4961 List of `StackExpander` children (even if `single=True`)
4962 '''
4963 return self.getAllElements(StackExpander,single)
4964 def getPieceMover(self,single=True):
4965 '''Get all or a sole `PieceMover` element(s) from this
4966
4967 Parameters
4968 ----------
4969 single : bool
4970 If `True`, there can be only one `PieceMover` child, otherwise fail.
4971 If `False` return all `PieceMover` children in this element
4972
4973 Returns
4974 -------
4975 children : list
4976 List of `PieceMover` children (even if `single=True`)
4977 '''
4978 return self.getAllElements(PieceMover,single)
4979 def getSelectionHighlighters(self,single=True):
4980 '''Get all or a sole `SelectionHighlighter` element(s) from this
4981
4982 Parameters
4983 ----------
4984 single : bool
4985 If `True`, there can be only one `SelectionHighlighter` child, otherwise fail.
4986 If `False` return all `SelectionHighlighter` children in this element
4987
4988 Returns
4989 -------
4990 children : list
4991 List of `SelectionHighlighter` children (even if `single=True`)
4992 '''
4993 return self.getAllElements(SelectionHighlighters,single)
4994 def getKeyBufferer(self,single=True):
4995 return self.getAllElements(KeyBufferer,single)
4996 def getHighlightLastMoved(self,single=True):
4997 '''Get all or a sole `HighlightLa` element(s) from this
4998
4999 Parameters
5000 ----------
5001 single : bool
5002 If `True`, there can be only one `HighlightLa` child, otherwise fail.
5003 If `False` return all `HighlightLa` children in this element
5004
5005 Returns
5006 -------
5007 children : list
5008 List of `HighlightLa` children (even if `single=True`)
5009 '''
5010 return self.getAllElements(HighlightLastMoved,single)
5011 def getCounterDetailViewer(self,single=True):
5012 '''Get all or a sole `CounterDetailViewer` element(s) from this
5013
5014 Parameters
5015 ----------
5016 single : bool
5017 If `True`, there can be only one `CounterDetailViewer` child, otherwise fail.
5018 If `False` return all `CounterDetailViewer` children in this element
5019
5020 Returns
5021 -------
5022 children : list
5023 List of `CounterDetailViewer` children (even if `single=True`)
5024 '''
5025 return self.getAllElements(CounterDetailViewer,single)
5026 def getGlobalMap(self,single=True):
5027 '''Get all or a sole `GlobalMap` element(s) from this
5028
5029 Parameters
5030 ----------
5031 single : bool
5032 If `True`, there can be only one `GlobalMap` child, otherwise fail.
5033 If `False` return all `GlobalMap` children in this element
5034
5035 Returns
5036 -------
5037 children : list
5038 List of `GlobalMap` children (even if `single=True`)
5039 '''
5040 return self.getAllElements(GlobalMap,single)
5041 def getZoomer(self,single=True):
5042 '''Get all or a sole `Zoomer` element(s) from this
5043
5044 Parameters
5045 ----------
5046 single : bool
5047 If `True`, there can be only one `Zoomer` child, otherwise fail.
5048 If `False` return all `Zoomer` children in this element
5049
5050 Returns
5051 -------
5052 children : list
5053 List of `Zoomer` children (even if `single=True`)
5054 '''
5055 return self.getAllElements(Zoomer,single)
5056 def getHidePiecesButton(self,single=True):
5057 '''Get all or a sole `HidePiece` element(s) from this
5058
5059 Parameters
5060 ----------
5061 single : bool
5062 If `True`, there can be only one `HidePiece` child, otherwise fail.
5063 If `False` return all `HidePiece` children in this element
5064
5065 Returns
5066 -------
5067 children : list
5068 List of `HidePiece` children (even if `single=True`)
5069 '''
5070 return self.getAllElements(HidePiecesButton,single)
5071 def getMassKeys(self,asdict=True):
5072 '''Get all MassKey element(s) from this
5073
5074 Parameters
5075 ----------
5076 asdict : bool
5077 If `True`, return a dictonary that maps key to `MassKey` elements. If `False`, return a list of all MassKey` children.
5078
5079 Returns
5080 -------
5081 children : dict or list
5082 Dictionary or list of `MassKey` children
5083 '''
5084 return self.getElementsByKey(MassKey,'name',asdict)
5085 def getFlare(self,single=True):
5086 '''Get all or a sole `Flare` element(s) from this
5087
5088 Parameters
5089 ----------
5090 single : bool
5091 If `True`, there can be only one `Flare` child, otherwise fail.
5092 If `False` return all `Flare` children in this element
5093
5094 Returns
5095 -------
5096 children : list
5097 List of `Flare` children (even if `single=True`)
5098 '''
5099 return self.getAllElements(Flare,single)
5100 def getAtStarts(self,single=True):
5101 '''Get all or a sole `AtStart` element(s) from this
5102
5103 Parameters
5104 ----------
5105 single : bool
5106 If `True`, there can be only one `AtStart` child, otherwise fail.
5107 If `False` return all `AtStart` children in this element
5108
5109 Returns
5110 -------
5111 children : list
5112 List of `AtStart` children (even if `single=True`)
5113 '''
5114 return self.getAllElements(AtStart,single)
5115 def getBoards(self,asdict=True):
5116 '''Get all Board element(s) from this
5117
5118 Parameters
5119 ----------
5120 asdict : bool
5121 If `True`, return a dictonary that maps key to `Board` elements. If `False`, return a list of all Board` children.
5122
5123 Returns
5124 -------
5125 children : dict or list
5126 Dictionary or list of `Board` children
5127 '''
5128 picker = self.getPicker()
5129 if picker is None: return None
5130 return picker[0].getBoards(asdict=asdict)
5131 def getLayers(self,asdict=True):
5132 '''Get all `PieceLayer` element(s) from this
5133
5134 Parameters
5135 ----------
5136 asdict : bool
5137 If `True`, return a dictonary that maps property name
5138 `PieceLayers` elements. If `False`, return a list of all
5139 `PieceLayers` children.
5140
5141 Returns
5142 -------
5143 children : dict or list
5144 Dictionary or list of `PieceLayers` children
5145
5146 '''
5147 return self.getElementsByKey(PieceLayers,'property',asdict)
5148 def getMenus(self,asdict=True):
5149 '''Get all Menu element(s) from this
5150
5151 Parameters
5152 ----------
5153 asdict : bool
5154 If `True`, return a dictonary that maps key to `Board`
5155 elements. If `False`, return a list of all Board`
5156 children.
5157
5158
5159 Returns
5160 -------
5161 children : dict or list
5162 Dictionary or list of `Board` children
5163
5164 '''
5165 return self.getElementsByKey(Menu,'name',asdict)
5166 def getLOSs(self,asdict=True):
5167 '''Get all Menu element(s) from this
5168
5169 Parameters
5170 ----------
5171 asdict : bool
5172 If `True`, return a dictonary that maps key to `Board`
5173 elements. If `False`, return a list of all Board`
5174 children.
5175
5176
5177 Returns
5178 -------
5179 children : dict or list
5180 Dictionary or list of `Board` children
5181
5182 '''
5183 return self.getElementsByKey(LineOfSight,'threadName',asdict)
5184 def addBoardPicker(self,**kwargs):
5185 '''Add a `BoardPicker` element to this
5186
5187 Parameters
5188 ----------
5189 kwargs : dict
5190 Dictionary of attribute key-value pairs
5191
5192 Returns
5193 -------
5194 element : BoardPicker
5195 The added element
5196 '''
5197 return self.add(BoardPicker,**kwargs)
5198 def addStackMetrics(self,**kwargs):
5199 '''Add a `StackMetrics` element to this
5200
5201 Parameters
5202 ----------
5203 kwargs : dict
5204 Dictionary of attribute key-value pairs
5205
5206 Returns
5207 -------
5208 element : StackMetrics
5209 The added element
5210 '''
5211 return self.add(StackMetrics,**kwargs)
5212 def addImageSaver(self,**kwargs):
5213 '''Add a `ImageSaver` element to this
5214
5215 Parameters
5216 ----------
5217 kwargs : dict
5218 Dictionary of attribute key-value pairs
5219
5220 Returns
5221 -------
5222 element : ImageSaver
5223 The added element
5224 '''
5225 return self.add(ImageSaver,**kwargs)
5226 def addTextSaver(self,**kwargs):
5227 '''Add a `TextSaver` element to this
5228
5229 Parameters
5230 ----------
5231 kwargs : dict
5232 Dictionary of attribute key-value pairs
5233
5234 Returns
5235 -------
5236 element : TextSaver
5237 The added element
5238 '''
5239 return self.add(TextSaver,**kwargs)
5240 def addForwardToChatter(self,**kwargs):
5241 '''Add a `ForwardToChatter` element to this
5242
5243 Parameters
5244 ----------
5245 kwargs : dict
5246 Dictionary of attribute key-value pairs
5247
5248 Returns
5249 -------
5250 element : ForwardToChatter
5251 The added element
5252 '''
5253 return self.add(ForwardToChatter,**kwargs)
5254 def addMenuDisplayer(self,**kwargs):
5255 '''Add a `MenuDisplayer` element to this
5256
5257 Parameters
5258 ----------
5259 kwargs : dict
5260 Dictionary of attribute key-value pairs
5261
5262 Returns
5263 -------
5264 element : MenuDisplayer
5265 The added element
5266 '''
5267 return self.add(MenuDisplayer,**kwargs)
5268 def addMapCenterer(self,**kwargs):
5269 '''Add a `MapCenterer` element to this
5270
5271 Parameters
5272 ----------
5273 kwargs : dict
5274 Dictionary of attribute key-value pairs
5275
5276 Returns
5277 -------
5278 element : MapCenterer
5279 The added element
5280 '''
5281 return self.add(MapCenterer,**kwargs)
5282 def addStackExpander(self,**kwargs):
5283 '''Add a `StackExpander` element to this
5284
5285 Parameters
5286 ----------
5287 kwargs : dict
5288 Dictionary of attribute key-value pairs
5289
5290 Returns
5291 -------
5292 element : StackExpander
5293 The added element
5294 '''
5295 return self.add(StackExpander,**kwargs)
5296 def addPieceMover(self,**kwargs):
5297 '''Add a `PieceMover` element to this
5298
5299 Parameters
5300 ----------
5301 kwargs : dict
5302 Dictionary of attribute key-value pairs
5303
5304 Returns
5305 -------
5306 element : PieceMover
5307 The added element
5308 '''
5309 return self.add(PieceMover,**kwargs)
5310 def addSelectionHighlighters(self,**kwargs):
5311 '''Add a `SelectionHighlighters` element to this
5312
5313 Parameters
5314 ----------
5315 kwargs : dict
5316 Dictionary of attribute key-value pairs
5317
5318 Returns
5319 -------
5320 element : SelectionHighlighters
5321 The added element
5322 '''
5323 return self.add(SelectionHighlighters,**kwargs)
5324 def addKeyBufferer(self,**kwargs):
5325 '''Add a `KeyBufferer` element to this
5326
5327 Parameters
5328 ----------
5329 kwargs : dict
5330 Dictionary of attribute key-value pairs
5331
5332 Returns
5333 -------
5334 element : KeyBufferer
5335 The added element
5336 '''
5337 return self.add(KeyBufferer,**kwargs)
5338 def addHighlightLastMoved(self,**kwargs):
5339 '''Add a `HighlightLastMoved` element to this
5340
5341 Parameters
5342 ----------
5343 kwargs : dict
5344 Dictionary of attribute key-value pairs
5345
5346 Returns
5347 -------
5348 element : HighlightLastMoved
5349 The added element
5350 '''
5351 return self.add(HighlightLastMoved,**kwargs)
5352 def addCounterDetailViewer(self,**kwargs):
5353 '''Add a `CounterDetailViewer` element to this
5354
5355 Parameters
5356 ----------
5357 kwargs : dict
5358 Dictionary of attribute key-value pairs
5359
5360 Returns
5361 -------
5362 element : CounterDetailViewer
5363 The added element
5364 '''
5365 return self.add(CounterDetailViewer,**kwargs)
5366 def addGlobalMap(self,**kwargs):
5367 '''Add a `GlobalMap` element to this
5368
5369 Parameters
5370 ----------
5371 kwargs : dict
5372 Dictionary of attribute key-value pairs
5373
5374 Returns
5375 -------
5376 element : GlobalMap
5377 The added element
5378 '''
5379 return self.add(GlobalMap,**kwargs)
5380 def addZoomer(self,**kwargs):
5381 '''Add a `Zoomer` element to this
5382
5383 Parameters
5384 ----------
5385 kwargs : dict
5386 Dictionary of attribute key-value pairs
5387
5388 Returns
5389 -------
5390 element : Zoomer
5391 The added element
5392 '''
5393 return self.add(Zoomer,**kwargs)
5394 def addHidePiecesButton(self,**kwargs):
5395 '''Add a `HidePiecesButton` element to this
5396
5397 Parameters
5398 ----------
5399 kwargs : dict
5400 Dictionary of attribute key-value pairs
5401
5402 Returns
5403 -------
5404 element : HidePiecesButton
5405 The added element
5406 '''
5407 return self.add(HidePiecesButton,**kwargs)
5408 def addMassKey(self,**kwargs):
5409 '''Add a `MassKey` element to this
5410
5411 Parameters
5412 ----------
5413 kwargs : dict
5414 Dictionary of attribute key-value pairs
5415
5416 Returns
5417 -------
5418 element : MassKey
5419 The added element
5420 '''
5421 return self.add(MassKey,**kwargs)
5422 def addStartupMassKey(self,**kwargs):
5423 '''Add a `StartupMassKey` element to this
5424
5425 Parameters
5426 ----------
5427 kwargs : dict
5428 Dictionary of attribute key-value pairs
5429
5430 Returns
5431 -------
5432 element : StartupMassKey
5433 The added element
5434 '''
5435 return self.add(MassKey,**kwargs)
5436 def addFlare(self,**kwargs):
5437 '''Add a `Flare` element to this
5438
5439 Parameters
5440 ----------
5441 kwargs : dict
5442 Dictionary of attribute key-value pairs
5443
5444 Returns
5445 -------
5446 element : Flare
5447 The added element
5448 '''
5449 return self.add(Flare,**kwargs)
5450 def addAtStart(self,**kwargs):
5451 '''Add a `AtStart` element to this
5452
5453 Parameters
5454 ----------
5455 kwargs : dict
5456 Dictionary of attribute key-value pairs
5457
5458 Returns
5459 -------
5460 element : AtStart
5461 The added element
5462 '''
5463 return self.add(AtStart,**kwargs)
5464
5465
5466 def addLayers(self,**kwargs):
5467 '''Add `PieceLayers` element to this
5468
5469 Parameters
5470 ----------
5471 kwargs : dict
5472 Dictionary of attribute key-value pairs
5473
5474 Returns
5475 -------
5476 element : PieceLayers
5477 The added element
5478 '''
5479 return self.add(PieceLayers,**kwargs)
5480 def addMenu(self,**kwargs):
5481 '''Add a `Menu` element to this
5482
5483 Parameters
5484 ----------
5485 kwargs : dict
5486 Dictionary of attribute key-value pairs
5487
5488 Returns
5489 -------
5490 element : Menu
5491 The added element
5492 '''
5493 return self.add(Menu,**kwargs)
5494 def addLOS(self,**kwargs):
5495 '''Add a `Menu` element to this
5496
5497 Parameters
5498 ----------
5499 kwargs : dict
5500 Dictionary of attribute key-value pairs
5501
5502 Returns
5503 -------
5504 element : Menu
5505 The added element
5506 '''
5507 return self.add(LineOfSight,**kwargs)
5508
5509 # --------------------------------------------------------------------
5510 class Map(BaseMap):
5511 TAG = Element.MODULE+'Map'
5512 def __init__(self,doc,node=None,
5513 mapName = '',
5514 allowMultiple = 'false',
5515 backgroundcolor = rgb(255,255,255),
5516 buttonName = '',
5517 changeFormat = '$message$',
5518 color = rgb(0,0,0),
5519 createFormat = '$pieceName$ created in $location$ *',
5520 edgeHeight = '0',
5521 edgeWidth = '0',
5522 hideKey = '',
5523 hotkey = key('M',ALT),
5524 icon = '/images/map.gif',
5525 launch = 'false',
5526 markMoved = 'Always',
5527 markUnmovedHotkey = '',
5528 markUnmovedIcon = '/images/unmoved.gif',
5529 markUnmovedReport = '',
5530 markUnmovedText = '',
5531 markUnmovedTooltip = 'Mark all pieces on this map as not moved',
5532 moveKey = '',
5533 moveToFormat = '$pieceName$ moves $previousLocation$ &rarr; $location$ *',
5534 moveWithinFormat = '$pieceName$ moves $previousLocation$ &rarr; $location$ *',
5535 showKey = '',
5536 thickness = '3'):
5537 super(Map,self).__init__(doc,self.TAG,node=node,
5538 allowMultiple = allowMultiple,
5539 backgroundcolor = backgroundcolor,
5540 buttonName = buttonName,
5541 changeFormat = changeFormat,
5542 color = color,
5543 createFormat = createFormat,
5544 edgeHeight = edgeHeight,
5545 edgeWidth = edgeWidth,
5546 hideKey = hideKey,
5547 hotkey = hotkey,
5548 icon = icon,
5549 launch = launch,
5550 mapName = mapName,
5551 markMoved = markMoved,
5552 markUnmovedHotkey = markUnmovedHotkey,
5553 markUnmovedIcon = markUnmovedIcon,
5554 markUnmovedReport = markUnmovedReport,
5555 markUnmovedText = markUnmovedText,
5556 markUnmovedTooltip = markUnmovedTooltip,
5557 moveKey = moveKey,
5558 moveToFormat = moveToFormat,
5559 moveWithinFormat = moveWithinFormat,
5560 showKey = showKey,
5561 thickness = thickness)
5562
5563 def getGame(self):
5564 return self.getParent(Game)
5565
5566 registerElement(Map)
5567
5568 # --------------------------------------------------------------------
5569 class WidgetMap(BaseMap):
5570 TAG = Element.WIDGET+'WidgetMap'
5571 def __init__(self,doc,node=None,**attr):
5572 super(WidgetMap,self).__init__(doc,self.TAG,node=node,**attr)
5573
5574 def getGame(self):
5575 return self.getParentOfClass([Game])
5576 def getMapWidget(self):
5577 return self.getParent(MapWidget)
5578
5579 registerElement(WidgetMap)
5580
5581
5582 #
5583 # EOF
5584 #
5585 # ====================================================================
5586 # From chart.py
5587
5588 # --------------------------------------------------------------------
5589 class ChartWindow(GameElement,WidgetElement):
5590 TAG=Element.MODULE+'ChartWindow'
5591 def __init__(self,elem,node=None,
5592 name = '',
5593 hotkey = key('A',ALT),
5594 description = '',
5595 text = '',
5596 tooltip = 'Show/hide Charts',
5597 icon = '/images/chart.gif'):
5598 super(ChartWindow,self).__init__(elem,self.TAG,node=node,
5599 name = name,
5600 hotkey = hotkey,
5601 description = description,
5602 text = text,
5603 tooltip = tooltip,
5604 icon = icon)
5605
5606 def addChart(self,**kwargs):
5607 '''Add a `Chart` element to this
5608
5609 Parameters
5610 ----------
5611 kwargs : dict
5612 Dictionary of attribute key-value pairs
5613
5614 Returns
5615 -------
5616 element : Chart
5617 The added element
5618 '''
5619 return self.add(Chart,**kwargs)
5620 def getCharts(self,asdict=True):
5621 '''Get all Chart element(s) from this
5622
5623 Parameters
5624 ----------
5625 asdict : bool
5626 If `True`, return a dictonary that maps key to `Chart`
5627 elements. If `False`, return a list of all Chart`
5628 children.
5629
5630 Returns
5631 -------
5632 children : dict or list
5633 Dictionary or list of `Chart` children
5634
5635 '''
5636 return self.getElementsById(Chart,'chartName',asdict=asdict)
5637
5638 registerElement(ChartWindow)
5639
5640 # --------------------------------------------------------------------
5641 class Chart(Element):
5642 TAG=Element.WIDGET+'Chart'
5643 def __init__(self,elem,node=None,
5644 chartName = '',
5645 fileName = '',
5646 description = ''):
5647 super(Chart,self).__init__(elem,self.TAG,node=node,
5648 chartName = chartName,
5649 description = description,
5650 fileName = fileName)
5651
5652 registerElement(Chart)
5653
5654 #
5655 # EOF
5656 #
5657 # ====================================================================
5658 # From command.py
5659
5660 # --------------------------------------------------------------------
5661 class Command:
5662 def __init__(self,what,iden,tpe,state):
5663 self.cmd = '/'.join([what,iden,tpe,state])
5664
5665 # --------------------------------------------------------------------
5666 class AddCommand(Command):
5667 ID = '+'
5668 def __init__(self,iden,tpe,state):
5669 super(AddCommand,self).__init__(self.ID,iden,tpe,state)
5670
5671
5672 #
5673 # EOF
5674 #
5675 # ====================================================================
5676 # From trait.py
5677 # ====================================================================
5678 class Trait:
5679 known_traits = []
5680 def __init__(self):
5681 '''Base class for trait capture.
5682
5683 Unlike the Element classes, this actually holds state that
5684 isn't reflected elsewhere in the DOM. This means that the
5685 data here is local to the object. So when we do
5686
5687 piece = foo.getPieceSlots()[0]
5688 traits = p.getTraits()
5689 for trait in traits:
5690 if trait.ID == 'piece':
5691 trait["gpid"] = newPid
5692 trait["lpid"] = newPid
5693
5694 we do not actually change anything in the DOM. To do that, we
5695 must add back _all_ the traits as
5696
5697 piece.setTraits(traits)
5698
5699 We can add traits to a piece, like
5700
5701 piece.addTrait(MarkTrait('Hello','World'))
5702
5703 But it is not particularly efficient. Better to do
5704 (continuing from above)
5705
5706 traits.append(MarkTrait('Hello','World;)
5707 piece.setTraits(traits)
5708
5709 .. include:: ../../vassal/traits/README.md
5710 :parser: myst_parser.sphinx_
5711
5712 '''
5713 self._type = None
5714 self._state = None
5715
5716 def setType(self,**kwargs):
5717 '''Set types. Dictionary of names and values. Dictonary keys
5718 defines how we access the fields, which is internal here.
5719 What matters is the order of the values.
5720
5721 '''
5722 self._type = list(kwargs.values())
5723 self._tnames = list(kwargs.keys())
5724
5725 def setState(self,**kwargs):
5726 '''Set states. Dictionary of names and values. Dictonary keys
5727 defines how we access the fields, which is internal here.
5728 What matters is the order of the values.
5729 '''
5730 self._state = list(kwargs.values())
5731 self._snames = list(kwargs.keys())
5732
5733 def __getitem__(self,key):
5734 '''Look up item in either type or state'''
5735 try:
5736 return self._type[self._tnames.index(key)]
5737 except:
5738 pass
5739 return self._state[self._snames.index(key)]
5740
5741 def __setitem__(self,key,value):
5742 '''Set item in either type or state'''
5743 try:
5744 self._type[self._tnames.index(key)] = value
5745 return
5746 except:
5747 pass
5748 self._state[self._snames.index(key)] = value
5749
5750 def encode(self,term=False):
5751 '''
5752 returns type and state encoded'''
5753 t = self.encodeFields(self.ID,*self._type,term=term)
5754 s = self.encodeFields(*self._state,term=term)
5755 return t,s
5756
5757 @classmethod
5758 def findTrait(cls,traits,ID,key=None,value=None,verbose=False):
5759 for trait in traits:
5760 if trait.ID != ID:
5761 continue
5762 if verbose:
5763 print(f' {trait.ID}')
5764 if key is None or value is None:
5765 if verbose:
5766 print(f' Return {trait.ID}')
5767 return trait
5768 if verbose:
5769 print(f' Check {key}={value}: {trait[key]}')
5770 if trait[key] == value:
5771 return trait
5772 if verbose:
5773 print(f' Trait of type {ID} with {key}={value} not found')
5774 return None
5775
5776 @classmethod
5777 def take(cls,iden,t,s):
5778 '''If the first part of the string t matches the ID, then take it.
5779
5780 t and s are lists of strings.
5781 '''
5782 if iden != cls.ID: return None
5783
5784 ret = cls()
5785 ret._type = t
5786 ret._state = s
5787 ret.check() # Check if we're reasonable, or raise
5788 #print(f'Took {iden} {cls}\n'
5789 # f' {ret._tnames}\n'
5790 # f' {ret._snames}')
5791 return ret
5792
5793 def check(self):
5794 '''Implement if trait should check that all is OK when cloning'''
5795 pass
5796
5797 @classmethod
5798 def encodeFields(cls,*args,term=False):
5799 return ';'.join([str(e).lower() if isinstance(e,bool) else str(e)
5800 for e in args])+(';' if term else '')
5801
5802 @classmethod
5803 def decodeFields(cls,s):
5804 from re import split
5805 return split(r'(?<!\\);',s)
5806 # return s.split(';') # Probably too simple-minded
5807
5808 @classmethod
5809 def encodeKeys(cls,keys,sep=','):
5810 return sep.join([k.replace(',','\\'+f'{sep}') for k in keys])
5811
5812 @classmethod
5813 def decodeKeys(cls,keys,sep=','):
5814 from re import split
5815 ks = split(r'(?<!\\)'+f'{sep}',keys)
5816 return [k.replace('\\'+f'{sep}',f'{sep}') for k in ks]
5817
5818 @classmethod
5819 def flatten(cls,traits,game=None,prototypes=None,verbose=False):
5820 if prototypes is None:
5821 if game is None:
5822 print(f'Warning: Game or prototypes not passed')
5823 return None
5824 prototypes = game.getPrototypes()[0].getPrototypes()
5825
5826 if len(traits) < 1: return None
5827
5828 basic = None
5829 if traits[-1].ID == BasicTrait.ID:
5830 basic = traits.pop()
5831
5832 if verbose:
5833 print(f'Piece {basic["name"]}')
5834
5835 ret = cls._flatten(traits,prototypes,' ',verbose)
5836 ret.append(basic)
5837
5838 return ret
5839
5840 @classmethod
5841 def _flatten(cls,traits,prototypes,ind,verbose):
5842 '''Expand all prototype traits in traits'''
5843 ret = []
5844 for trait in traits:
5845 # Ignore recursive basic traits
5846 if trait.ID == BasicTrait.ID:
5847 continue
5848 # Add normal traits
5849 if trait.ID != PrototypeTrait.ID:
5850 if verbose:
5851 print(f'{ind}Adding trait "{trait.ID}"')
5852
5853 ret.append(trait)
5854 continue
5855
5856 # Find prototype
5857 name = trait['name']
5858 proto = prototypes.get(name,None)
5859 if proto is None:
5860 if name != ' prototype':
5861 print(f'{ind}Warning, prototype {name} not found')
5862 continue
5863
5864 if verbose:
5865 print(f'{ind}Expanding prototype "{name}"')
5866
5867 # Recursive call to add prototype traits (and possibly
5868 # more recursive calls
5869 ret.extend(cls._flatten(proto.getTraits(), prototypes,
5870 ind+' ',verbose))
5871
5872 return ret
5873
5874 def print(self,file=None):
5875 if file is None:
5876 from sys import stdout
5877 file = stdout
5878
5879 nt = max([len(i) for i in self._tnames])
5880 ns = max([len(i) for i in self._snames])
5881 nw = max(nt,ns)
5882
5883 print(f'Trait ID={self.ID}',file=file)
5884 print(f' Type:', file=file)
5885 for n,v in zip(self._tnames,self._type):
5886 print(f' {n:<{nw}s}: {v}',file=file)
5887 print(f' State:', file=file)
5888 for n,v in zip(self._snames,self._state):
5889 print(f' {n:<{nw}s}: {v}',file=file)
5890
5891 #
5892 # EOF
5893 #
5894 # ====================================================================
5895 # From withtraits.py
5896
5897 # --------------------------------------------------------------------
5898 #
5899 # Traits of this kind of object are
5900 #
5901 # - Evaluated from the start of the list to the end of the list,
5902 # skipping over report and trigger traits
5903 # - Then evaluated from the end of the list to the start, only
5904 # evaluating report and trigger traits
5905 # - The list _must_ end in a BasicTrait
5906 #
5907 # Traits are copied when making a copy of objects of this class, and
5908 # are done so using a full decoding and encoding. This means that
5909 # copying is a bit susceptible to expansions of the strings of the traits,
5910 # in particular if they contain special characters such as ',' or '/'.
5911 #
5912 class WithTraits(Element):
5913 def __init__(self,parent,tag,node=None,traits=[],**kwargs):
5914 '''Base class for things that have traits
5915
5916 Parameters
5917 ----------
5918 parent : Element
5919 Parent to add this to
5920 node : xml.minidom.Element
5921 If not None, XML element to read definition from.
5922 Rest of the arguments are ignored if not None.
5923 traits : list of Trait objects
5924 The traits to set on this object
5925 kwargs : dict
5926 More attributes to set on element
5927 '''
5928 super(WithTraits,self).__init__(parent,tag,node=node,**kwargs)
5929 if node is None: self.setTraits(*traits)
5930
5931 def addTrait(self,trait):
5932 '''Add a `Trait` element to this. Note that this re-encodes
5933 all traits.
5934
5935 Parameters
5936 ----------
5937 trait : Trait
5938 The trait to add
5939 '''
5940 traits = self.getTraits()
5941 traits.append(trait)
5942 self.setTraits(*traits)
5943
5944
5945 def getTraits(self):
5946 '''Get all element traits as objects. This decodes the trait
5947 definitions. This is useful if we have read the element from
5948 the XML file, or similar.
5949
5950 Note that the list of traits returned are _not_ tied to the
5951 XML nodes content. Therefore, if one makes changes to the list,
5952 or to elements of the list, and these changes should be
5953 reflected in this object, then we _must_ call
5954
5955 setTraits(traits)
5956
5957 with the changed list of traits.
5958
5959 Returns
5960 -------
5961 traits : list of Trait objects
5962 The decoded traits
5963
5964 '''
5965 code = self._node.childNodes[0].nodeValue
5966 return self.decodeAdd(code)
5967
5968 def encodedStates(self):
5969 from re import split
5970
5971 code = self._node.childNodes[0].nodeValue
5972 cmd, iden, typ, sta = split(fr'(?<!\\)/',code) #code.split('/')
5973
5974 return sta
5975
5976 def decodeStates(self,code,verbose=False):
5977 from re import split
5978
5979 newstates, oldstates = split(fr'(?<!\\)/',code)#code.split('/')
5980
5981 splitit = lambda l : \
5982 [s.strip('\\').split(';') for s in l.split(r' ')]
5983
5984 newstates = splitit(newstates)
5985 oldstates = splitit(oldstates)
5986
5987 traits = self.getTraits()
5988
5989 if len(traits) != len(newstates):
5990 print(f'Piece has {len(traits)} traits but got '
5991 f'{len(newstates)} states')
5992
5993 for trait, state in zip(traits,newstates):
5994 trait._state = state;
5995 # print(trait.ID)
5996 # for n,s in zip(trait._snames,trait._state):
5997 # print(f' {n:30s}: {s}')
5998
5999 self.setTraits(*traits)
6000
6001 def copyStates(self,other,verbose=False):
6002 straits = other.getTraits()
6003 dtraits = self.getTraits()
6004
6005 matches = 0
6006 for strait in straits:
6007 if len(strait._state) < 1:
6008 continue
6009
6010 cand = []
6011 ttrait = None
6012 for dtrait in dtraits:
6013 if dtrait.ID == strait.ID:
6014 cand.append(dtrait)
6015
6016 if verbose and len(cand) < 1:
6017 print(f'Could not find candidate for {strait.ID}')
6018 continue
6019
6020 if len(cand) == 1:
6021 ttrait = cand[0]
6022
6023 else:
6024 # print(f'Got {len(cand)} candidiate targets {strait.ID}')
6025
6026 best = None
6027 count = 0
6028 types = strait._type
6029 for c in cand:
6030 cnt = sum([ct == t for ct,t in zip(c._type, types)])
6031 if cnt > count:
6032 best = c
6033 count = cnt
6034
6035 if verbose and best is None:
6036 print(f'No candidate for {strait.ID} {len(again)}')
6037
6038 if verbose and count+2 < len(types):
6039 print(f'Ambigious candidate for {strait.ID} '
6040 f'({count} match out of {len(types)})')
6041 #print(best._type)
6042 #print(types)
6043
6044 ttrait = best
6045
6046 if ttrait is None:
6047 continue
6048
6049 ttrait._state = strait._state
6050 matches += 1
6051 # print(ttrait.ID)
6052 # for n,s in zip(ttrait._snames,ttrait._state):
6053 # print(f' {n:30s}: {s}')
6054
6055 if verbose:
6056 print(f'Got {matches} matches out of {len(dtraits)}')
6057
6058 self.setTraits(*dtraits)
6059
6060
6061 def decodeAdd(self,code,verbose=False):
6062 '''Try to decode make a piece from a piece of state code'''
6063 from re import split
6064
6065 cmd, iden, typ, sta = split(fr'(?<!\\)/',code) #code.split('/')
6066 # print(cmd,iden,typ,sta)
6067
6068 types = typ.split(r' ')
6069 states = sta.split(r' ')
6070 types = [t.strip('\\').split(';') for t in types]
6071 states = [s.strip('\\').split(';') for s in states]
6072 traits = []
6073
6074 for t, s in zip(types,states):
6075 tid = t[0]
6076 trem = t[1:]
6077 known = False
6078
6079 for c in Trait.known_traits:
6080 t = c.take(tid,trem,s) # See if we have it
6081 if t is not None:
6082 traits.append(t) # Got it
6083 known = True
6084 break
6085
6086 if not known:
6087 print(f'Warning: Unknown trait {tid}')
6088
6089 return traits
6090
6091 def encodeAdd(self,*traits,iden='null',verbose=False):
6092 '''Encodes type and states'''
6093 if len(traits) < 1: return ''
6094
6095 last = traits[-1]
6096 # A little hackish to use the name of the class, but needed
6097 # because of imports into patch scripts.
6098 if not isinstance(last,BasicTrait) and \
6099 not last.__class__.__name__.endswith('BasicTrait'):
6100 from sys import stderr
6101 print(f'Warning - last trait NOT a BasicTrait, but a {type(last)}',
6102 file=stderr)
6103
6104 types = []
6105 states = []
6106 for trait in traits:
6107 if trait is None:
6108 print(f'Trait is None (traits: {traits})')
6109 continue
6110 tpe, state = trait.encode()
6111 types.append(tpe)
6112 states.append(state)
6113
6114 tpe = WithTraits.encodeParts(*types)
6115 state = WithTraits.encodeParts(*states)
6116 add = AddCommand(str(iden),tpe,state)
6117 return add.cmd
6118
6119
6120 def setTraits(self,*traits,iden='null'):
6121 '''Set traits on this element. This encodes the traits into
6122 this object.
6123
6124 Parameters
6125 ----------
6126 traits : tuple of Trait objects
6127 The traits to set on this object.
6128 iden : str
6129 Identifier
6130
6131 '''
6132 add = self.encodeAdd(*traits,iden=iden)
6133 if self._node is None:
6134 from xml.dom.minidom import Element, Text
6135 self._node = Element(self.TAG)
6136 self._node.appendChild(Text())
6137
6138 if len(self._node.childNodes) < 1:
6139 self.addText('')
6140 self._node.childNodes[0].nodeValue = add
6141
6142 def removeTrait(self,ID,key=None,value=None,verbose=False):
6143 '''Remove a trait from this object.
6144
6145 Parameters
6146 ----------
6147 ID : str
6148 The type of trait to remove. Must be a valid
6149 ID of a class derived from Trait.
6150 key : str
6151 Optional key to inspect to select trait that has
6152 this key and the traits key value is the argument value,
6153 value :
6154 If specified, then only traits which key has this value
6155 are removed
6156 verbose : bool
6157 Be verbose if True
6158
6159 Returns
6160 -------
6161 trait : Trait
6162 The removed trait or None
6163 '''
6164 traits = self.getTraits()
6165 trait = Trait.findTrait(traits,ID,key,value,verbose)
6166 if trait is not None:
6167 traits.remove(trait)
6168 self.setTraits(traits)
6169 return trait
6170
6171 def addTraits(self,*toadd):
6172 '''Add traits to this. Note that this will
6173 decode and reencode the traits. Only use this when
6174 adding traits on-mass. Repeated use of this is inefficient.
6175
6176 This member function takes care to push any basic trait to
6177 the end of the list.
6178
6179 The added traits will not override existing triats.
6180
6181 Paramters
6182 ---------
6183 toAdd : tuple of Trait objects
6184 The traits to add
6185
6186 '''
6187 traits = self.getTraits()
6188 basic = Trait.findTrait(traits,BasicTrait.ID)
6189 if basic:
6190 traits.remove(basic)
6191 traits.extend(toAdd)
6192 if basic:
6193 traits.append(basic)
6194 self.setTraits(traits)
6195
6196
6197 @classmethod
6198 def encodeParts(cls,*parts):
6199 '''Encode parts of a full piece definition
6200
6201 Each trait (VASSAL.counter.Decorator,
6202 VASSAL.counter.BasicPiece) definition or state is separated by
6203 a litteral TAB character. Beyond the first TAB separator,
6204 additional escape characters (BACKSLAH) are added in front of
6205 the separator. This is to that VASSAL.utils.SequenceDecoder
6206 does not see consequitive TABs as a single TAB.
6207 '''
6208 ret = ''
6209 sep = r' '
6210 for i, p in enumerate(parts):
6211 if i != 0:
6212 ret += '\\'*(i-1) + sep
6213 ret += str(p)
6214
6215 return ret
6216
6217
6218 def cloneNode(self,parent):
6219 '''This clones the underlying XML node.
6220
6221 Parameters
6222 ----------
6223 parent : Element
6224 The element to clone this element into
6225
6226 Returns
6227 -------
6228 copy : xml.minidom.Element
6229 The newly created clone of this object's node
6230 '''
6231 copy = self._node.cloneNode(deep=True)
6232 if parent is not None:
6233 parent._node.appendChild(copy)
6234 else:
6235 print('WARNING: No parent to add copy to')
6236 return copy
6237
6238 # --------------------------------------------------------------------
6239 class DummyWithTraits(WithTraits):
6240 TAG = 'dummy'
6241 def __init__(self,parent,node=None,traits=[]):
6242 '''An empty element. Used when making searching'''
6243 super(DummyWithTraits,self).__init__(tag = self.TAG,
6244 parent = parent,
6245 node = node,
6246 traits = traits)
6247 if parent is not None:
6248 parent.remove(self)
6249
6250
6251 registerElement(DummyWithTraits)
6252
6253 # --------------------------------------------------------------------
6254 class PieceSlot(WithTraits):
6255 TAG = Element.WIDGET+'PieceSlot'
6256 def __init__(self,parent,node=None,
6257 entryName = '',
6258 traits = [],
6259 gpid = 0,
6260 height = 72,
6261 width = 72,
6262 icon = ''):
6263 '''A piece slot. Used all the time.
6264
6265 Parameters
6266 ----------
6267 parent : Element
6268 Parent to add this to
6269 node : xml.minidom.Element
6270 If not None, XML element to read definition from.
6271 Rest of the arguments are ignored if not None.
6272 entryName : str
6273 Name of this
6274 traits : list of Trait objects
6275 The traits to set on this object
6276 gpid : int
6277 Global Piece identifier. If 0, will be set by Game
6278 height : int
6279 Height size of the piece (in pixels)
6280 width : int
6281 Width size of the piece (in pixels)
6282 icon : str
6283 Piece image file name within 'image' sub-dir of archive
6284 '''
6285 super(PieceSlot,self).\
6286 __init__(parent,self.TAG,node=node,
6287 traits = traits,
6288 entryName = entryName,
6289 gpid = gpid,
6290 height = height,
6291 width = width,
6292 icon = icon)
6293
6294
6295 def clone(self,parent):
6296 '''Adds copy of self to parent, possibly with new GPID'''
6297 game = self.getParentOfClass([Game])
6298 gpid = game.nextPieceSlotId()
6299 #opid = int(self.getAttribute('gpid'))
6300 #print(f'Using GPID={gpid} for clone {opid}')
6301
6302 node = self.cloneNode(parent)
6303 piece = PieceSlot(parent,node=node)
6304 piece.setAttribute('gpid',gpid)
6305
6306 traits = piece.getTraits()
6307 for trait in traits:
6308 if isinstance(trait,BasicTrait):
6309 trait['gpid'] = gpid
6310
6311 piece.setTraits(*traits)
6312 return piece
6313
6314 registerElement(PieceSlot)
6315
6316 # --------------------------------------------------------------------
6317 class Prototype(WithTraits):
6318 TAG = Element.MODULE+'PrototypeDefinition'
6319 def __init__(self,cont,node=None,
6320 name = '',
6321 traits = [],
6322 description = ''):
6323 '''A prototype. Used all the time.
6324
6325 Parameters
6326 ----------
6327 cont : Element
6328 Parent to add this to
6329 node : xml.minidom.Element
6330 If not None, XML element to read definition from.
6331 Rest of the arguments are ignored if not None.
6332 name : str
6333 Name of this
6334 traits : list of Trait objects
6335 The traits to set on this object
6336 description : str
6337 A free-form description of this prototype
6338 '''
6339 super(Prototype,self).__init__(cont,self.TAG,node=node,
6340 traits = traits,
6341 name = name,
6342 description = description)
6343
6344 registerElement(Prototype)
6345
6346 #
6347 # EOF
6348 #
6349 # ====================================================================
6350 # From traits/area.py
6351
6352 class AreaTrait(Trait):
6353 ID = 'AreaOfEffect'
6354 def __init__(self,
6355 transparancyColor = rgb(0x77,0x77,0x77),
6356 transparancyLevel = 30,
6357 radius = 1,
6358 alwaysActive = False,
6359 activateCommand = 'Toggle area of effect',
6360 activateKey = key('A'), # Ctrl-A
6361 mapShaderName = '',
6362 fixedRadius = True,
6363 radiusMarker = '', # Property
6364 description = 'Show area of effect',
6365 name = 'EffectArea',
6366 onMenuText = '', # Show area of effect
6367 onKey = '', # key('A')
6368 offMenuText = '', # Hide area of effect
6369 offKey = '', # key(A,SHIFT)
6370 globallyVisible = True):
6371 super(AreaTrait,self).__init__()
6372 self.setType(
6373 transparancyColor = transparancyColor,
6374 transparancyLevel = int(transparancyLevel),
6375 radius = radius,
6376 alwaysActive = alwaysActive,
6377 activateCommand = activateCommand,
6378 activateKey = activateKey,
6379 mapShaderName = mapShaderName,
6380 fixedRadius = fixedRadius,
6381 radiusMarker = radiusMarker,
6382 description = description,
6383 name = name,
6384 onMenuText = onMenuText,
6385 onKey = onKey,
6386 offMenuText = offMenuText,
6387 offKey = offKey,
6388 globallyVisible = globallyVisible
6389 )
6390 self.setState(active = alwaysActive or not globallyVisible)
6391
6392 Trait.known_traits.append(AreaTrait)
6393 #
6394 # EOF
6395 #
6396 # ====================================================================
6397 # From traits/dynamicproperty.py
6398
6399 # --------------------------------------------------------------------
6400 #
6401 #
6402 class ChangePropertyTrait(Trait):
6403 DIRECT = 'P'
6404 INCREMENT = 'I'
6405 def __init__(self,
6406 *commands,
6407 numeric = False,
6408 min = 0,
6409 max = 100,
6410 wrap = False):
6411 '''Base class for property (piece or global) change traits.
6412
6413 Encodes constraints and commands.
6414 '''
6415 # assert name is not None and len(name) > 0, \
6416 # 'No name specified for ChangePropertyTriat'
6417 super(ChangePropertyTrait,self).__init__()
6418 self._constraints = self.encodeConstraints(numeric,wrap,min,max)
6419 self._commands = self.encodeCommands(commands)
6420
6421 def encodeConstraints(self,numeric,wrap,min,max):
6422 isnum = f'{numeric}'.lower()
6423 iswrap = f'{wrap}'.lower()
6424 return f'{isnum},{min},{max},{iswrap}'
6425
6426 def decodeConstraints(self,constraints):
6427 f = Trait.decodeKeys(constraints)
6428 return f[0]=='true',f[3]=='true',int(f[1]),int(f[2])
6429
6430 def encodeCommands(self,commands):
6431 cmds = []
6432 for cmd in commands:
6433 # print(cmd)
6434 com = cmd[0] + ':' + cmd[1].replace(',',r'\,') + ':' + cmd[2]
6435 if cmd[2] == self.DIRECT:
6436 com += r'\,'+cmd[3].replace(',',r'\\,').replace(':',r'\:')
6437 elif cmd[2] == self.INCREMENT:
6438 com += r'\,'+cmd[3].replace(',',r'\\,').replace(':',r'\:')
6439 cmds.append(com)
6440 # print(cmds)
6441 return ','.join(cmds)
6442
6443 def decodeCommands(self,commands):
6444 cmds = Trait.decodeKeys(commands)
6445 ret = []
6446 for cmd in cmds:
6447 parts = Trait.decodeKeys(cmd,':')
6448 # print('parts',parts)
6449 if parts[-1][0] == self.DIRECT:
6450 parts = parts[:-1]+Trait.decodeKeys(parts[-1],',')
6451 if parts[-1][0] == self.INCREMENT:
6452 parts = parts[:-1]+Trait.decodeKeys(parts[-1],',')
6453 ret.append(parts)
6454 # print(commands,parts)
6455 return ret
6456
6457 def getCommands(self):
6458 return self.decodeCommands(self['commands'])
6459
6460 def setCommands(self,commands):
6461 self['commands'] = self.encodeCommands(commands)
6462
6463 def check(self):
6464 assert len(self['name']) > 0,\
6465 f'No name given for ChangePropertyTrait'
6466
6467
6468 # --------------------------------------------------------------------
6469 class DynamicPropertyTrait(ChangePropertyTrait):
6470 ID = 'PROP'
6471 def __init__(self,
6472 *commands,
6473 name = '',
6474 value = 0,
6475 numeric = False,
6476 min = 0,
6477 max = 100,
6478 wrap = False,
6479 description = ''):
6480 '''Commands are
6481
6482 - menu
6483 - key
6484 - Type (only 'P' for now)
6485 - Expression
6486 '''
6487 super(DynamicPropertyTrait,self).__init__(*commands,
6488 numeric = numeric,
6489 min = min,
6490 max = max,
6491 wrap = wrap)
6492 # print(commands,'Name',name)
6493 self.setType(name = name,
6494 constraints = self._constraints,
6495 commands = self._commands,
6496 description = description)
6497 self.setState(value=value)
6498
6499
6500 Trait.known_traits.append(DynamicPropertyTrait)
6501
6502 #
6503 # EOF
6504 #
6505 # ====================================================================
6506 # From traits/globalproperty.py
6507
6508 # --------------------------------------------------------------------
6509 class GlobalPropertyTrait(ChangePropertyTrait):
6510 # The real value of CURRENT_ZONE causes problems when copying the
6511 # trait, since it contains slashes. Maybe a solition is to make
6512 # it a raw string with escaped slashes? No, that's already done
6513 # below when setting the type. However, the default in the Java
6514 # code is the CURRENT_ZONE real value, so setting this to the
6515 # empty string should make it be that value.
6516 ID = 'setprop'
6517 CURRENT_ZONE = 'Current Zone/Current Map/Module'
6518 NAMED_ZONE = 'Named Zone'
6519 NAMED_MAP = 'Named Map'
6520 DIRECT = 'P'
6521 def __init__(self,
6522 *commands,
6523 name = '',
6524 numeric = False,
6525 min = 0,
6526 max = 100,
6527 wrap = False,
6528 description = '',
6529 level = CURRENT_ZONE,
6530 search = ''):
6531 '''Commands are
6532
6533 - menu
6534 - key
6535 - Type (only 'P' for now)
6536 - Expression
6537 '''
6538 super(GlobalPropertyTrait,self).__init__(*commands,
6539 numeric = numeric,
6540 min = min,
6541 max = max,
6542 wrap = wrap)
6543 self.setType(name = name,
6544 constraints = self._constraints,
6545 commands = self._commands,
6546 description = description,
6547 level = level.replace('/',r'\/'),
6548 search = search)
6549 self.setState()
6550
6551 Trait.known_traits.append(GlobalPropertyTrait)
6552
6553 #
6554 # EOF
6555 #
6556 # ====================================================================
6557 # From traits/prototype.py
6558
6559 # --------------------------------------------------------------------
6560 class PrototypeTrait(Trait):
6561 ID = 'prototype'
6562 def __init__(self,name=''):
6563 '''Create a prototype trait (VASSAL.counter.UsePrototype)'''
6564 super(PrototypeTrait,self).__init__()
6565 self.setType(name = name)
6566 self.setState(ignored = '')
6567
6568
6569 Trait.known_traits.append(PrototypeTrait)
6570
6571 #
6572 # EOF
6573 #
6574 # ====================================================================
6575 # From traits/place.py
6576
6577 # --------------------------------------------------------------------
6578 class PlaceTrait(Trait):
6579 ID = 'placemark'
6580 STACK_TOP = 0
6581 STACK_BOTTOM = 1
6582 ABOVE = 2
6583 BELOW = 3
6584
6585 # How the LaTeX exporter organises the units. Format with
6586 # 0: the group
6587 # 1: the piece name
6588 # SKEL_PATH = (PieceWindow.TAG +r':Counters\/' +
6589 # TabWidget.TAG +r':Counters\/' +
6590 # PanelWidget.TAG +':{0}' +r'\/'+
6591 # ListWidget.TAG +':{0} counters'+r'\/'+
6592 # PieceSlot.TAG +':{1}')
6593 @classmethod
6594 @property
6595 def SKEL_PATH(cls):
6596
6597 return (PieceWindow.TAG +r':Counters\/' +
6598 TabWidget.TAG +r':Counters\/' +
6599 PanelWidget.TAG +':{0}' +r'\/'+
6600 ListWidget.TAG +':{0} counters'+r'\/'+
6601 PieceSlot.TAG +':{1}')
6602
6603 def __init__(self,
6604 command = '', # Context menu name
6605 key = '', # Context menu key
6606 markerSpec = '', # Full path in module
6607 markerText = 'null', # Hard coded message
6608 xOffset = 0,
6609 yOffset = 0,
6610 matchRotation = True,
6611 afterKey = '',
6612 description = '',
6613 gpid = '', # Set in JAVA, but with warning
6614 placement = ABOVE,
6615 above = False):
6616 '''Create a place marker trait (VASSAL.counter.PlaceMarker)'''
6617 super(PlaceTrait,self).__init__()
6618 self.setType(command = command, # Context menu name
6619 key = key, # Context menu key
6620 markerSpec = markerSpec,
6621 markerText = markerText,
6622 xOffset = xOffset,
6623 yOffset = yOffset,
6624 matchRotation = matchRotation,
6625 afterKey = afterKey,
6626 description = description,
6627 gpid = gpid,
6628 placement = placement,
6629 above = above)
6630 self.setState()
6631
6632 Trait.known_traits.append(PlaceTrait)
6633
6634 # --------------------------------------------------------------------
6635 class ReplaceTrait(PlaceTrait):
6636 ID = 'replace'
6637 def __init__(self,
6638 command = '', # Context menu name
6639 key = '', # Context menu key
6640 markerSpec = '', # Full path in module
6641 markerText = 'null', # Hard message
6642 xOffset = 0,
6643 yOffset = 0,
6644 matchRotation = True,
6645 afterKey = '',
6646 description = '',
6647 gpid = '', # Set in JAVA
6648 placement = PlaceTrait.ABOVE,
6649 above = False):
6650 super(ReplaceTrait,self).__init__(command = command,
6651 key = key,
6652 markerSpec = markerSpec,
6653 markerText = markerText,
6654 xOffset = xOffset,
6655 yOffset = yOffset,
6656 matchRotation = matchRotation,
6657 afterKey = afterKey,
6658 description = description,
6659 gpid = gpid,
6660 placement = placement,
6661 above = above)
6662
6663
6664 Trait.known_traits.append(ReplaceTrait)
6665
6666 #
6667 # EOF
6668 #
6669 # ====================================================================
6670 # From traits/report.py
6671
6672 # --------------------------------------------------------------------
6673 class ReportTrait (Trait):
6674 ID = 'report'
6675 def __init__(self,
6676 *keys,
6677 nosuppress = True,
6678 description = '',
6679 report = '$location$: $newPieceName$ $menuCommand$ *',
6680 cyclekeys = '',
6681 cyclereps = ''):
6682 '''Create a report trait (VASSAL.counters.ReportActon)'''
6683 super(ReportTrait,self).__init__()
6684 esckeys = ','.join([k.replace(',',r'\,') for k in keys])
6685 esccycl = ','.join([k.replace(',',r'\,') for k in cyclekeys])
6686 escreps = ','.join([k.replace(',',r'\,') for k in cyclereps])
6687
6688 self.setType(keys = esckeys,
6689 report = report,
6690 cycleKeys = esccycl,
6691 cycleReports = escreps,
6692 description = description,
6693 nosuppress = nosuppress)
6694 self.setState(cycle = -1)
6695
6696 Trait.known_traits.append(ReportTrait)
6697
6698 #
6699 # EOF
6700 #
6701 # ====================================================================
6702 # From traits/calculatedproperty.py
6703
6704 # --------------------------------------------------------------------
6705 class CalculatedTrait(Trait):
6706 ID = 'calcProp'
6707 def __init__(self,name='',expression='',description=''):
6708 '''Define a trait that calculates a property'''
6709 super(CalculatedTrait,self).__init__()
6710 self.setType(name = name,
6711 expression = expression,
6712 description = description)
6713 self.setState()
6714
6715
6716 Trait.known_traits.append(CalculatedTrait)
6717
6718 #
6719 # EOF
6720 #
6721 # ====================================================================
6722 # From traits/restrictcommand.py
6723
6724 # --------------------------------------------------------------------
6725 class RestrictCommandsTrait(Trait):
6726 ID = 'hideCmd'
6727 HIDE = 'Hide'
6728 DISABLE = 'Disable'
6729 def __init__(self,
6730 name = '',
6731 hideOrDisable = HIDE,
6732 expression = '',# Restrict when true
6733 keys = []):
6734 '''Create a layer trait (VASSAL.counter.RestrictCommands)'''
6735 super(RestrictCommandsTrait,self).__init__()
6736 encKeys = ','.join([k.replace(',',r'\,') for k in keys])
6737 self.setType(name = name,
6738 hideOrDisable = hideOrDisable,
6739 expression = expression,
6740 keys = encKeys)
6741 self.setState(state='')
6742 def setKeys(self,keys):
6743 self['keys'] = ','.join([k.replace(',',r'\,') for k in keys])
6744
6745
6746 Trait.known_traits.append(RestrictCommandsTrait)
6747
6748 #
6749 # EOF
6750 #
6751 # ====================================================================
6752 # From traits/label.py
6753
6754 class LabelTraitCodes:
6755 TOP = 't'
6756 BOTTOM = 'b'
6757 CENTER = 'c'
6758 LEFT = 'l'
6759 RIGHT = 'r'
6760 PLAIN = 0
6761 BOLD = 1
6762 ITALIC = 2
6763
6764 # --------------------------------------------------------------------
6765 class LabelTrait(Trait):
6766 ID = 'label'
6767 def __init__(self,
6768 label = None,
6769 labelKey = '',
6770 menuCommand ='Change label',
6771 fontSize = 10,
6772 background = 'none',
6773 foreground = '255,255,255',
6774 vertical = LabelTraitCodes.TOP,
6775 verticalOff = 0,
6776 horizontal = LabelTraitCodes.CENTER,
6777 horizontalOff = 0,
6778 verticalJust = LabelTraitCodes.BOTTOM,
6779 horizontalJust = LabelTraitCodes.CENTER,
6780 nameFormat = '$pieceName$ ($label$)',
6781 fontFamily = 'Dialog',
6782 fontStyle = LabelTraitCodes.PLAIN,
6783 rotate = 0,
6784 propertyName = 'TextLabel',
6785 description = '',
6786 alwaysUseFormat = False):
6787 '''Create a label trait (can be edited property)'''
6788 super(LabelTrait,self).__init__()
6789 self.setType(labelKey = labelKey,
6790 menuCommand = menuCommand,
6791 fontSize = fontSize,
6792 background = background,
6793 foreground = foreground,
6794 vertical = vertical,
6795 verticalOff = verticalOff,
6796 horizontal = horizontal,
6797 horizontalOff = horizontalOff,
6798 verticalJust = verticalJust,
6799 horizontalJust = horizontalJust,
6800 nameFormat = nameFormat,
6801 fontFamily = fontFamily,
6802 fontStyle = fontStyle,
6803 rotate = rotate,
6804 propertyName = propertyName,
6805 description = description,
6806 alwaysUseFormat = alwaysUseFormat)
6807 self.setState(label = (nameFormat if label is None else label))
6808
6809
6810 Trait.known_traits.append(LabelTrait)
6811
6812 #
6813 # EOF
6814 #
6815 # ====================================================================
6816 # From traits/layer.py
6817
6818 # --------------------------------------------------------------------
6819 class LayerTrait(Trait):
6820 ID = 'emb2'
6821 def __init__(self,
6822 images = [''],
6823 newNames = None,
6824 activateName = 'Activate',
6825 activateMask = CTRL,
6826 activateChar = 'A',
6827 increaseName = 'Increase',
6828 increaseMask = CTRL,
6829 increaseChar = '[',
6830 decreaseName = '',
6831 decreaseMask = CTRL,
6832 decreaseChar = ']',
6833 resetName = '',
6834 resetKey = '',
6835 resetLevel = 1,
6836 under = False,
6837 underXoff = 0,
6838 underYoff = 0,
6839 loop = True,
6840 name = '',
6841 description = '',
6842 randomKey = '',
6843 randomName = '',
6844 follow = False,
6845 expression = '',
6846 first = 1,
6847 version = 1, # 1:new, 0:old
6848 always = True,
6849 activateKey = key('A'),
6850 increaseKey = key('['),
6851 decreaseKey = key(']'),
6852 scale = 1.):
6853 '''Create a layer trait (VASSAL.counter.Embellishment)'''
6854 super(LayerTrait,self).__init__()
6855 if newNames is None and images is not None:
6856 newNames = ['']*len(images)
6857 self.setType(
6858 activateName = activateName,
6859 activateMask = activateMask,
6860 activateChar = activateChar,
6861 increaseName = increaseName,
6862 increaseMask = increaseMask,
6863 increaseChar = increaseChar,
6864 decreaseName = decreaseName,
6865 decreaseMask = decreaseMask,
6866 decreaseChar = decreaseChar,
6867 resetName = resetName,
6868 resetKey = resetKey,
6869 resetLevel = resetLevel,
6870 under = under,
6871 underXoff = underXoff,
6872 underYoff = underYoff,
6873 images = ','.join(images),
6874 newNames = ','.join(newNames),
6875 loop = loop,
6876 name = name,
6877 randomKey = randomKey,
6878 randomName = randomName,
6879 follow = follow,
6880 expression = expression,
6881 first = first,
6882 version = version,
6883 always = always,
6884 activateKey = activateKey,
6885 increaseKey = increaseKey,
6886 decreaseKey = decreaseKey,
6887 description = description,
6888 scale = scale)
6889 self.setState(level=1)
6890
6891 Trait.known_traits.append(LayerTrait)
6892
6893 #
6894 # EOF
6895 #
6896 # ====================================================================
6897 # From traits/globalcommand.py
6898
6899 # --------------------------------------------------------------------
6900 class GlobalCommandTrait(Trait):
6901 ID = 'globalkey'
6902 def __init__(self,
6903 commandName = '',
6904 key = '', # Command received
6905 globalKey = '', # Command to send to targets
6906 properties = '', # Filter target on this expression
6907 ranged = False,
6908 range = 1,
6909 reportSingle = True,
6910 fixedRange = True,
6911 rangeProperty = '',
6912 description = '',
6913 deskSelect = '-1',
6914 target = ''):
6915 '''Create a global key command in piece
6916 (VASSAL.counters.CounterGlobalKeyCommand)'''
6917 self.setType(commandName = commandName,
6918 key = key,
6919 globalKey = globalKey,
6920 properties = properties,
6921 ranged = ranged,
6922 range = range,
6923 reportSingle = reportSingle,
6924 fixedRange = fixedRange,
6925 rangeProperty = rangeProperty,
6926 description = description,
6927 deskSelect = deskSelect,
6928 target = target)
6929 self.setState()
6930
6931 Trait.known_traits.append(GlobalCommandTrait)
6932
6933 #
6934 # EOF
6935 #
6936 # ====================================================================
6937 # From traits/globalhotkey.py
6938
6939 # --------------------------------------------------------------------
6940 class GlobalHotkeyTrait(Trait):
6941 ID = 'globalhotkey'
6942 def __init__(self,
6943 name = '', # Command received
6944 key = '', # Command key received
6945 globalHotkey = '', # Key to send
6946 description = ''):
6947 '''Create a global key command in piece
6948 (VASSAL.counters.GlobalHotkey)'''
6949 self.setType(name = name,
6950 key = key,
6951 globalHotkey = globalHotkey,
6952 description = description)
6953 self.setState()
6954
6955 Trait.known_traits.append(GlobalHotkeyTrait)
6956
6957 #
6958 # EOF
6959 #
6960 # ====================================================================
6961 # From traits/nostack.py
6962
6963 # --------------------------------------------------------------------
6964 class NoStackTrait(Trait):
6965 ID = 'immob'
6966 NORMAL_SELECT = ''
6967 SHIFT_SELECT = 'i'
6968 CTRL_SELECT = 't'
6969 ALT_SELECT = 'c'
6970 NEVER_SELECT = 'n'
6971 NORMAL_BAND_SELECT = ''
6972 ALT_BAND_SELECT = 'A'
6973 ALT_SHIFT_BAND_SELECT = 'B'
6974 NEVER_BAND_SELECT = 'Z'
6975 NORMAL_MOVE = 'N'
6976 SELECT_MOVE = 'I'
6977 NEVER_MOVE = 'V'
6978 NORMAL_STACK = 'L'
6979 NEVER_STACK = 'R'
6980 IGNORE_GRID = 'g'
6981 def __init__(self,
6982 select = NORMAL_SELECT,
6983 bandSelect = NORMAL_BAND_SELECT,
6984 move = NORMAL_MOVE,
6985 canStack = False,
6986 ignoreGrid = False,
6987 description = ''):
6988 '''No stacking trait'''
6989 selectionOptions = (select +
6990 (self.IGNORE_GRID if ignoreGrid else '') +
6991 bandSelect)
6992 movementOptions = move
6993 stackingOptions = self.NORMAL_STACK if canStack else self.NEVER_STACK
6994
6995 '''Create a mark trait (static property)'''
6996 super(NoStackTrait,self).__init__()
6997
6998 self.setType(selectionOptions = selectionOptions,
6999 movementOptions = movementOptions,
7000 stackingOptions = stackingOptions,
7001 description = description)
7002 self.setState()
7003
7004
7005 Trait.known_traits.append(NoStackTrait)
7006
7007 #
7008 # EOF
7009 #
7010 # ====================================================================
7011 # From traits/deselect.py
7012
7013 # --------------------------------------------------------------------
7014 class DeselectTrait(Trait):
7015 ID = 'deselect'
7016 THIS = 'D' # Deselect only this piece
7017 ALL = 'A' # Deselect all pieces
7018 ONLY = 'S' # Select this piece only
7019 def __init__(self,
7020 command = '',
7021 key = '',
7022 description = '',
7023 unstack = False,
7024 deselect = THIS):
7025 '''Create a deselect trait'''
7026 super(DeselectTrait,self).__init__()
7027 self.setType(command = command,
7028 key = key,
7029 description = description,
7030 unstack = unstack,
7031 deselect = deselect)
7032 self.setState()
7033
7034
7035 Trait.known_traits.append(DeselectTrait)
7036
7037 #
7038 # EOF
7039 #
7040 # ====================================================================
7041 # From traits/restrictaccess.py
7042
7043 # --------------------------------------------------------------------
7044 class RestrictAccessTrait(Trait):
7045 ID = 'restrict'
7046 def __init__(self,
7047 sides = [],
7048 byPlayer = False,
7049 noMovement = True,
7050 description = '',
7051 owner = '',):
7052 '''Create a layer trait (VASSAL.counter.Restricted)'''
7053 super(RestrictAccessTrait,self).__init__()
7054 encSides = ','.join(sides)
7055 self.setType(sides = encSides,
7056 byPlayer = byPlayer,
7057 noMovement = noMovement,
7058 description = description)
7059 self.setState(owner=owner)
7060
7061 Trait.known_traits.append(RestrictAccessTrait)
7062
7063 #
7064 # EOF
7065 #
7066 # ====================================================================
7067 # From traits/rotate.py
7068
7069 # --------------------------------------------------------------------
7070 class RotateTrait(Trait):
7071 ID = 'rotate'
7072 def __init__(self,
7073 nangles = 6,
7074 rotateCWKey = key(']'),
7075 rotateCCWKey = key('['),
7076 rotateCW = 'Rotate CW',
7077 rotateCCW = 'Rotate CCW',
7078 rotateRndKey = '',
7079 rotateRnd = '',
7080 name = 'Rotate',
7081 description = 'Rotate piece',
7082 rotateDirectKey = '',
7083 rotateDirect = '',
7084 directExpression = '',
7085 directIsFacing = True,
7086 angle = 0):
7087 '''Create a Rotate trait'''
7088 super(RotateTrait,self).__init__()
7089 if nangles == 1:
7090 self.setType(nangles = nangles,
7091 rotateKey = rotateCWKey,
7092 rotate = rotateCW,
7093 rotateRndKey = rotateRndKey,
7094 rotateRnd = rotateRnd,
7095 name = name,
7096 description = description,
7097 rotateDirectKey = rotateDirectKey,
7098 rotateDirect = rotateDirect,
7099 directExpression = directExpression,
7100 directIsFacing = directIsFacing)
7101 else:
7102 self.setType(nangles = nangles,
7103 rotateCWKey = rotateCWKey,
7104 rotateCCWKey = rotateCCWKey,
7105 rotateCW = rotateCW,
7106 rotateCCW = rotateCCW,
7107 rotateRndKey = rotateRndKey,
7108 rotateRnd = rotateRnd,
7109 name = name,
7110 description = description,
7111 rotateDirectKey = rotateDirectKey,
7112 rotateDirect = rotateDirect,
7113 directExpression = directExpression,
7114 directIsFacing = directIsFacing)
7115
7116 self.setState(angle = int(angle) if nangles > 1 else float(angle))
7117
7118 Trait.known_traits.append(RotateTrait)
7119
7120 #
7121 # EOF
7122 #
7123 # ====================================================================
7124 # From traits/stack.py
7125
7126 # --------------------------------------------------------------------
7127 class StackTrait(Trait):
7128 ID = 'stack'
7129 def __init__(self,
7130 board = '',
7131 x = '',
7132 y = '',
7133 pieceIds = [],
7134 layer = -1):
7135 '''Create a stack trait in a save file'''
7136 self.setType() # NAME
7137 # print('Piece IDs:',pieceIds)
7138 self.setState(board = board,
7139 x = x,
7140 y = y,
7141 pieceIds = ';'.join([str(p) for p in pieceIds]),
7142 layer = f'@@{layer}')
7143
7144 Trait.known_traits.append(StackTrait)
7145
7146 #
7147 # EOF
7148 #
7149 # ====================================================================
7150 # From traits/mark.py
7151
7152 # --------------------------------------------------------------------
7153 class MarkTrait(Trait):
7154 ID = 'mark'
7155 def __init__(self,name='',value=''):
7156 '''Create a mark trait (static property)'''
7157 super(MarkTrait,self).__init__()
7158 self.setType(name = name)
7159 self.setState(value = value)
7160
7161
7162 Trait.known_traits.append(MarkTrait)
7163
7164 #
7165 # EOF
7166 #
7167 # ====================================================================
7168 # From traits/mask.py
7169
7170 # --------------------------------------------------------------------
7171 # Inset
7172 # obs;88,130;ag_hide_1.png;Reveal;I;?;sides:Argentine;Peek;;true;;
7173 # obs;88,130;ag_hide_1.png;Reveal;I;?;side:Argentine;;;true;;
7174 #
7175 # Peek
7176 # obs;88,130;ag_hide_1.png;Reveal;P89,130;?;sides:Argentine;Peek;;true;;
7177 #
7178 # Image
7179 #
7180 class MaskTrait(Trait):
7181 ID = 'obs'
7182 INSET = 'I'
7183 BACKGROUND = 'B'
7184 PEEK = 'P'
7185 IMAGE = 'G'
7186 INSET2 = '2'
7187 PLAYER = 'player:'
7188 SIDE = 'side:'
7189 SIDES = 'sides:'
7190 def __init__(self,
7191 keyCommand = '',
7192 imageName = '',
7193 hideCommand = '',
7194 displayStyle = '',
7195 peekKey = '',
7196 ownerImage = '',
7197 maskedName = '?',
7198 access = '',#?
7199 peekCommand = '',
7200 description = '',
7201 autoPeek = True,
7202 dealKey = '',
7203 dealExpr = ''):
7204 '''Create a masking trait'''
7205 super(MaskTrait,self).__init__()
7206 disp = displayStyle
7207 if displayStyle == self.PEEK:
7208 disp += peekKey
7209 elif displayStyle == self.IMAGE:
7210 disp += ownerImage
7211
7212 acc = self.PLAYER
7213 if isinstance(access,list):
7214 acc = self.SIDES + ':'.join(access)
7215 elif access.startswith('player'):
7216 acc = self.PLAYER
7217 elif access.startswith('side'):
7218 acc = self.SIDE
7219
7220 self.setType(keyCommand = keyCommand,
7221 imageImage = imageName,
7222 hideCommand = hideCommand,
7223 displayStyle = disp,
7224 maskedName = maskedName,
7225 access = acc, # ?
7226 peekCommand = peekCommand,
7227 description = description,
7228 autoPeek = autoPeek,
7229 dealKey = dealKey,
7230 dealExpr = dealExpr)
7231 self.setState(value='null')
7232
7233 @classmethod
7234 def peekDisplay(cls,key):#Encoded key
7235 return cls.PEEK + key
7236
7237 @classmethod
7238 def peekImage(cls,ownerImage):
7239 return cls.IMAGE + ownerImage
7240
7241 @classmethod
7242 def sides(cls,*names):
7243 return cls.SIDES+':'.join(names)
7244
7245 Trait.known_traits.append(MaskTrait)
7246
7247 #
7248 # EOF
7249 #
7250 # ====================================================================
7251 # From traits/trail.py
7252
7253 # --------------------------------------------------------------------
7254 class TrailTrait(Trait):
7255 ID = 'footprint'
7256 def __init__(self,
7257 key = key('T'),
7258 name = 'Movement Trail',
7259 localVisible = False,
7260 globalVisible = False,
7261 radius = 10,
7262 fillColor = rgb(255,255,255),
7263 lineColor = rgb(0,0,0),
7264 activeOpacity = 100,
7265 inactiveOpacity = 50,
7266 edgesBuffer = 20,
7267 displayBuffer = 30,
7268 lineWidth = 5,
7269 turnOn = '',
7270 turnOff = '',
7271 reset = '',
7272 description = 'Enable or disable movement trail'):
7273 ''' Create a movement trail trait ( VASSAL.counters.Footprint)'''
7274 super(TrailTrait,self).__init__()
7275 lw = (lineWidth
7276 if isinstance(lineWidth,str) and lineWidth.startswith('{') else
7277 int(lineWidth))
7278 ra = (radius
7279 if isinstance(radius,str) and radius.startswith('{') else
7280 int(radius))
7281
7282 self.setType(key = key,# ENABLE KEY
7283 name = name,# MENU
7284 localVisible = localVisible,# LOCAL VISABLE
7285 globalVisible = globalVisible,# GLOBAL VISABLE
7286 radius = ra,# RADIUS
7287 fillColor = fillColor,# FILL COLOR
7288 lineColor = lineColor,# LINE COLOR
7289 activeOpacity = activeOpacity,# ACTIVE OPACITY
7290 inactiveOpacity = inactiveOpacity,# INACTIVE OPACITY
7291 edgesBuffer = edgesBuffer,# EDGES BUFFER
7292 displayBuffer = displayBuffer,# DISPLAY BUFFER
7293 lineWidth = lw,# LINE WIDTH
7294 turnOn = turnOn,# TURN ON KEY
7295 turnOff = turnOff,# TURN OFF KEY
7296 reset = reset,# RESET KEY
7297 description = description) # DESC
7298 self.setState(isGlobal = False,
7299 map = '',
7300 points = 0, # POINTS (followed by [; [X,Y]*]
7301 init = False)
7302
7303 Trait.known_traits.append(TrailTrait)
7304
7305 #
7306 # EOF
7307 #
7308 # ====================================================================
7309 # From traits/delete.py
7310
7311 # --------------------------------------------------------------------
7312 class DeleteTrait(Trait):
7313 ID = 'delete'
7314 def __init__(self,
7315 name = 'Delete',
7316 key = key('D')):
7317 '''Create a delete trait (VASSAL.counters.Delete)'''
7318 super(DeleteTrait,self).__init__()
7319 self.setType(name = name,
7320 key = key,
7321 dummy = '')
7322 self.setState()
7323
7324 Trait.known_traits.append(DeleteTrait)
7325
7326 #
7327 # EOF
7328 #
7329 # ====================================================================
7330 # From traits/sendto.py
7331
7332 # --------------------------------------------------------------------
7333 class SendtoTrait(Trait):
7334 ID = 'sendto'
7335 LOCATION = 'L'
7336 ZONE = 'Z'
7337 REGION = 'R'
7338 GRID = 'G'
7339 def __init__(self,
7340 mapName = '',
7341 boardName = '',
7342 name = '',
7343 key = key('E'),
7344 restoreName = 'Restore',
7345 restoreKey = key('R'),
7346 x = 200,
7347 y = 200,
7348 xidx = 0,
7349 yidx = 0,
7350 xoff = 1,
7351 yoff = 1,
7352 description = '',
7353 destination = LOCATION,
7354 zone = '',
7355 region = '',
7356 expression = '',
7357 position = ''):
7358 '''Create a send to trait (VASSAL.counter.SendToLocation)'''
7359 self.setType(name = name,# NAME
7360 key = key,# KEY , MODIFIER
7361 mapName = mapName,# MAP
7362 boardName = boardName,# BOARD
7363 x = x,
7364 y = y,# X ; Y
7365 restoreName = restoreName,# BACK
7366 restoreKey = restoreKey,# KEY , MODIFIER
7367 xidx = xidx,
7368 yidx = yidx,# XIDX ; YIDX
7369 xoff = xoff,
7370 yoff = yoff,# XOFF ; YOFF
7371 description = description,# DESC
7372 destination = destination,# DEST type
7373 zone = zone,# ZONE
7374 region = region,# REGION
7375 expression = expression,# EXPRESSION
7376 position = position) # GRIDPOS
7377 self.setState(backMap = '', backX = '', backY = '')
7378
7379 Trait.known_traits.append(SendtoTrait)
7380
7381 #
7382 # EOF
7383 #
7384 # ====================================================================
7385 # From traits/moved.py
7386
7387 # --------------------------------------------------------------------
7388 class MovedTrait(Trait):
7389 ID = 'markmoved'
7390 def __init__(self,
7391 image = 'moved.gif',
7392 xoff = 36,
7393 yoff = -38,
7394 name = 'Mark moved',
7395 key = key('M'),
7396 dummy = '' # Description
7397 # ignoreSame = True
7398 ):
7399 '''Create a moved trait (VASSAL.counters.MovementMarkable)'''
7400 super(MovedTrait,self).__init__()
7401 self.setType(image = image,
7402 xoff = xoff,
7403 yoff = yoff,
7404 name = name,
7405 key = key,
7406 dummy = dummy, # Description
7407 # ignoreSame = ignoreSame
7408 )
7409 self.setState(moved = False)
7410
7411 Trait.known_traits.append(MovedTrait)
7412
7413 #
7414 # EOF
7415 #
7416 # ====================================================================
7417 # From traits/skel.py
7418
7419
7420 #
7421 # EOF
7422 #
7423 # ====================================================================
7424 # From traits/submenu.py
7425
7426 # --------------------------------------------------------------------
7427 class SubMenuTrait(Trait):
7428 ID = 'submenu'
7429 def __init__(self,
7430 subMenu = '', # Title
7431 keys = [], # Keys
7432 description = ''):
7433 '''Create a sub menu (VASSAL.counters.SubMenu)'''
7434 self.setType(subMenu = subMenu, # CLONEKEY
7435 keys = ','.join([k.replace(',',r'\,')
7436 for k in keys]),
7437 description = description)
7438 self.setState() # PROPERTY COUNT (followed by [; KEY; VALUE]+)
7439 def setKeys(self,keys):
7440 '''Set the keys'''
7441 self['keys'] = ','.join([k.replace(',',r'\,') for k in keys])
7442
7443 Trait.known_traits.append(SubMenuTrait)
7444
7445 #
7446 # EOF
7447 #
7448 # ====================================================================
7449 # From traits/basic.py
7450
7451 # --------------------------------------------------------------------
7452 class BasicTrait(Trait):
7453 ID = 'piece'
7454 def __init__(self,
7455 name = '',
7456 filename = '', # Can be empty
7457 gpid = '', # Can be empty
7458 cloneKey = '', # Deprecated
7459 deleteKey = ''): # Deprecated
7460 '''Create a basic unit (VASSAL.counters.BasicPiece)'''
7461 self.setType(cloneKey = cloneKey, # CLONEKEY
7462 deleteKey = deleteKey, # DELETEKEY
7463 filename = filename, # IMAGE
7464 name = name) # NAME
7465 self.setState(map = 'null', # MAPID (possibly 'null')
7466 x = 0,
7467 y = 0,
7468 gpid = gpid,
7469 properties = 0) # PROPERTY COUNT (followed by [; KEY; VALUE]+)
7470
7471 Trait.known_traits.append(BasicTrait)
7472
7473 #
7474 # EOF
7475 #
7476 # ====================================================================
7477 # From traits/trigger.py
7478
7479 # --------------------------------------------------------------------
7480 class TriggerTrait(Trait):
7481 ID = 'macro'
7482 WHILE = 'while'
7483 UNTIL = 'until'
7484 COUNTED = 'counted' # - Always one "do ... while"
7485 def __init__(self,
7486 name = '',
7487 command = '', # Context menu name
7488 key = '', # Context menu key
7489 property = '', # Enable/Disable
7490 watchKeys = [],
7491 actionKeys = [], # What to do
7492 loop = False,
7493 preLoop = '', # Key
7494 postLoop = '', # Key
7495 loopType = COUNTED, # Loop type
7496 whileExpression = '',
7497 untilExpression = '',
7498 count = 0,
7499 index = False,
7500 indexProperty = '',
7501 indexStart = '',
7502 indexStep = ''):
7503 '''Create a layer trait (VASSAL.counter.Trigger)'''
7504 super(TriggerTrait,self).__init__()
7505 encWKeys = Trait.encodeKeys(watchKeys, ',')
7506 encAKeys = Trait.encodeKeys(actionKeys,',')
7507 self.setType(name = name,
7508 command = command, # Context menu name
7509 key = key, # Context menu key
7510 property = property, # Enable/Disable
7511 watchKeys = encWKeys,
7512 actionKeys = encAKeys, # What to do
7513 loop = loop,
7514 preLoop = preLoop, # Key
7515 postLoop = postLoop, # Key
7516 loopType = loopType, # Loop type
7517 whileExpression = whileExpression,
7518 untilExpression = untilExpression,
7519 count = count,
7520 index = index,
7521 indexProperty = indexProperty,
7522 indexStart = indexStart,
7523 indexStep = indexStep)
7524 self.setState(state='')
7525
7526 def getActionKeys(self):
7527 return Trait.decodeKeys(self['actionKeys'],',')
7528
7529 def getWatchKeys(self):
7530 return Trait.decodeKeys(self['watchKeys'],',')
7531
7532 def setActionKeys(self,keys):
7533 self['actionKeys'] = Trait.encodeKeys(keys,',')
7534
7535 def setWatchKeys(self,keys):
7536 self['watchKeys'] = Trait.encodeKeys(keys,',')
7537
7538
7539
7540 Trait.known_traits.append(TriggerTrait)
7541
7542 #
7543 # EOF
7544 #
7545 # ====================================================================
7546 # From traits/nonrect.py
7547
7548 # --------------------------------------------------------------------
7549 class NonRectangleTrait(Trait):
7550 ID = 'nonRect2'
7551 CLOSE = 'c'
7552 MOVETO = 'm'
7553 LINETO = 'l'
7554 CUBICTO = 'l'
7555 QUADTO = 'l'
7556 def __init__(self,
7557 scale = 1.,
7558 filename = '',
7559 path = [],
7560 image = None):
7561 '''Create a NonRectangle trait (static property)'''
7562 super(NonRectangleTrait,self).__init__()
7563 l = []
7564 if len(filename) > 0:
7565 l.append(f'n{filename}')
7566
7567 if len(path) <= 0:
7568 path = self.getShape(image)
7569
7570 if len(path) > 0:
7571 # print(path)
7572 l += [f'{p[0]},{int(p[1])},{int(p[2])}' if len(p) > 2 else p
7573 for p in path]
7574
7575 self.setType(scale = scale,
7576 code = ','.join(l))
7577 self.setState()
7578
7579 @classmethod
7580 def getShape(cls,buffer):
7581 if buffer is None:
7582 return []
7583
7584 from io import BytesIO
7585
7586 image = buffer
7587 if image[:5] == b'<?xml':
7588 from cairosvg import svg2png
7589 image = svg2png(image)
7590
7591 from PIL import Image
7592
7593 code = []
7594 with Image.open(BytesIO(image)) as img:
7595 alp = img.getchannel('A') # Alpha channel
7596 # Find least and largest non-transparent pixel in each row
7597 rows = []
7598 w = alp.width
7599 h = alp.height
7600 bb = alp.getbbox()
7601 for r in range(bb[1],bb[3]):
7602 ll, rr = bb[2], bb[0]
7603 for c in range(bb[0],bb[2]):
7604 if alp.getpixel((c,r)) != 0:
7605 ll = min(c,ll)
7606 rr = max(c,rr)
7607 rows += [[r-h//2,ll-w//2,rr-w//2]]
7608
7609 # Now produce the code - we start with the top line
7610 code = [(cls.MOVETO,rows[0][1],rows[0][0]-1),
7611 (cls.LINETO,rows[0][2],rows[0][0]-1)]
7612
7613 # Now loop down right side of image
7614 for c in rows:
7615 last = code[-1]
7616 if last[1] != c[2]:
7617 code += [(cls.LINETO, c[2], last[2])]
7618 code += [(cls.LINETO, c[2], c[0])]
7619
7620 # Now loop up left side of image
7621 for c in rows[::-1]:
7622 last = code[-1]
7623 if last[1] != c[1]:
7624 code += [(cls.LINETO,c[1],last[2])]
7625 code += [(cls.LINETO,c[1],c[0])]
7626
7627 # Terminate with close
7628 code += [(cls.CLOSE)]
7629
7630 return code
7631
7632
7633 Trait.known_traits.append(NonRectangleTrait)
7634
7635 #
7636 # EOF
7637 #
7638 # ====================================================================
7639 # From traits/click.py
7640
7641 # --------------------------------------------------------------------
7642 class ClickTrait(Trait):
7643 ID = 'button'
7644 def __init__(self,
7645 key = '',
7646 x = 0,
7647 y = 0,
7648 width = 0,
7649 height = 0,
7650 description = '',
7651 context = False,
7652 whole = True,
7653 version = 1,
7654 points = []):
7655 '''Create a click trait (static property)'''
7656 super(ClickTrait,self).__init__()
7657 self.setType(key = key,
7658 x = x,
7659 y = y,
7660 width = width,
7661 height = height,
7662 description = description,
7663 context = context,
7664 whole = whole,
7665 version = version,
7666 npoints = len(points),
7667 points = ';'.join([f'{p[0]};{p[1]}'
7668 for p in points]))
7669 self.setState()
7670
7671
7672 Trait.known_traits.append(ClickTrait)
7673
7674 #
7675 # EOF
7676 #
7677 # ====================================================================
7678 # From game.py
7679
7680 # --------------------------------------------------------------------
7681 class Game(Element):
7682 TAG = Element.BUILD+'GameModule'
7683 def __init__(self,build,node=None,
7684 name = '',
7685 version = '',
7686 ModuleOther1 = "",
7687 ModuleOther2 = "",
7688 VassalVersion = "3.6.7",
7689 description = "",
7690 nextPieceSlotId = 20):
7691 '''Create a new Game object
7692
7693 Parameters
7694 ----------
7695 build : xml.dom.Document
7696 root note
7697 node : xml.dom.Node
7698 To read from, or None
7699 name : str
7700 Name of module
7701 version : str
7702 Version of module
7703 ModuleOther1 : str
7704 Free form string
7705 ModuleOther2 : str
7706 Free form string
7707 VassalVersion : str
7708 VASSAL version this was created for
7709 description : str
7710 Speaks volumes
7711 nextPieceSlotId : int
7712 Starting slot ID.
7713 '''
7714 super(Game,self).__init__(build, self.TAG,
7715 node = node,
7716 name = name,
7717 version = version,
7718 ModuleOther1 = ModuleOther1,
7719 ModuleOther2 = ModuleOther2,
7720 VassalVersion = VassalVersion,
7721 description = description,
7722 nextPieceSlotId = nextPieceSlotId)
7723 def nextPieceSlotId(self):
7724 '''Increment next piece slot ID'''
7725 ret = int(self.getAttribute('nextPieceSlotId'))
7726 self.setAttribute('nextPieceSlotId',str(ret+1))
7727 return ret
7728 #
7729 def addBasicCommandEncoder(self,**kwargs):
7730 '''Add a `BasicCommandEncoder` element to this
7731
7732 Parameters
7733 ----------
7734 kwargs : dict
7735 Dictionary of attribute key-value pairs
7736
7737 Returns
7738 -------
7739 element : BasicCommandEncoder
7740 The added element
7741 '''
7742 return self.add(BasicCommandEncoder,**kwargs)
7743 def addGlobalTranslatableMessages(self,**kwargs):
7744 '''Add a `GlobalTranslatableMessages` element to this
7745
7746 Parameters
7747 ----------
7748 kwargs : dict
7749 Dictionary of attribute key-value pairs
7750
7751 Returns
7752 -------
7753 element : GlobalTranslatableMessages
7754 The added element
7755 '''
7756 return self.add(GlobalTranslatableMessages,**kwargs)
7757 def addPlayerRoster(self,**kwargs):
7758 '''Add a `PlayerRoster` element to this
7759
7760 Parameters
7761 ----------
7762 kwargs : dict
7763 Dictionary of attribute key-value pairs
7764
7765 Returns
7766 -------
7767 element : PlayerRoster
7768 The added element
7769 '''
7770 return self.add(PlayerRoster,**kwargs)
7771 def addChessClock(self,**kwargs):
7772 '''Add a `ChessClockControl` element to this
7773
7774 Parameters
7775 ----------
7776 kwargs : dict
7777 Dictionary of attribute key-value pairs
7778
7779 Returns
7780 -------
7781 element : PlayerRoster
7782 The added element
7783 '''
7784 return self.add(ChessClockControl,**kwargs)
7785 def addLanguage(self,**kwargs):
7786 '''Add a `Language` element to this
7787
7788 Parameters
7789 ----------
7790 kwargs : dict
7791 Dictionary of attribute key-value pairs
7792
7793 Returns
7794 -------
7795 element : Language
7796 The added element
7797 '''
7798 return self.add(Language,**kwargs)
7799 def addChatter(self,**kwargs):
7800 '''Add a `Chatter` element to this
7801
7802 Parameters
7803 ----------
7804 kwargs : dict
7805 Dictionary of attribute key-value pairs
7806
7807 Returns
7808 -------
7809 element : Chatter
7810 The added element
7811 '''
7812 return self.add(Chatter,**kwargs)
7813 def addKeyNamer(self,**kwargs):
7814 '''Add a `KeyNamer` element to this
7815
7816 Parameters
7817 ----------
7818 kwargs : dict
7819 Dictionary of attribute key-value pairs
7820
7821 Returns
7822 -------
7823 element : KeyNamer
7824 The added element
7825 '''
7826 return self.add(KeyNamer,**kwargs)
7827 def addNotes(self,**kwargs):
7828 '''Add a `Notes` element to this
7829
7830 Parameters
7831 ----------
7832 kwargs : dict
7833 Dictionary of attribute key-value pairs
7834
7835 Returns
7836 -------
7837 element : Notes
7838 The added element
7839 '''
7840 return self.add(Notes,**kwargs)
7841 def addLanguage(self,**kwargs):
7842 '''Add a `Language` element to this
7843
7844 Parameters
7845 ----------
7846 kwargs : dict
7847 Dictionary of attribute key-value pairs
7848
7849 Returns
7850 -------
7851 element : Language
7852 The added element
7853 '''
7854 return self.add(Language,**kwargs)
7855 def addChatter(self,**kwargs):
7856 '''Add a `Chatter` element to this
7857
7858 Parameters
7859 ----------
7860 kwargs : dict
7861 Dictionary of attribute key-value pairs
7862
7863 Returns
7864 -------
7865 element : Chatter
7866 The added element
7867 '''
7868 return self.add(Chatter,**kwargs)
7869 def addKeyNamer(self,**kwargs):
7870 '''Add a `KeyNamer` element to this
7871
7872 Parameters
7873 ----------
7874 kwargs : dict
7875 Dictionary of attribute key-value pairs
7876
7877 Returns
7878 -------
7879 element : KeyNamer
7880 The added element
7881 '''
7882 return self.add(KeyNamer,**kwargs)
7883 def addGlobalProperties(self,**kwargs):
7884 '''Add a `GlobalProperties` element to this
7885
7886 Parameters
7887 ----------
7888 kwargs : dict
7889 Dictionary of attribute key-value pairs
7890
7891 Returns
7892 -------
7893 element : GlobalProperties
7894 The added element
7895 '''
7896 return self.add(GlobalProperties,**kwargs)
7897 def addGlobalOptions(self,**kwargs):
7898 '''Add a `GlobalOptions` element to this
7899
7900 Parameters
7901 ----------
7902 kwargs : dict
7903 Dictionary of attribute key-value pairs
7904
7905 Returns
7906 -------
7907 element : GlobalOptions
7908 The added element
7909 '''
7910 return self.add(GlobalOptions,**kwargs)
7911 def addTurnTrack(self,**kwargs):
7912 '''Add a `TurnTrack` element to this
7913
7914 Parameters
7915 ----------
7916 kwargs : dict
7917 Dictionary of attribute key-value pairs
7918
7919 Returns
7920 -------
7921 element : TurnTrack
7922 The added element
7923 '''
7924 return self.add(TurnTrack,**kwargs)
7925 def addDocumentation(self,**kwargs):
7926 '''Add a `Documentation` element to this
7927
7928 Parameters
7929 ----------
7930 kwargs : dict
7931 Dictionary of attribute key-value pairs
7932
7933 Returns
7934 -------
7935 element : Documentation
7936 The added element
7937 '''
7938 return self.add(Documentation,**kwargs)
7939 def addPrototypes(self,**kwargs):
7940 '''Add a `Prototypes` element to this
7941
7942 Parameters
7943 ----------
7944 kwargs : dict
7945 Dictionary of attribute key-value pairs
7946
7947 Returns
7948 -------
7949 element : Prototypes
7950 The added element
7951 '''
7952 return self.add(Prototypes,**kwargs)
7953 def addPieceWindow(self,**kwargs):
7954 '''Add a `PieceWindow` element to this
7955
7956 Parameters
7957 ----------
7958 kwargs : dict
7959 Dictionary of attribute key-value pairs
7960
7961 Returns
7962 -------
7963 element : PieceWindow
7964 The added element
7965 '''
7966 return self.add(PieceWindow,**kwargs)
7967 def addChartWindow(self,**kwargs):
7968 '''Add a `ChartWindow` element to this
7969
7970 Parameters
7971 ----------
7972 kwargs : dict
7973 Dictionary of attribute key-value pairs
7974
7975 Returns
7976 -------
7977 element : ChartWindow
7978 The added element
7979 '''
7980 return self.add(ChartWindow,**kwargs)
7981 def addInventory(self,**kwargs):
7982 '''Add a `Inventory` element to this
7983
7984 Parameters
7985 ----------
7986 kwargs : dict
7987 Dictionary of attribute key-value pairs
7988
7989 Returns
7990 -------
7991 element : Inventory
7992 The added element
7993 '''
7994 return self.add(Inventory,**kwargs)
7995 def addMap(self,**kwargs):
7996 '''Add a `Map` element to this
7997
7998 Parameters
7999 ----------
8000 kwargs : dict
8001 Dictionary of attribute key-value pairs
8002
8003 Returns
8004 -------
8005 element : Map
8006 The added element
8007 '''
8008 return self.add(Map,**kwargs)
8009 def addDiceButton(self,**kwargs):
8010 '''Add a `DiceButton` element to this
8011
8012 Parameters
8013 ----------
8014 kwargs : dict
8015 Dictionary of attribute key-value pairs
8016
8017 Returns
8018 -------
8019 element : DiceButton
8020 The added element
8021 '''
8022 return self.add(DiceButton,**kwargs)
8023 def addPredefinedSetup(self,**kwargs):
8024 '''Add a `PredefinedSetup` element to this
8025
8026 Parameters
8027 ----------
8028 kwargs : dict
8029 Dictionary of attribute key-value pairs
8030
8031 Returns
8032 -------
8033 element : PredefinedSetup
8034 The added element
8035 '''
8036 return self.add(PredefinedSetup,**kwargs)
8037 def addGameMassKey(self,**kwargs):
8038 '''Add a `GameMassKey` element to this
8039
8040 Parameters
8041 ----------
8042 kwargs : dict
8043 Dictionary of attribute key-value pairs
8044
8045 Returns
8046 -------
8047 element : GameMassKey
8048 The added element
8049 '''
8050 return self.add(GameMassKey,**kwargs)
8051 def addStartupMassKey(self,**kwargs):
8052 '''Add a `StartupMassKey` element to this
8053
8054 Parameters
8055 ----------
8056 kwargs : dict
8057 Dictionary of attribute key-value pairs
8058
8059 Returns
8060 -------
8061 element : StartupMassKey
8062 The added element
8063 '''
8064 return self.add(StartupMassKey,**kwargs)
8065 def addMenu(self,**kwargs):
8066 '''Add a `Menu` element to this
8067
8068 Parameters
8069 ----------
8070 kwargs : dict
8071 Dictionary of attribute key-value pairs
8072
8073 Returns
8074 -------
8075 element : Menu
8076 The added element
8077 '''
8078 return self.add(Menu,**kwargs)
8079 def addSymbolicDice(self,**kwargs):
8080 '''Add a `SymbolicDice` element to this
8081
8082 Parameters
8083 ----------
8084 kwargs : dict
8085 Dictionary of attribute key-value pairs
8086
8087 Returns
8088 -------
8089 element : SymbolicDice
8090 The added element
8091 '''
8092 return self.add(SymbolicDice,**kwargs)
8093
8094
8095 # ----------------------------------------------------------------
8096 def getGlobalProperties(self,single=True):
8097 '''Get all or a sole `GlobalPropertie` element(s) from this
8098
8099 Parameters
8100 ----------
8101 single : bool
8102 If `True`, there can be only one `GlobalPropertie` child, otherwise fail.
8103 If `False` return all `GlobalPropertie` children in this element
8104
8105 Returns
8106 -------
8107 children : list
8108 List of `GlobalPropertie` children (even if `single=True`)
8109 '''
8110 return self.getAllElements(GlobalProperties,single)
8111 def getBasicCommandEncoder(self,single=True):
8112 '''Get all or a sole `Ba` element(s) from this
8113
8114 Parameters
8115 ----------
8116 single : bool
8117 If `True`, there can be only one `Ba` child, otherwise fail.
8118 If `False` return all `Ba` children in this element
8119
8120 Returns
8121 -------
8122 children : list
8123 List of `Ba` children (even if `single=True`)
8124 '''
8125 return self.getAllElements(BasicCommandEncoder,single)
8126 def getGlobalTranslatableMessages(self,single=True):
8127 '''Get all or a sole `GlobalTranslatableMessage` element(s) from this
8128
8129 Parameters
8130 ----------
8131 single : bool
8132 If `True`, there can be only one `GlobalTranslatableMessage` child, otherwise fail.
8133 If `False` return all `GlobalTranslatableMessage` children in this element
8134
8135 Returns
8136 -------
8137 children : list
8138 List of `GlobalTranslatableMessage` children (even if `single=True`)
8139 '''
8140 return self.getAllElements(GlobalTranslatableMessages,single)
8141 def getLanguages(self,single=False):
8142 '''Get all or a sole `Language` element(s) from this
8143
8144 Parameters
8145 ----------
8146 single : bool
8147 If `True`, there can be only one `Language` child, otherwise fail.
8148 If `False` return all `Language` children in this element
8149
8150 Returns
8151 -------
8152 children : list
8153 List of `Language` children (even if `single=True`)
8154 '''
8155 return self.getAllElements(Language,single)
8156 def getChessClocks(self,asdict=False):
8157 '''Get all or a sole `Language` element(s) from this
8158
8159 Parameters
8160 ----------
8161 single : bool
8162 If `True`, there can be only one `Language` child, otherwise fail.
8163 If `False` return all `Language` children in this element
8164
8165 Returns
8166 -------
8167 children : list
8168 List of `Language` children (even if `single=True`)
8169 '''
8170 return self.getElementsByKey(ChessClockControl,'name',asdict)
8171 def getChatter(self,single=True):
8172 '''Get all or a sole `Chatter` element(s) from this
8173
8174 Parameters
8175 ----------
8176 single : bool
8177 If `True`, there can be only one `Chatter` child, otherwise fail.
8178 If `False` return all `Chatter` children in this element
8179
8180 Returns
8181 -------
8182 children : list
8183 List of `Chatter` children (even if `single=True`)
8184 '''
8185 return self.getAllElements(Chatter,single)
8186 def getKeyNamer(self,single=True):
8187 '''Get all or a sole `KeyNamer` element(s) from this
8188
8189 Parameters
8190 ----------
8191 single : bool
8192 If `True`, there can be only one `KeyNamer` child, otherwise fail.
8193 If `False` return all `KeyNamer` children in this element
8194
8195 Returns
8196 -------
8197 children : list
8198 List of `KeyNamer` children (even if `single=True`)
8199 '''
8200 return self.getAllElements(KeyNamer,single)
8201 def getDocumentation(self,single=True):
8202 '''Get all or a sole `Documentation` element(s) from this
8203
8204 Parameters
8205 ----------
8206 single : bool
8207 If `True`, there can be only one `Documentation` child, otherwise fail.
8208 If `False` return all `Documentation` children in this element
8209
8210 Returns
8211 -------
8212 children : list
8213 List of `Documentation` children (even if `single=True`)
8214 '''
8215 return self.getAllElements(Documentation,single)
8216 def getPrototypes(self,single=True):
8217 '''Get all or a sole `Prototypes` (i.e., the containers of
8218 prototypes, not a list of actual prototypes) element(s) from
8219 this
8220
8221 Parameters
8222 ----------
8223 single : bool
8224 If `True`, there can be only one `Prototypes` child, otherwise fail.
8225 If `False` return all `Prototypes` children in this element
8226
8227 Returns
8228 -------
8229 children : list
8230 List of `Prototype` children (even if `single=True`)
8231
8232 '''
8233 return self.getAllElements(Prototypes,single)
8234 def getPlayerRoster(self,single=True):
8235 '''Get all or a sole `PlayerRo` element(s) from this
8236
8237 Parameters
8238 ----------
8239 single : bool
8240 If `True`, there can be only one `PlayerRo` child, otherwise fail.
8241 If `False` return all `PlayerRo` children in this element
8242
8243 Returns
8244 -------
8245 children : list
8246 List of `PlayerRo` children (even if `single=True`)
8247 '''
8248 return self.getAllElements(PlayerRoster,single)
8249 def getGlobalOptions(self,single=True):
8250 '''Get all or a sole `GlobalOption` element(s) from this
8251
8252 Parameters
8253 ----------
8254 single : bool
8255 If `True`, there can be only one `GlobalOption` child, otherwise fail.
8256 If `False` return all `GlobalOption` children in this element
8257
8258 Returns
8259 -------
8260 children : list
8261 List of `GlobalOption` children (even if `single=True`)
8262 '''
8263 return self.getAllElements(GlobalOptions,single)
8264 def getInventories(self,asdict=True):
8265 '''Get all Inventorie element(s) from this
8266
8267 Parameters
8268 ----------
8269 asdict : bool
8270 If `True`, return a dictonary that maps key to `Inventorie` elements. If `False`, return a list of all Inventorie` children.
8271
8272 Returns
8273 -------
8274 children : dict or list
8275 Dictionary or list of `Inventorie` children
8276 '''
8277 return self.getElementsByKey(Inventory,'name',single)
8278 def getPieceWindows(self,asdict=True):
8279 '''Get all PieceWindow element(s) from this
8280
8281 Parameters
8282 ----------
8283 asdict : bool
8284 If `True`, return a dictonary that maps key to `PieceWindow` elements. If `False`, return a list of all PieceWindow` children.
8285
8286 Returns
8287 -------
8288 children : dict or list
8289 Dictionary or list of `PieceWindow` children
8290 '''
8291 return self.getElementsByKey(PieceWindow,'name',asdict)
8292 def getChartWindows(self,asdict=True):
8293 '''Get all ChartWindow element(s) from this
8294
8295 Parameters
8296 ----------
8297 asdict : bool
8298 If `True`, return a dictonary that maps key to `ChartWindow` elements. If `False`, return a list of all ChartWindow` children.
8299
8300 Returns
8301 -------
8302 children : dict or list
8303 Dictionary or list of `ChartWindow` children
8304 '''
8305 return self.getElementsByKey(ChartWindow,'name',asdict)
8306 def getDiceButtons(self,asdict=True):
8307 '''Get all DiceButton element(s) from this
8308
8309 Parameters
8310 ----------
8311 asdict : bool
8312 If `True`, return a dictonary that maps key to `DiceButton` elements. If `False`, return a list of all DiceButton` children.
8313
8314 Returns
8315 -------
8316 children : dict or list
8317 Dictionary or list of `DiceButton` children
8318 '''
8319 return self.getElementsByKey(DiceButton,'name',asdict)
8320 def getPredefinedSetups(self,asdict=True):
8321 '''Get all PredefinedSetup element(s) from this
8322
8323 Parameters
8324 ----------
8325 asdict : bool
8326 If `True`, return a dictonary that maps key to `PredefinedSetup` elements. If `False`, return a list of all PredefinedSetup` children.
8327
8328 Returns
8329 -------
8330 children : dict or list
8331 Dictionary or list of `PredefinedSetup` children
8332 '''
8333 return self.getElementsByKey(PredefinedSetup,'name',asdict)
8334 def getNotes(self,single=True):
8335 '''Get all or a sole `Note` element(s) from this
8336
8337 Parameters
8338 ----------
8339 single : bool
8340 If `True`, there can be only one `Note` child, otherwise fail.
8341 If `False` return all `Note` children in this element
8342
8343 Returns
8344 -------
8345 children : list
8346 List of `Note` children (even if `single=True`)
8347 '''
8348 return self.getAllElements(Notes,single)
8349 def getTurnTracks(self,asdict=True):
8350 '''Get all TurnTrack element(s) from this
8351
8352 Parameters
8353 ----------
8354 asdict : bool
8355 If `True`, return a dictonary that maps key to `TurnTrack` elements. If `False`, return a list of all TurnTrack` children.
8356
8357 Returns
8358 -------
8359 children : dict or list
8360 Dictionary or list of `TurnTrack` children
8361 '''
8362 return self.getElementsByKey(TurnTrack,'name',asdict)
8363 def getPieces(self,asdict=False):
8364 '''Get all Piece element(s) from this
8365
8366 Parameters
8367 ----------
8368 asdict : bool
8369 If `True`, return a dictonary that maps key to `Piece` elements. If `False`, return a list of all Piece` children.
8370
8371 Returns
8372 -------
8373 children : dict or list
8374 Dictionary or list of `Piece` children
8375 '''
8376 return self.getElementsByKey(PieceSlot,'entryName',asdict)
8377 def getSpecificPieces(self,*names,asdict=False):
8378 '''Get all SpecificPiece element(s) from this
8379
8380 Parameters
8381 ----------
8382 asdict : bool
8383 If `True`, return a dictonary that maps key to `SpecificPiece` elements. If `False`, return a list of all SpecificPiece` children.
8384
8385 Returns
8386 -------
8387 children : dict or list
8388 Dictionary or list of `SpecificPiece` children
8389 '''
8390 return self.getSpecificElements(PieceSlot,'entryName',
8391 *names,asdict=asdict)
8392 def getMap(self,asdict=False):
8393 return self.getElementsByKey(Map,'mapName',asdict)
8394 def getWidgetMaps(self,asdict=True):
8395 '''Get all WidgetMap element(s) from this
8396
8397 Parameters
8398 ----------
8399 asdict : bool
8400 If `True`, return a dictonary that maps key to `WidgetMap` elements. If `False`, return a list of all WidgetMap` children.
8401
8402 Returns
8403 -------
8404 children : dict or list
8405 Dictionary or list of `WidgetMap` children
8406 '''
8407 return self.getElementsByKey(WidgetMap,'mapName',asdict=asdict)
8408 def getMaps(self,asdict=True):
8409 '''Get all Map element(s) from this
8410
8411 Parameters
8412 ----------
8413 asdict : bool
8414 If `True`, return a dictonary that maps key to `Map` elements. If `False`, return a list of all Map` children.
8415
8416 Returns
8417 -------
8418 children : dict or list
8419 Dictionary or list of `Map` children
8420 '''
8421 maps = self.getMap(asdict=asdict)
8422 wmaps = self.getWidgetMaps(asdict=asdict)
8423 if asdict:
8424 maps.update(wmaps)
8425 else:
8426 maps.extend(wmaps)
8427 return maps
8428 def getBoards(self,asdict=True):
8429 '''Get all Board element(s) from this
8430
8431 Parameters
8432 ----------
8433 asdict : bool
8434 If `True`, return a dictonary that maps key to `Board`
8435 elements. If `False`, return a list of all Board`
8436 children.
8437
8438
8439 Returns
8440 -------
8441 children : dict or list
8442 Dictionary or list of `Board` children
8443
8444 '''
8445 return self.getElementsByKey(Board,'name',asdict)
8446 def getGameMassKeys(self,asdict=True):
8447 '''Get all GameMassKey element(s) from this
8448
8449 Parameters
8450 ----------
8451 asdict : bool
8452 If `True`, return a dictonary that maps key to `Board`
8453 elements. If `False`, return a list of all Board`
8454 children.
8455
8456
8457 Returns
8458 -------
8459 children : dict or list
8460 Dictionary or list of `Board` children
8461
8462 '''
8463 return self.getElementsByKey(GameMassKey,'name',asdict)
8464 def getStartupMassKeys(self,asdict=True):
8465 '''Get all StartupMassKey element(s) from this
8466
8467 Parameters
8468 ----------
8469 asdict : bool
8470 If `True`, return a dictonary that maps key to `Board`
8471 elements. If `False`, return a list of all Board`
8472 children.
8473
8474
8475 Returns
8476 -------
8477 children : dict or list
8478 Dictionary or list of `Board` children
8479
8480 '''
8481 return self.getElementsByKey(StartupMassKey,'name',asdict)
8482 def getMenus(self,asdict=True):
8483 '''Get all Menu element(s) from this
8484
8485 Parameters
8486 ----------
8487 asdict : bool
8488 If `True`, return a dictonary that maps key to `Board`
8489 elements. If `False`, return a list of all Board`
8490 children.
8491
8492
8493 Returns
8494 -------
8495 children : dict or list
8496 Dictionary or list of `Board` children
8497
8498 '''
8499 return self.getElementsByKey(Menu,'text',asdict)
8500 def getSymbolicDices(self,asdict=True):
8501 '''Get all Menu element(s) from this
8502
8503 Parameters
8504 ----------
8505 asdict : bool
8506 If `True`, return a dictonary that maps key to `SymbolicDice`
8507 elements. If `False`, return a list of all `SymbolicDice`
8508 children.
8509
8510 Returns
8511 -------
8512 children : dict or list
8513 Dictionary or list of `SymbolicDice` children
8514
8515 '''
8516 return self.getElementsByKey(SymbolicDice,'name',asdict)
8517 def getAtStarts(self,single=False):
8518 '''Get all or a sole `AtStart` element(s) from this
8519
8520 Parameters
8521 ----------
8522 single : bool
8523 If `True`, there can be only one `AtStart` child, otherwise fail.
8524 If `False` return all `AtStart` children in this element
8525
8526 Returns
8527 -------
8528 children : list
8529 List of `AtStart` children (even if `single=True`)
8530 '''
8531 return self.getAllElements(AtStart,single)
8532
8533 registerElement(Game)
8534
8535 # --------------------------------------------------------------------
8536 class BasicCommandEncoder(GameElement):
8537 TAG = Element.MODULE+'BasicCommandEncoder'
8538 def __init__(self,doc,node=None):
8539 super(BasicCommandEncoder,self).__init__(doc,self.TAG,node=node)
8540
8541 registerElement(BasicCommandEncoder)
8542
8543 #
8544 # EOF
8545 #
8546 # ====================================================================
8547 # From buildfile.py
8548
8549 # --------------------------------------------------------------------
8550 class BuildFile(Element):
8551 def __init__(self,root=None):
8552 '''Construct from a DOM object, if given, otherwise make new'''
8553 from xml.dom.minidom import Document
8554 super(BuildFile,self).__init__(None,'',None)
8555
8556 self._root = root
8557 if self._root is None:
8558 self._root = Document()
8559
8560 self._node = self._root
8561
8562 def addGame(self,**kwargs):
8563 '''Add a `Game` element to this
8564
8565 Parameters
8566 ----------
8567 kwargs : dict
8568 Dictionary of attribute key-value pairs
8569
8570 Returns
8571 -------
8572 element : Game
8573 The added element
8574 '''
8575 return Game(self,**kwargs)
8576
8577 def getGame(self):
8578 '''Get the `Game`'''
8579 return Game(self,
8580 node=self._root.\
8581 getElementsByTagName('VASSAL.build.GameModule')[0])
8582
8583 def encode(self):
8584 '''Encode into XML'''
8585 return self._root.toprettyxml(indent=' ',
8586 encoding="UTF-8",
8587 standalone=False)
8588
8589
8590 #
8591 # EOF
8592 #
8593 # ====================================================================
8594 # From moduledata.py
8595
8596 # --------------------------------------------------------------------
8597 class Data(Element):
8598 TAG = 'data'
8599 def __init__(self,doc,node=None,version='1'):
8600 super(Data,self).__init__(doc,self.TAG,node=node,version=version)
8601
8602 def addVersion(self,**kwargs):
8603 '''Add a `Version` element to this
8604
8605 Parameters
8606 ----------
8607 kwargs : dict
8608 Dictionary of attribute key-value pairs
8609
8610 Returns
8611 -------
8612 element : Version
8613 The added element
8614 '''
8615 return self.add(Version,**kwargs)
8616 def addVASSALVersion(self,**kwargs):
8617 '''Add a `VASSALVersion` element to this
8618
8619 Parameters
8620 ----------
8621 kwargs : dict
8622 Dictionary of attribute key-value pairs
8623
8624 Returns
8625 -------
8626 element : VASSALVersion
8627 The added element
8628 '''
8629 return self.add(VASSALVersion,**kwargs)
8630 def addName(self,**kwargs):
8631 '''Add a `Name` element to this
8632
8633 Parameters
8634 ----------
8635 kwargs : dict
8636 Dictionary of attribute key-value pairs
8637
8638 Returns
8639 -------
8640 element : Name
8641 The added element
8642 '''
8643 return self.add(Name,**kwargs)
8644 def addDescription(self,**kwargs):
8645 '''Add a `Description` element to this
8646
8647 Parameters
8648 ----------
8649 kwargs : dict
8650 Dictionary of attribute key-value pairs
8651
8652 Returns
8653 -------
8654 element : Description
8655 The added element
8656 '''
8657 return self.add(Description,**kwargs)
8658 def addDateSaved(self,**kwargs):
8659 '''Add a `DateSaved` element to this
8660
8661 Parameters
8662 ----------
8663 kwargs : dict
8664 Dictionary of attribute key-value pairs
8665
8666 Returns
8667 -------
8668 element : DateSaved
8669 The added element
8670 '''
8671 return self.add(DateSaved,**kwargs)
8672 def getVersion(self,single=True):
8673 '''Get all or a sole `Version` element(s) from this
8674
8675 Parameters
8676 ----------
8677 single : bool
8678 If `True`, there can be only one `Version` child, otherwise fail.
8679 If `False` return all `Version` children in this element
8680
8681 Returns
8682 -------
8683 children : list
8684 List of `Version` children (even if `single=True`)
8685 '''
8686 return self.getAllElements(Version,single=single)
8687 def getVASSALVersion(self,single=True):
8688 '''Get all or a sole `VASSALVersion` element(s) from this
8689
8690 Parameters
8691 ----------
8692 single : bool
8693 If `True`, there can be only one `VASSALVersion` child,
8694 otherwise fail. If `False` return all `VASSALVersion`
8695 children in this element
8696
8697 Returns
8698 -------
8699 children : list
8700 List of `VASSALVersion` children (even if `single=True`)
8701
8702 '''
8703 return self.getAllElements(VASSALVersion,single=single)
8704 def getName(self,single=True):
8705 return self.getAllElements(Name,single=single)
8706 def getDescription(self,single=True):
8707 '''Get all or a sole `Description` element(s) from this
8708
8709 Parameters
8710 ----------
8711 single : bool
8712 If `True`, there can be only one `Description` child,
8713 otherwise fail. If `False` return all `De` children in
8714 this element
8715
8716 Returns
8717 -------
8718 children : list
8719 List of `De` children (even if `single=True`)
8720
8721 '''
8722 return self.getAllElements(Description,single=single)
8723 def getDateSaved(self,single=True):
8724 '''Get all or a sole `DateSaved` element(s) from this
8725
8726 Parameters
8727 ----------
8728 single : bool
8729 If `True`, there can be only one `DateSaved` child, otherwise fail.
8730 If `False` return all `DateSaved` children in this element
8731
8732 Returns
8733 -------
8734 children : list
8735 List of `DateSaved` children (even if `single=True`)
8736 '''
8737 return self.getAllElements(DateSaved,single=single)
8738
8739 # --------------------------------------------------------------------
8740 class DataElement(Element):
8741 def __init__(self,data,tag,node=None,**kwargs):
8742 super(DataElement,self).__init__(data,tag,node=node,**kwargs)
8743
8744 def getData(self):
8745 return self.getParent(Data)
8746
8747 # --------------------------------------------------------------------
8748 class Version(DataElement):
8749 TAG = 'version'
8750 def __init__(self,data,node=None,version=''):
8751 super(Version,self).__init__(data,self.TAG,node=node)
8752 if node is None:
8753 self.addText(version)
8754
8755 # --------------------------------------------------------------------
8756 class VASSALVersion(DataElement):
8757 TAG = 'VassalVersion'
8758 def __init__(self,data,node=None,version='3.6.7'):
8759 super(VASSALVersion,self).__init__(data,self.TAG,node=node)
8760 if node is None:
8761 self.addText(version)
8762
8763 # --------------------------------------------------------------------
8764 class Name(DataElement):
8765 TAG = 'name'
8766 def __init__(self,data,node=None,name=''):
8767 super(Name,self).__init__(data,self.TAG,node=node)
8768 if node is None:
8769 self.addText(name)
8770
8771 # --------------------------------------------------------------------
8772 class Description(DataElement):
8773 TAG = 'description'
8774 def __init__(self,data,node=None,description=''):
8775 super(Description,self).__init__(data,self.TAG,node=node)
8776 if node is None:
8777 self.addText(description)
8778
8779 # --------------------------------------------------------------------
8780 class DateSaved(DataElement):
8781 TAG = 'dateSaved'
8782 def __init__(self,data,node=None,milisecondsSinceEpoch=-1):
8783 super(DateSaved,self).__init__(data,self.TAG,node=node)
8784 if node is None:
8785 from time import time
8786 s = f'{int(time()*1000)}' if milisecondsSinceEpoch < 0 else \
8787 str(milisecondsSinceEpoch)
8788 self.addText(s)
8789
8790 # --------------------------------------------------------------------
8791 class ModuleData(Element):
8792
8793 def __init__(self,root=None):
8794 '''Construct from a DOM object, if given, otherwise make new'''
8795 from xml.dom.minidom import Document
8796 super(ModuleData,self).__init__(None,'',None)
8797
8798 self._root = root
8799 if self._root is None:
8800 self._root = Document()
8801
8802 self._node = self._root
8803
8804 def addData(self,**kwargs):
8805 '''Add a `Data` element to this
8806
8807 Parameters
8808 ----------
8809 kwargs : dict
8810 Dictionary of attribute key-value pairs
8811
8812 Returns
8813 -------
8814 element : Data
8815 The added element
8816 '''
8817 return Data(self,**kwargs)
8818
8819 def getData(self):
8820 return Data(self,
8821 node=self._root.getElementsByTagName(Data.TAG)[0])
8822
8823 def encode(self):
8824 return self._root.toprettyxml(indent=' ',
8825 encoding="UTF-8",
8826 standalone=False)
8827
8828 #
8829 # EOF
8830 #
8831 # ====================================================================
8832 # From save.py
8833
8834 # ====================================================================
8835 class SaveIO:
8836 '''Wrapper around a save file
8837
8838 Save file is
8839
8840 "!VCSK" KEY content
8841
8842 Key is two bytes drawn as a random number in 0-255. Content is
8843 two bytes per character. Content characters are encoded with the
8844 random key.
8845
8846 Save file (.vsav) content is
8847
8848 "begin_save" ESC
8849 "\" ESC
8850 [commands]* ESC
8851 "PLAYER" name password side ESC
8852 [map+"BoardPicker" name x y ESC]+
8853 "SETUP_STACK" ESC
8854 "TURN"+name state ESC
8855 "end_save"
8856
8857 Commands are
8858
8859 "+/" id "/" body "\"
8860
8861 where body are
8862
8863 "stack" "/" mapName ; x ; y ; ids "\"
8864 piece_type "/" piece_state (x and y set here too) "\"
8865
8866 x and y are pixel coordinates (sigh!). This means we have to know
8867
8868 - the pixel location of a hex
8869 - the hex coordinates of that hex
8870 - whether rows and columns are descending
8871 - if even hexes are higher or not
8872
8873 The two first items _must_ be user supplied (I think). When we
8874 add stacks or pieces, we must then get the numerical hex
8875 coordinates - not what the user specified in the VASSAL editor or
8876 the like. Of course, this means opening the module before writing
8877 the patch.py script.
8878
8879 It seems like every piece is added in a stack.
8880
8881 The id is a numerical value. Rather big (e.g., 1268518000806). It
8882 is the current number of miliseconds since epoch, with offset to
8883 disambiguate.
8884
8885 The ID is the current time, taken from a milisecond clock,
8886 possibly adjusted up if there is a clash. This is all managed by
8887 the GameState class.
8888
8889 '''
8890 VCS_HEADER = b'!VCSK'
8891 VK_ESC = chr(27)
8892 DEC_MAP = {
8893 # 0-9
8894 0x30: 0x30,
8895 0x31: 0x30,
8896 0x32: 0x30,
8897 0x33: 0x30,
8898 0x34: 0x30,
8899 0x35: 0x30,
8900 0x36: 0x30,
8901 0x37: 0x30,
8902 0x38: 0x30,
8903 0x39: 0x30,
8904 # A-F
8905 0x41: 0x37,
8906 0x42: 0x37,
8907 0x43: 0x37,
8908 0x44: 0x37,
8909 0x45: 0x37,
8910 0x46: 0x37,
8911 # a-f
8912 0x61: 0x57,
8913 0x62: 0x57,
8914 0x63: 0x57,
8915 0x64: 0x57,
8916 0x65: 0x57,
8917 0x66: 0x57
8918 }
8919 ENC_MAP = [b'0',b'1',b'2',b'3',b'4',b'5',b'6',b'7',b'8',b'9',
8920 b'a',b'b',b'c',b'd',b'e',b'f']
8921
8922 # ----------------------------------------------------------------
8923 @classmethod
8924 def decHex(cls,b):
8925 '''Decode a single char into a number
8926
8927 If the encoded number is b, then the decoded number is
8928
8929 b - off
8930
8931 where off is an offset that depends on b
8932
8933 off = 0x30 if 0x30 <= b <= 0x39
8934 0x37 if 0x41 <= b <= 0x46
8935 0x57 if 0x61 <= b <= 0x66
8936 '''
8937 return b - cls.DEC_MAP[b]
8938 # --------------------------------------------------------------------
8939 @classmethod
8940 def readByte(cls,inp,key):
8941 '''Read a single byte of information from input stream
8942
8943 Two characters (c1 and c2) are read from input stream, and the
8944 decoded byte is then
8945
8946 ((dechex(c1) << 4 | dechex(c2)) ^ key) & 0xFF
8947
8948 Parameters
8949 ----------
8950 inp : stream
8951 Input to read from
8952 key : int
8953 Key to decode the input
8954
8955 Returns
8956 -------
8957 b : int
8958 The read byte
8959 '''
8960 try:
8961 pair = inp.read(2)
8962 except Exception as e:
8963 from sys import stderr
8964 print(e,file=stderr)
8965 return None
8966
8967 if len(pair) < 2:
8968 return None
8969
8970 return ((cls.decHex(pair[0]) << 4 | cls.decHex(pair[1])) ^ key) & 0xFF
8971 # --------------------------------------------------------------------
8972 @classmethod
8973 def readSave(cls,file,alsometa=False):
8974 '''Read data from save file. The data is read into lines
8975 returned as a list.
8976
8977 '''
8978 from zipfile import ZipFile
8979
8980 # We open the save file as a zip file
8981 with ZipFile(file,'r') as z:
8982 # open the save file in the archive
8983 save = z.open('savedGame','r')
8984
8985 # First, we check the header
8986 head = save.read(len(cls.VCS_HEADER))
8987 assert head == cls.VCS_HEADER, \
8988 f'Read header {head} is not {cls.VCS_HEADER}'
8989
8990 # Then, read the key
8991 pair = save.read(2)
8992 key = (cls.decHex(pair[0]) << 4 | cls.decHex(pair[1]))
8993
8994 # Now read content, one byte at a time
8995 content = ''
8996 while True:
8997 byte = cls.readByte(save,key)
8998 if byte is None:
8999 break
9000
9001 # Convert byte to character
9002 content += chr(byte)
9003
9004 lines = content.split(cls.VK_ESC)
9005
9006 if alsometa:
9007 savedata = z.read(VSav.SAVE_DATA)
9008 moduledata = z.read(VMod.MODULE_DATA)
9009
9010 if not alsometa:
9011 return key, lines
9012
9013 return key,lines,savedata,moduledata
9014
9015 # --------------------------------------------------------------------
9016 @classmethod
9017 def writeByte(cls,out,byte,key):
9018 '''Write a single byte
9019
9020 Parameters
9021 ----------
9022 out : IOStream
9023 Stream to write to
9024 byte : char
9025 Single byte to write
9026 key : int
9027 Key to encode with (defaults to 0xAA - alternating 0's and 1's)
9028 '''
9029 b = ord(byte) ^ key
9030 pair = cls.ENC_MAP[(b & 0xF0) >> 4], cls.ENC_MAP[b & 0x0F]
9031 out.write(pair[0])
9032 out.write(pair[1])
9033
9034 # --------------------------------------------------------------------
9035 @classmethod
9036 def writeInZip(cls,z,key,lines,filename='savedGame'):
9037 '''Write a save file in a zip file (VMod)'''
9038 # open the save file in the archive
9039 with z.open(filename,'w') as save:
9040 # Write header
9041 save.write(cls.VCS_HEADER)
9042
9043 # Split key
9044 pair = cls.ENC_MAP[(key & 0xF0) >> 4], cls.ENC_MAP[(key & 0x0F)]
9045 save.write(pair[0])
9046 save.write(pair[1])
9047
9048 # Form content
9049 content = cls.VK_ESC.join(lines)
9050
9051 # Write each character as two
9052 for c in content:
9053 cls.writeByte(save, c, key)
9054
9055 # --------------------------------------------------------------------
9056 @classmethod
9057 def writeSave(cls,file,key,lines,savedata=None,moduledata=None):
9058 '''Write a save file'''
9059 from zipfile import ZipFile, ZIP_DEFLATED
9060
9061 # We open the save file as a zip file
9062 with ZipFile(file,'w',ZIP_DEFLATED) as z:
9063 cls.writeInZip(z,key,lines,filename='savedGame')
9064
9065 if savedata is not None:
9066 z.writestr(VSav.SAVE_DATA,savedata)
9067 z.writestr(VMod.MODULE_DATA,moduledata)
9068
9069 # ====================================================================
9070 #
9071 # VSave file
9072 #
9073 class SaveFile:
9074 def __init__(self,game,firstid=None):
9075 '''Creates a save file to add positions to'''
9076 from time import time
9077 self._game = game
9078 self._counters = {}
9079 self._stacks = {}
9080 self._pieces = self._game.getPieces(asdict=True)
9081 self._nextId = (int(time()*1000) - 360000
9082 if firstid is None else firstid)
9083
9084 def add(self,grid,**kwargs):
9085 '''Add pieces to the save.
9086
9087 Parameters
9088 ----------
9089 grid : BaseGrid
9090 Grid to add pieces to
9091 kwargs : dict
9092 Either a map from piece name to hex position,
9093 Or a map from hex position to list of pieces
9094 '''
9095 for k,v in kwargs.items():
9096 # print('Add to save',k,v)
9097 self._add(grid,k,v)
9098
9099 def _add(self,grid,k,v):
9100 '''Add to the save'''
9101 # print(f'Adding {k} -> {v}')
9102 loc = None
9103 piece = self._pieces.get(k,None)
9104 pieces = []
9105 boardName = grid.getBoard()['name']
9106 # print(f'Board name: {boardName}')
9107 if piece is not None:
9108 # print(f'Key is piece: {k}->{piece}')
9109 pieces.append(piece)
9110 loc = v
9111 else:
9112 # Key is not a piece name, so a location
9113 loc = k
9114 # Convert value to iterable
9115 try:
9116 iter(v)
9117 except:
9118 v = list(v)
9119
9120 for vv in v:
9121 if isinstance(vv,PieceSlot):
9122 pieces.append(vv)
9123 continue
9124 if isinstance(vv,str):
9125 piece = self._pieces.get(vv,None)
9126 if piece is None:
9127 continue
9128 pieces.append(piece)
9129
9130 # print(f'Loc: {loc}')
9131 if len(pieces) < 1:
9132 return
9133
9134 if (boardName,loc) not in self._stacks:
9135 # print(f'Adding stack {boardName},{loc}')
9136 coord = grid.getLocation(loc)
9137 if coord is None:
9138 print(f'did not get coordinates from {loc}')
9139 return
9140 self._stacks[(boardName,loc)] = {
9141 'x': coord[0],
9142 'y': coord[1],
9143 'pids': [] }
9144
9145 place = self._stacks[(boardName,loc)]
9146 for piece in pieces:
9147 name = piece['entryName']
9148 count = self._counters.get(name,None)
9149
9150 if count is None:
9151 count = {'pid': self._nextId,
9152 'piece': piece,
9153 'board': boardName,
9154 'x': place['x'],
9155 'y': place['y'],
9156 }
9157 self._counters[name] = count
9158 self._nextId += 1
9159
9160
9161 # print(f'Adding to stack {boardName},{loc}: {count[0]}')
9162 place['pids'].append(count['pid'])
9163
9164 def getLines(self):
9165 '''Get the final lines of code'''
9166 key = 0xAA # fixed key
9167
9168 lines = ['begin_save',
9169 '',
9170 '\\']
9171
9172 self._pieceLines(lines)
9173 self._otherLines(lines)
9174
9175 lines.append('end_save')
9176 return lines
9177
9178 def _pieceLines(self,lines):
9179 '''Add piece lines to save file
9180
9181 Parameters
9182 ----------
9183 lines : list
9184 The lines to add
9185 '''
9186 # print(self._counters)
9187 for counter in self._counters.values():
9188 iden = counter['pid']
9189 piece = counter['piece']
9190 traits = piece.getTraits()
9191 traits = Trait.flatten(traits,self._game)
9192 # Get last - trait (basic piece), and modify coords
9193 basic = traits[-1]
9194 basic['map'] = counter['board']
9195 basic['x'] = counter['x']
9196 basic['y'] = counter['y']
9197 # Set old location if possible
9198 parent = piece.getParent(DummyElement,checkTag=False)
9199 if parent is not None and parent._node.nodeName == AtStart.TAG:
9200 oldLoc = parent['location']
9201 oldBoard = parent['owningBoard']
9202 oldMap = self._game.getBoards()[oldBoard].getMap()['mapName']
9203 oldX = parent['x']
9204 oldY = parent['y']
9205 oldZone = None
9206 zones = self._game.getBoards()[oldBoard].getZones()
9207 for zone in zones.values():
9208 grid = zone.getGrids()[0]
9209 if grid is None: continue
9210
9211 coord = grid.getLocation(oldLoc)
9212 if coord is None: continue
9213
9214 oldZone = zone['name']
9215 oldX = coord[0]
9216 oldY = coord[1]
9217 break
9218
9219 if oldZone is not None:
9220 basic['properties'] = \
9221 f'6;OldZone;{oldZone};OldLocationName;{oldLoc};'+\
9222 f'OldX;{oldX};OldY;{oldY};'+\
9223 f'OldBoard;{oldBoard};OldMap;{oldMap}'
9224 else:
9225 basic['properties'] = \
9226 f'5;OldLocationName;{oldLoc};'+\
9227 f'OldX;{oldX};OldY;{oldY};'+\
9228 f'6;OldBoard;{oldBoard};OldMap;{oldMap}'
9229
9230 for trait in traits:
9231 if trait.ID == TrailTrait.ID:
9232 trait['map'] = oldMap
9233 trait['points'] = f'1;{oldX},{oldY}'
9234 trait['init'] = True
9235
9236 # Wrapper
9237 wrap = DummyWithTraits(self._game,traits=[])
9238 wrap.setTraits(*traits,iden=str(iden))
9239 lines.append(wrap._node.childNodes[0].nodeValue+'\\')
9240
9241 layer = -1
9242 for key,dat in self._stacks.items():
9243 pids = dat.get('pids',None)
9244 x = dat['x']
9245 y = dat['y']
9246 if pids is None or len(pids) < 1:
9247 print(f'No pieces at {key[0]},{key[1]}')
9248 continue
9249
9250 iden = self._nextId
9251 self._nextId += 1
9252 stack = StackTrait(board=key[0],x=x,y=y,pieceIds=pids,layer=layer)
9253 layer = 1
9254 wrap = DummyWithTraits(self._game,traits=[])
9255 wrap.setTraits(stack,iden=iden)
9256 lines.append(wrap._node.childNodes[0].nodeValue+'\\')
9257
9258 def _otherLines(self,lines):
9259 '''Add other lines to save'''
9260 lines.append('UNMASK\tnull')
9261 for r in self._game.getPlayerRoster():
9262 lines.extend(r.encode())
9263 for n in self._game.getNotes(single=False):
9264 lines.extend(n.encode())
9265 setupStack = False
9266 for m in self._game.getMaps(asdict=False):
9267 for bp in m.getBoardPicker(single=False):
9268 lines.extend(bp.encode())
9269 if not setupStack:
9270 atstart = m.getAtStarts(single=False)
9271 if atstart and len(atstart) > 0:
9272 lines.append('SETUP_STACK')
9273 setupStack = True
9274
9275 # for tk,tt in self._game.getTurnTracks(asdict=True):
9276 # lines.extend(tt.encode())
9277
9278
9279 # --------------------------------------------------------------------
9280 class SaveData(ModuleData):
9281 def __init__(self,root=None):
9282 '''Convinience wrapper'''
9283 super(SaveData,self).__init__(root=root)
9284 # ====================================================================
9285 # From vsav.py
9286
9287 # --------------------------------------------------------------------
9288 class VSav:
9289 SAVE_DATA = 'savedata'
9290
9291 def __init__(self,build,vmod):
9292 '''Create a VASSAL save file programmatically
9293
9294 Parameters
9295 ----------
9296 build : xml.dom.Document
9297 `buildFile.xml` as XML
9298 vmod : VMod
9299 Module file
9300 '''
9301 from time import time
9302 self._vmod = vmod
9303 self._game = build.getGame()
9304 self._start = int(time()*1000)
9305
9306
9307 def createSaveData(self,description=None):
9308 '''Create `savedgame`'''
9309 desc = (self._game['description']
9310 if description is None else description)
9311 self._saveData = SaveData(root=None)
9312 data = self._saveData.addData()
9313 data.addVersion (version =self._game['version'])
9314 data.addVASSALVersion(version =self._game['VassalVersion'])
9315 data.addDescription (description=desc)
9316 data.addDateSaved (milisecondsSinceEpoch=self._start)
9317 return self._saveData
9318
9319 def createModuleData(self):
9320 '''Create `moduleData`'''
9321 self._moduleData = ModuleData()
9322 data = self._moduleData.addData()
9323 data.addVersion (version =self._game['version'])
9324 data.addVASSALVersion(version =self._game['VassalVersion'])
9325 data.addName (name =self._game['name'])
9326 data.addDescription (description=self._game['description'])
9327 data.addDateSaved (milisecondsSinceEpoch=self._start)
9328 return self._moduleData
9329
9330 def addSaveFile(self):
9331 '''Add a save file to the module
9332
9333 Returns
9334 -------
9335 vsav : SaveFile
9336 Save file to add content to
9337 '''
9338 self._saveFile = SaveFile(game=self._game,firstid=self._start)
9339 return self._saveFile
9340
9341 def run(self,savename='Save.vsav',description=None):
9342 '''Run this to generate the save file
9343
9344 Parameters
9345 ----------
9346 savename : str
9347 Name of save file to write
9348 description : str
9349 Short description of the save file
9350 '''
9351 from zipfile import ZipFile, ZIP_DEFLATED
9352
9353 self.createSaveData(description=description)
9354 self.createModuleData()
9355
9356 with self._vmod.getInternalFile(savename,'w') as vsav:
9357 with ZipFile(vsav,'w',ZIP_DEFLATED) as zvsav:
9358 # The key is set to 0xAA (alternating ones and zeros)
9359 SaveIO.writeInZip(zvsav,0xAA,self._saveFile.getLines())
9360
9361 zvsav.writestr(VMod.MODULE_DATA, self._moduleData.encode())
9362 zvsav.writestr(VSav.SAVE_DATA, self._saveData.encode())
9363
9364 #
9365 # EOF
9366 #
9367 # ====================================================================
9368 # From vmod.py
9369 # ====================================================================
9370 #
9371 # Wrapper around a module
9372 #
9373 class VMod:
9374 BUILD_FILE = 'buildFile.xml'
9375 MODULE_DATA = 'moduledata'
9376
9377 def __init__(self,filename,mode):
9378 '''Interface to VASSAL Module (a Zip file)'''
9379 self._mode = mode
9380 self._vmod = self._open(filename,mode)
9381
9382 def __enter__(self):
9383 '''Enter context'''
9384 return self
9385
9386 def __exit__(self,*e):
9387 '''Exit context'''
9388 self._vmod.close()
9389 return None
9390
9391 def _open(self,filename,mode):
9392 '''Open a file in VMod'''
9393 from zipfile import ZipFile, ZIP_DEFLATED
9394
9395 return ZipFile(filename,mode,compression=ZIP_DEFLATED)
9396
9397 def removeFiles(self,*filenames):
9398 '''Open a temporary zip file, and copy content from there to
9399 that file, excluding filenames mentioned in the arguments.
9400 Then close current file, rename the temporary file to this,
9401 and reopen in 'append' mode. The deleted files are returned
9402 as a dictionary.
9403
9404 Parameters
9405 ----------
9406 filenames : tuple
9407 List of files to remove from the VMOD
9408
9409 Returns
9410 -------
9411 files : dict
9412 Dictionary from filename to content of the removed files.
9413
9414 Note, the VMOD is re-opened in append mode after this
9415 '''
9416 from tempfile import mkdtemp
9417 from zipfile import ZipFile
9418 from shutil import move, rmtree
9419 from os import path
9420
9421 tempdir = mkdtemp()
9422 ret = {}
9423
9424 try:
9425 tempname = path.join(tempdir, 'new.zip')
9426 with self._open(tempname, 'w') as tmp:
9427
9428 for item in self._vmod.infolist():
9429 data = self._vmod.read(item.filename)
9430
9431 if item.filename not in filenames:
9432 tmp.writestr(item, data)
9433 else:
9434 ret[item.filename] = data
9435
9436 name = self._vmod.filename
9437 self._vmod.close()
9438 move(tempname, name)
9439
9440 self._mode = 'a'
9441 self._vmod = self._open(name,'a')
9442 finally:
9443 rmtree(tempdir)
9444
9445 # Return the removed files
9446 return ret
9447
9448 def fileName(self):
9449 '''Get name of VMod file'''
9450 return self._vmod.filename
9451
9452 def replaceFiles(self,**files):
9453 '''Replace existing files with new files
9454
9455 Parameters
9456 ----------
9457 files : dict
9458 Dictionary that maps file name to content
9459 '''
9460 self.removeFiles(*list(files.keys()))
9461
9462 self.addFiles(**files);
9463
9464 def addFiles(self,**files):
9465 '''Add a set of files to this
9466
9467 Parameters
9468 ----------
9469 files : dict
9470 Dictionary that maps file name to content.
9471 '''
9472 for filename,data in files.items():
9473 self.addFile(filename,data)
9474
9475 def addFile(self,filename,content):
9476 '''Add a file to this
9477
9478 Parameters
9479 ----------
9480 filename : str
9481 File name in module
9482 content : str
9483 File content
9484
9485 Returns
9486 -------
9487 element : File
9488 The added element
9489 '''
9490 self._vmod.writestr(filename,content)
9491
9492 def addExternalFile(self,filename,target=None):
9493 '''Add an external file element to this
9494
9495 Parameters
9496 ----------
9497 kwargs : dict
9498 Dictionary of attribute key-value pairs
9499
9500 Returns
9501 -------
9502 element : ExternalFile
9503 The added element
9504 '''
9505 if target is None: target = filename
9506 self._vmod.write(filename,target)
9507
9508 def getFileNames(self):
9509 '''Get all filenames in module'''
9510 return self._vmod.namelist()
9511
9512 def getFileMapping(self):
9513 '''Get mapping from short name to full archive name'''
9514 from pathlib import Path
9515
9516 names = self.getFileNames()
9517
9518 return {Path(p).stem: str(p) for p in names}
9519
9520 def getFiles(self,*filenames):
9521 '''Return named files as a dictionary.
9522
9523 Parameters
9524 ----------
9525 filenames : tuple
9526 The files to get
9527
9528 Returns
9529 -------
9530 files : dict
9531 Mapping of file name to file content
9532 '''
9533 fn = self.getFileNames()
9534 ret = {}
9535 for f in filenames:
9536 if f not in fn:
9537 continue
9538
9539 ret[f] = self._vmod.read(f)
9540
9541 return ret
9542
9543 def getDOM(self,filename):
9544 '''Get content of a file decoded as XML DOM
9545
9546 Parameters
9547 ----------
9548 filename : str
9549 Name of file in module
9550 '''
9551 from xml.dom.minidom import parseString
9552
9553 r = self.getFiles(filename)
9554 if filename not in r:
9555 raise RuntimeError(f'No {filename} found!')
9556
9557 return parseString(r[filename])
9558
9559 def getBuildFile(self):
9560 '''Get the buildFile.xml decoded as a DOM tree'''
9561 return self.getDOM(VMod.BUILD_FILE)
9562
9563 def getModuleData(self):
9564 '''Get the moduledata decoded as a DOM tree'''
9565 return self.getDOM(VMod.MODULE_DATA)
9566
9567 def getInternalFile(self,filename,mode):
9568 return self._vmod.open(filename,mode)
9569
9570 def addVSav(self,build):
9571 '''Add a `VSav` element to this
9572
9573 Parameters
9574 ----------
9575 kwargs : dict
9576 Dictionary of attribute key-value pairs
9577
9578 Returns
9579 -------
9580 element : VSav
9581 The added element
9582 '''
9583 return VSav(build=build,vmod=self)
9584
9585
9586 #
9587 # EOF
9588 #
9589 # ====================================================================
9590 # From upgrade.py
9591
9592
9593 class VLogUpgrader:
9594 def __init__(self,
9595 vmodFileName,
9596 vlogFileName,
9597 verbose=False):
9598 self._readVModFile(vmodFileName,verbose)
9599 self._readVLogFile(vlogFileName,verbose)
9600
9601 def _readVModFile(self,vmodFileName,verbose=False):
9602 with VMod(vmodFileName, 'r') as vmod:
9603 self._build = BuildFile(vmod.getBuildFile())
9604 self._game = self._build.getGame()
9605
9606 self._vmod_pieces = {}
9607 for piece in self._game.getPieces():
9608 name, piece = self._expandPiece(piece,verbose)
9609 self._vmod_pieces[name] = piece
9610
9611 def _expandPiece(self,piece,verbose=False):
9612 traits = piece.getTraits();
9613 newTraits = Trait.flatten(traits, game=self._game,verbose=verbose)
9614
9615 piece.setTraits(*newTraits)
9616
9617 name = newTraits[-1]['name']
9618
9619 return name, piece
9620
9621 def _readVLogFile(self,vlogFileName,verbose=False):
9622 key, lines, sdata, mdata = SaveIO.readSave(vlogFileName,
9623 alsometa=True)
9624
9625 self._key = key
9626 self._lines = lines
9627 self._save_data = sdata
9628 self._meta_data = mdata
9629 self._vlog_pieces = {}
9630
9631 for line in self._lines:
9632 iden, name, piece = self._vlogPiece(line,verbose)
9633 if piece is None:
9634 continue
9635
9636 vmod_piece = self._vmod_pieces.get(name,None)
9637 if vmod_piece is None:
9638 print(f'Did not find piece "{name}" in vmod')
9639 vmod_piece = piece
9640
9641 vmod_piece.copyStates(piece)
9642 self._vlog_pieces[iden] = {'name': name,
9643 'vlog': piece,
9644 'vmod': vmod_piece}
9645
9646
9647 def _vlogPiece(self,line,verbose=False):
9648 from re import match
9649
9650 m = match(r'^\+/([0-9]+)/.*;([a-z0-9_]+)\.png.*',line)
9651 if m is None:
9652 return None,None,None
9653
9654 iden = int(m.group(1))
9655 piece = PieceSlot(None)
9656 piece.setTraits(*piece.decodeAdd(line,verbose),iden=iden)
9657 basic = piece.getTraits()[-1]
9658
9659 return iden,basic['name'],piece
9660
9661
9662 def _newLine(self,line,verbose):
9663 self._new_lines.append(line)
9664 if verbose:
9665 print(line)
9666
9667 def upgrade(self,shownew=False,verbose=False):
9668 self._new_lines = []
9669 for line in self._lines:
9670 add_line = self.newDefine(line,verbose)
9671 if add_line:
9672 self._newLine(add_line,shownew)
9673 continue
9674
9675 cmd_line = self.newCommand(line,verbose)
9676 if cmd_line:
9677 self._newLine(cmd_line,shownew)
9678 continue
9679
9680 oth_line = self.other(line,verbose)
9681 if oth_line:
9682 self._newLine(oth_line,shownew)
9683 continue
9684
9685 self._newLine(line,shownew)
9686
9687 def newCommand(self,line,verbose=False):
9688 from re import match
9689
9690 m = match(r'LOG\s+([+MD])/([0-9]+)/([^/]+)(.*)',line)
9691 if not m:
9692 return None
9693
9694 cmd = m.group(1)
9695 iden = int(m.group(2))
9696 more = m.group(3)
9697
9698 if more == 'stack':
9699 return None
9700
9701 vp = self._vlog_pieces.get(iden,None)
9702 if vp is None:
9703 print(f'Piece {iden} not found: "{line}"')
9704 return None
9705
9706 if cmd == '+' or cmd == 'M':
9707 return None
9708
9709 # Get the code
9710 code = more + m.group(4)
9711
9712 # Decode the states from the code into the old piece
9713 vp['vlog'].decodeStates(code,verbose)
9714
9715 # Get the previsous state from the new piece
9716 old = vp['vmod'].encodedStates()
9717
9718 # Copy states from the old piece to the new piece
9719 vp['vmod'].copyStates(vp['vlog'],verbose)
9720
9721 # Get the new state code from the new piece
9722 new = vp['vmod'].encodedStates()
9723
9724 newline = 'LOG\t'+cmd+'/'+str(iden)+'/'+new+'/'+old+'\\\\'
9725 # print('WAS',line)
9726 # print('NOW',newline)
9727 return newline
9728
9729 def newDefine(self,line,verbose):
9730 from re import match
9731
9732 m = match(r'\+/([0-9]+)/([^/]+).*',line)
9733
9734 if not m:
9735 return False
9736
9737 iden = int(m.group(1))
9738 more = m.group(2)
9739 if more == 'stack':
9740 return False
9741
9742 vp = self._vlog_pieces.get(iden,None)
9743 if vp is None:
9744 print(f'Piece {iden} not known')
9745
9746 old = vp['vlog']
9747 new = vp['vmod']
9748
9749 old_add = old._node.childNodes[0].nodeValue;
9750 new_add = new.encodeAdd(*new.getTraits(),iden=iden,verbose=verbose);
9751
9752 return new_add
9753
9754 def other(self,line,verbose=False):
9755 return None
9756
9757
9758 def write(self,outFileName,verbose=False):
9759 SaveIO.writeSave(outFileName,
9760 key = 0xAA,
9761 lines = self._new_lines,
9762 savedata = self._save_data,
9763 moduledata = self._meta_data)
9764
9765
9766
9767 #
9768 # EOF
9769 #
9770 # ====================================================================
9771 # From exporter.py
9772
9773 class Exporter:
9774 def __init__(self):
9775 '''Base class for exporters'''
9776 pass
9777
9778
9779 def setup(self):
9780 '''Should be defined to set-up for processing, for example
9781 generating images and such. This is executed in a context
9782 where the VMod file has been opened for writing via
9783 `self._vmod`. Thus, files can be added to the module at this
9784 stage.
9785 '''
9786 pass
9787
9788 def createBuildFile(self,ignores='(.*markers?|all|commons|[ ]+)'):
9789 '''Should be defined to make the `buildFile.xml` document
9790
9791 Parameters
9792 ----------
9793 ignores : str
9794 Regular expression to match ignored categories for factions
9795 determination. Python's re.fullmatch is applied to this
9796 regular exression against chit categories. If the pattern
9797 is matched, then the chit is not considered to belong to a
9798 faction.
9799
9800 '''
9801 pass
9802
9803 def createModuleData(self):
9804 '''Should be defined to make the `moduledata` document'''
9805 pass
9806
9807 def run(self,vmodname,patch=None):
9808 '''Run the exporter to generate the module
9809 '''
9810 with VMod(vmodname,'w') as vmod:
9811 self._vmod = vmod
9812 self.setup()
9813 self.createBuildFile()
9814 self.createModuleData()
9815 self.runPatch(patch)
9816 self._vmod.addFiles(**{VMod.BUILD_FILE :
9817 self._build.encode(),
9818 VMod.MODULE_DATA :
9819 self._moduleData.encode()})
9820 Verbose().message('Created VMOD')
9821
9822
9823 def runPatch(self,patch):
9824 '''Run user specified patch script. The script should define
9825
9826 ```
9827 def patch(buildFile,moduleData,vmod,verbose):
9828 ```
9829
9830 where `buildFile` is the `buildFile.xml` and `moduleData` are
9831 the XML documents as `xml.dom.Document` objects, `vmod` is a
9832 `VMod` instance, and `verbose` is a `bool` selecting verbose
9833 mode or not.
9834 '''
9835 if patch is None or patch == '':
9836 return
9837
9838 from importlib.util import spec_from_file_location, module_from_spec
9839 from pathlib import Path
9840 from sys import modules
9841
9842 p = Path(patch)
9843 with VerboseGuard(f'Will patch module with {p.stem}.patch function') \
9844 as v:
9845
9846 spec = spec_from_file_location(p.stem, p.absolute())
9847 module = module_from_spec(spec)
9848 spec.loader.exec_module(module)
9849 modules[p.stem] = module
9850
9851 # Patch must accept xml.dom.document,xml.dom.document,ZipFile
9852 module.patch(self._build,
9853 self._moduleData,
9854 self._vmod,
9855 Verbose().verbose)
9856
9857 # ====================================================================
9858 # From latexexporter.py
9859
9860 # ====================================================================
9861 #
9862 # Exporter class
9863 #
9864 class LaTeXExporter(Exporter):
9865 class Specials:
9866 BATTLE_MARK = 'wgBattleMarker'
9867 BATTLE_CTRL = 'wgBattleCtrl'
9868 BATTLE_CALC = 'wgBattleCalc'
9869 BATTLE_UNIT = 'wgBattleUnit'
9870 ODDS_MARK = 'wgOddsMarker'
9871 HIDDEN_NAME = 'wg hidden unit'
9872
9873 class Keys:
9874 MARK_BATTLE = key(NONE,0)+',wgMarkBattle'
9875 CLEAR_BATTLE = key(NONE,0)+',wgClearBattle'
9876 CLEAR_ALL_BATTLE = key(NONE,0)+',wgClearAllBattle'
9877 ZERO_BATTLE = key(NONE,0)+',wgZeroBattle'
9878 INCR_BATTLE = key(NONE,0)+',wgIncrBattle'
9879 SET_BATTLE = key(NONE,0)+',wgSetBattle'
9880 GET_BATTLE = key(NONE,0)+',wgGetBattle'
9881 MARK_ODDS = key(NONE,0)+',wgMarkOdds'
9882 MARK_RESULT = key(NONE,0)+',wgMarkResult'
9883 CLEAR_MOVED = key(NONE,0)+',wgClearMoved'
9884 ZERO_BATTLE_AF = key(NONE,0)+',wgZeroBattleAF'
9885 ZERO_BATTLE_DF = key(NONE,0)+',wgZeroBattleDF'
9886 ZERO_BATTLE_FRAC = key(NONE,0)+',wgZeroBattleFrac'
9887 ZERO_BATTLE_ODDS = key(NONE,0)+',wgZeroBattleOdds'
9888 ZERO_BATTLE_SHFT = key(NONE,0)+',wgZeroBattleShift'
9889 ZERO_BATTLE_IDX = key(NONE,0)+',wgZeroBattleIdx'
9890 CALC_BATTLE_AF = key(NONE,0)+',wgCalcBattleAF'
9891 CALC_BATTLE_DF = key(NONE,0)+',wgCalcBattleDF'
9892 CALC_BATTLE_FRAC = key(NONE,0)+',wgCalcBattleFrac'
9893 CALC_BATTLE_ODDS = key(NONE,0)+',wgCalcBattleOdds'
9894 CALC_BATTLE_SHFT = key(NONE,0)+',wgCalcBattleShift'
9895 CALC_BATTLE_IDX = key(NONE,0)+',wgCalcBattleIdx'
9896 CALC_BATTLE_RES = key(NONE,0)+',wgCalcBattleResult'
9897 CLEAR_BATTLE_PHS = key(NONE,0)+',wgClearBattlePhs'
9898 RESOLVE_BATTLE = key(NONE,0)+',wgResolveBattle'
9899 ROLL_DICE = key(NONE,0)+',wgRollDice'
9900 DICE_INIT_KEY = key(NONE,0)+',wgInitDice'
9901 CLEAR_KEY = key('C')
9902 CLEAR_ALL_KEY = key('C',CTRL_SHIFT)
9903 DELETE_KEY = key('D')
9904 ELIMINATE_KEY = key('E')
9905 FLIP_KEY = key('F')
9906 TRAIL_KEY = key('T')
9907 RESTORE_KEY = key('R')
9908 MARK_KEY = key('X')
9909 RESOLVE_KEY = key('Y')
9910 ROTATE_CCWKey = key('[')
9911 ROTATE_CWKey = key(']')
9912 CHARTS_KEY = key('A',ALT)
9913 OOB_KEY = key('B',ALT)
9914 COUNTERS_KEY = key('C',ALT)
9915 DEAD_KEY = key('E',ALT)
9916 DICE_KEY = key('6',ALT)
9917 RECALC_ODDS = key('X',CTRL_SHIFT)
9918
9919 class Globals:
9920 BATTLE_COUNTER = 'wgBattleCounter'
9921 CURRENT_BATTLE = 'wgCurrentBattle'
9922 CURRENT_ATTACKER = 'wgCurrentAttacker'
9923 BATTLE_NO = 'wgBattleNo'
9924 BATTLE_AF = 'wgBattleAF'
9925 BATTLE_DF = 'wgBattleDF'
9926 BATTLE_FRAC = 'wgBattleFrac'
9927 BATTLE_IDX = 'wgBattleIdx'
9928 BATTLE_ODDS = 'wgBattleOdds'
9929 BATTLE_ODDSM = 'wgBattleOddsMarker'
9930 BATTLE_SHIFT = 'wgBattleShift'
9931 BATTLE_RESULT = 'wgBattleResult'
9932 AUTO_ODDS = 'wgAutoOdds'
9933 AUTO_RESULTS = 'wgAutoResults'
9934 NO_CLEAR_MOVES = 'wgNoClearMoves'
9935 NO_CLEAR_BATTLES = 'wgNoClearBattles'
9936 DEBUG = 'wgDebug'
9937 VERBOSE = 'wgVerbose'
9938
9939 def __init__(self,
9940 vmodname = 'Draft.vmod',
9941 pdfname = 'export.pdf',
9942 infoname = 'export.json',
9943 title = 'Draft',
9944 version = 'draft',
9945 imageFormat = 'png',
9946 description = '',
9947 rules = None,
9948 tutorial = None,
9949 patch = None,
9950 visible = True,
9951 vassalVersion = '3.6.7',
9952 nonato = False,
9953 nochit = False,
9954 counterScale = 1,
9955 resolution = 150):
9956 '''Exports a PDF and associated JSON files to a VASSAL module.
9957
9958 Parameters
9959 ----------
9960 vmodname : str
9961 Name of module file to write
9962 pdfname : str
9963 Name of PDF file to read images from
9964 infoname : str
9965 Name of JSON file to read meta data from
9966 title : str
9967 Name of module
9968 version : str
9969 Version of midule
9970 description : str
9971 Short description of the module
9972 rules : str
9973 Optional name PDF file to attach as rules
9974 tutorial : str
9975 Optional name of a VASSAL log file to use as tutorial
9976 patch : str
9977 Optional name of Python script to post process the module
9978 visible : bool
9979 Make grids visible
9980 vassalVersion : str
9981 VASSAL version to encode this module for
9982 resolution : int
9983 Resolution for images (default 150)
9984 '''
9985 self._vmodname = vmodname
9986 self._pdfname = pdfname
9987 self._infoname = infoname
9988 self._title = title
9989 self._version = version
9990 self._description = description
9991 self._rules = rules
9992 self._tutorial = tutorial
9993 self._patch = patch
9994 self._visible = visible or version.lower() == 'draft'
9995 self._vassalVersion = vassalVersion
9996 self._nonato = nonato
9997 self._nochit = nochit
9998 self._resolution = resolution
9999 self._counterScale = counterScale
10000 self._img_format = imageFormat.lower()
10001
10002 self._battleMark = LaTeXExporter.Specials.BATTLE_MARK
10003 self._oddsMark = LaTeXExporter.Specials.ODDS_MARK
10004 self._battleCtrl = LaTeXExporter.Specials.BATTLE_CTRL
10005 self._battleCalc = LaTeXExporter.Specials.BATTLE_CALC
10006 self._battleUnit = LaTeXExporter.Specials.BATTLE_UNIT
10007 self._hiddenName = LaTeXExporter.Specials.HIDDEN_NAME
10008 self._markBattle = LaTeXExporter.Keys.MARK_BATTLE
10009 self._clearBattle = LaTeXExporter.Keys.CLEAR_BATTLE
10010 self._clearAllBattle = LaTeXExporter.Keys.CLEAR_ALL_BATTLE
10011 self._zeroBattle = LaTeXExporter.Keys.ZERO_BATTLE
10012 self._incrBattle = LaTeXExporter.Keys.INCR_BATTLE
10013 self._setBattle = LaTeXExporter.Keys.SET_BATTLE
10014 self._getBattle = LaTeXExporter.Keys.GET_BATTLE
10015 self._markOdds = LaTeXExporter.Keys.MARK_ODDS
10016 self._markResult = LaTeXExporter.Keys.MARK_RESULT
10017 self._clearMoved = LaTeXExporter.Keys.CLEAR_MOVED
10018 self._zeroBattleAF = LaTeXExporter.Keys.ZERO_BATTLE_AF
10019 self._zeroBattleDF = LaTeXExporter.Keys.ZERO_BATTLE_DF
10020 self._zeroBattleFrac = LaTeXExporter.Keys.ZERO_BATTLE_FRAC
10021 self._zeroBattleOdds = LaTeXExporter.Keys.ZERO_BATTLE_ODDS
10022 self._zeroBattleShft = LaTeXExporter.Keys.ZERO_BATTLE_SHFT
10023 self._zeroBattleIdx = LaTeXExporter.Keys.ZERO_BATTLE_IDX
10024 self._calcBattleAF = LaTeXExporter.Keys.CALC_BATTLE_AF
10025 self._calcBattleDF = LaTeXExporter.Keys.CALC_BATTLE_DF
10026 self._calcBattleFrac = LaTeXExporter.Keys.CALC_BATTLE_FRAC
10027 self._calcBattleOdds = LaTeXExporter.Keys.CALC_BATTLE_ODDS
10028 self._calcBattleShft = LaTeXExporter.Keys.CALC_BATTLE_SHFT
10029 self._calcBattleIdx = LaTeXExporter.Keys.CALC_BATTLE_IDX
10030 self._calcBattleRes = LaTeXExporter.Keys.CALC_BATTLE_RES
10031 self._clearBattlePhs = LaTeXExporter.Keys.CLEAR_BATTLE_PHS
10032 self._resolveBattle = LaTeXExporter.Keys.RESOLVE_BATTLE
10033 self._rollDice = LaTeXExporter.Keys.ROLL_DICE
10034 self._diceInitKey = LaTeXExporter.Keys.DICE_INIT_KEY
10035 self._clearKey = LaTeXExporter.Keys.CLEAR_KEY
10036 self._clearAllKey = LaTeXExporter.Keys.CLEAR_ALL_KEY
10037 self._deleteKey = LaTeXExporter.Keys.DELETE_KEY
10038 self._eliminateKey = LaTeXExporter.Keys.ELIMINATE_KEY
10039 self._flipKey = LaTeXExporter.Keys.FLIP_KEY
10040 self._trailKey = LaTeXExporter.Keys.TRAIL_KEY
10041 self._restoreKey = LaTeXExporter.Keys.RESTORE_KEY
10042 self._markKey = LaTeXExporter.Keys.MARK_KEY
10043 self._resolveKey = LaTeXExporter.Keys.RESOLVE_KEY
10044 self._rotateCCWKey = LaTeXExporter.Keys.ROTATE_CCWKey
10045 self._rotateCWKey = LaTeXExporter.Keys.ROTATE_CWKey
10046 self._chartsKey = LaTeXExporter.Keys.CHARTS_KEY
10047 self._oobKey = LaTeXExporter.Keys.OOB_KEY
10048 self._countersKey = LaTeXExporter.Keys.COUNTERS_KEY
10049 self._deadKey = LaTeXExporter.Keys.DEAD_KEY
10050 self._diceKey = LaTeXExporter.Keys.DICE_KEY
10051 self._recalcOdds = LaTeXExporter.Keys.RECALC_ODDS
10052 self._battleCounter = LaTeXExporter.Globals.BATTLE_COUNTER
10053 self._currentBattle = LaTeXExporter.Globals.CURRENT_BATTLE
10054 self._currentAttacker = LaTeXExporter.Globals.CURRENT_ATTACKER
10055 self._battleNo = LaTeXExporter.Globals.BATTLE_NO
10056 self._battleAF = LaTeXExporter.Globals.BATTLE_AF
10057 self._battleDF = LaTeXExporter.Globals.BATTLE_DF
10058 self._battleFrac = LaTeXExporter.Globals.BATTLE_FRAC
10059 self._battleIdx = LaTeXExporter.Globals.BATTLE_IDX
10060 self._battleOdds = LaTeXExporter.Globals.BATTLE_ODDS
10061 self._battleOddsM = LaTeXExporter.Globals.BATTLE_ODDSM
10062 self._battleShift = LaTeXExporter.Globals.BATTLE_SHIFT
10063 self._battleResult = LaTeXExporter.Globals.BATTLE_RESULT
10064 self._autoOdds = LaTeXExporter.Globals.AUTO_ODDS
10065 self._autoResults = LaTeXExporter.Globals.AUTO_RESULTS
10066 self._noClearMoves = LaTeXExporter.Globals.NO_CLEAR_MOVES
10067 self._noClearBattles = LaTeXExporter.Globals.NO_CLEAR_BATTLES
10068 self._debug = LaTeXExporter.Globals.DEBUG
10069 self._verbose = LaTeXExporter.Globals.VERBOSE
10070 self._battleMarks = []
10071 self._oddsMarks = []
10072 self._resultMarks = []
10073 self._hidden = None
10074 self._dice = {}
10075 self._diceInit = None
10076
10077 with VerboseGuard('Overall settings') as v:
10078 v(f'Module file name: {self._vmodname}')
10079 v(f'PDF file name: {self._pdfname}')
10080 v(f'JSON file name: {self._infoname}')
10081 v(f'Game title: {self._title}')
10082 v(f'Game version: {self._version}')
10083 v(f'Description: {self._description}')
10084 v(f'Rules PDF file: {self._rules}')
10085 v(f'Tutorial log: {self._tutorial}')
10086 v(f'Patch scripts: {self._patch}')
10087 v(f'Visible grids: {self._visible}')
10088 v(f'Resolution: {self._resolution}')
10089 v(f'Scale of counters: {self._counterScale}')
10090 v(f'Image format: {self._img_format}')
10091
10092
10093 def setup(self):
10094 # Start the processing
10095 self._info = self.convertPages()
10096 self._categories, \
10097 self._mains, \
10098 self._echelons, \
10099 self._commands = self.writeImages(self._counterScale)
10100
10101
10102 def run(self):
10103 super(LaTeXExporter,self).run(self._vmodname,self._patch)
10104
10105
10106
10107 # ================================================================
10108 def createProcess(self,args):
10109 '''Spawn a process and pipe output here
10110
10111 Parameters
10112 ----------
10113 args : list
10114 List of process command line elements
10115
10116 Returns
10117 -------
10118 pipe : subprocess.Pipe
10119 Pipe to read from
10120 '''
10121 from os import environ
10122 from subprocess import Popen, PIPE
10123
10124 return Popen(args,env=environ.copy(),stdout=PIPE,stderr=PIPE)
10125
10126 # ----------------------------------------------------------------
10127 def addPws(self,opw=None,upw=None):
10128 '''Add a `Pws` element to arguments
10129
10130 Add password options
10131
10132 Parameters
10133 ----------
10134 kwargs : dict
10135 Dictionary of attribute key-value pairs
10136
10137 Returns
10138 -------
10139 element : Pws
10140 The added element
10141 '''
10142 args = []
10143 if upw is not None: args.extend(['-upw',upw])
10144 if opw is not None: args.extend(['-opw',opw])
10145 return args
10146
10147 # ----------------------------------------------------------------
10148 def getPdfInfo(self,upw=None,opw=None,timeout=None):
10149 '''Get information about the PDF
10150
10151 Parameters
10152 ----------
10153 opw : str
10154 Owner password (optional)
10155 upw : str
10156 User password (optional)
10157 timeout : int
10158 Time out in miliseconds for subprocesses
10159
10160 Returns
10161 -------
10162 info : dict
10163 Image information
10164 '''
10165 args = ['pdfinfo', self._pdfname ]
10166 args.extend(self.addPws(opw=opw,upw=upw))
10167
10168 with VerboseGuard(f'Getting information from PDF {self._pdfname}'):
10169 proc = self.createProcess(args)
10170 try:
10171 out, err = proc.communicate(timeout=timeout)
10172 except:
10173 proc.kill()
10174 proc.communicate()
10175 raise RuntimeError(f'Failed to get PDF info: {e}')
10176
10177 d = {}
10178 for field in out.decode('utf8','ignore').split('\n'):
10179 if field == '':
10180 continue
10181 subfields = field.split(':')
10182 key, value = subfields[0], ':'.join(subfields[1:])
10183 if key != '':
10184 d[key] = (int(value.strip()) if key == 'Pages'
10185 else value.strip())
10186
10187 if 'Pages' not in d:
10188 raise ValueError(f'Page count not found from {self._pdfname}')
10189
10190 return d
10191
10192 # ----------------------------------------------------------------
10193 def getImagesInfo(self):
10194 '''Read in JSON information, and return as dictionary'''
10195 from json import load
10196
10197 with VerboseGuard(f'Getting information from JSON {self._infoname}'):
10198 with open(self._infoname) as file:
10199 info = load(file)
10200
10201 return info
10202
10203 # ================================================================
10204 @classmethod
10205 def parseLength(cls,value,def_unit='px'):
10206 from re import match
10207
10208 scales = {
10209 'px': 1,
10210 'pt': 1.25,
10211 'pc': 15,
10212 'in': 90,
10213 'mm': 3.543307,
10214 'cm': 35.43307,
10215 '%': -1/100
10216 }
10217
10218 if not value:
10219 return 0
10220
10221 parts = match(r'^\s*(-?\d+(?:\.\d+)?)\s*(px|in|cm|mm|pt|pc|%)?', value)
10222 if not parts:
10223 raise RuntimeError(f'Unknown length format: "{value}"')
10224
10225 number = float(parts.group(1))
10226 unit = parts.group(2) or def_unit
10227 factor = scales.get(unit,None)
10228
10229 if not factor:
10230 raise RuntimeError(f'Unknown unit: "{unit}"')
10231
10232 return factor * number
10233
10234 # ----------------------------------------------------------------
10235 @classmethod
10236 def scaleSVG(cls,buffer,factor):
10237 '''Buffer is bytes'''
10238 from xml.dom.minidom import parse
10239 from re import split
10240 from io import StringIO, BytesIO
10241
10242 if not LaTeXExporter.isSVG(buffer):
10243 return buffer
10244
10245 with BytesIO(buffer) as stream:
10246 doc = parse(stream)
10247
10248 if not doc:
10249 raise RuntimeError('Failed to parse buffer as XML')
10250
10251 root = doc.childNodes[0]
10252 getA = lambda e,n,d=None : \
10253 e.getAttribute(n) if e.hasAttribute(n) else d
10254 setA = lambda e,n,v : e.setAttribute(n,v)
10255 leng = LaTeXExporter.parseLength
10256
10257 width = leng(getA(root,'width', '0'))
10258 height = leng(getA(root,'height','0'))
10259 vport = getA(root,'viewBox','0 0 0 0').strip()
10260 vp = [leng(v) for v in split('[ \t,]',vport)]
10261 # print(f'Input WxH: {width}x{height} ({vp})')
10262
10263 width *= factor
10264 height *= factor
10265 vp = [factor * v for v in vp]
10266
10267 # print(f'Scaled WxH: {width}x{height} ({vp})')
10268
10269 if width <= 0 and vp:
10270 width = vp[2] - vp[0]
10271
10272 if height <= 0 and vp:
10273 height = vp[3] - vp[1]
10274
10275 if not vp:
10276 vp = [0, 0, width, height]
10277
10278 setA(root,'transform',f'scale({factor})')
10279 setA(root,'width', f'{width}')
10280 setA(root,'height',f'{height}')
10281 setA(root,'viewBox',' '.join([f'{v}' for v in vp]))
10282
10283
10284 with StringIO() as out:
10285 doc.writexml(out)
10286 return out.getvalue().encode()
10287
10288
10289 # ================================================================
10290 def convertPage(self,page,opw=None,upw=None,timeout=None):
10291 '''Convert a page from PDF into an image (bytes)
10292
10293 Parameters
10294 ----------
10295 page : int
10296 Page number in the PDF to convert
10297 opw : str
10298 Owner password (optional)
10299 upw : str
10300 User password (optional)
10301 timeout : int
10302 Time out in miliseconds for subprocesses
10303
10304 Returns
10305 -------
10306 info : dict
10307 Image information
10308 '''
10309 args = ['pdftocairo']
10310 if self._img_format != 'svg':
10311 args.extend([
10312 '-transp',
10313 '-singlefile'])
10314
10315 args.extend([
10316 '-r', str(self._resolution),
10317 '-f', str(page),
10318 '-l', str(page),
10319 f'-{self._img_format}' ])
10320 args.extend(self.addPws(opw=opw,upw=upw))
10321 args.append(self._pdfname)
10322 args.append('-')
10323
10324 # print(f'Conversion command',' '.join(args))
10325 proc = self.createProcess(args)
10326
10327 try:
10328 out, err = proc.communicate(timeout=timeout)
10329 except Exception as e:
10330 proc.kill()
10331 proc.communicate()
10332 raise RuntimeError(f'Failed to convert page {page} of '
10333 f'{self._pdfname}: {e}')
10334
10335 if len(out) <= 0:
10336 raise RuntimeError(f'Failed to convert page {page} of '
10337 f'{self._pdfname}: {err}')
10338
10339 # This does not seem to work - VASSAL (and Inkscape) does not
10340 # apply the 'scale' transformation to the image!
10341 #
10342 # if self._img_format == 'svg':
10343 # out = LaTeXExporter.scaleSVG(out,2)
10344
10345 return out
10346
10347
10348 # ----------------------------------------------------------------
10349 def ignoreEntry(self,info,ignores=['<<dummy>>','<<eol>>']):
10350 '''Check if we should ignore an entry in the JSON file'''
10351 return info['category'] in ignores
10352
10353 # ----------------------------------------------------------------
10354 def scaleImage(self,buffer,factor):
10355 from PIL import Image
10356 from io import BytesIO
10357 from math import isclose
10358
10359 if isclose(factor,1): return buffer
10360
10361 # print(f'Scaling image by factor {factor}')
10362 with Image.open(BytesIO(buffer)) as img:
10363 w, h = img.width, img.height
10364 cpy = img.resize((int(factor*w),int(factor*h)))
10365
10366 with BytesIO() as out:
10367 cpy.save(out,format='PNG')
10368 return out.getvalue()
10369
10370
10371 # ----------------------------------------------------------------
10372 def convertPages(self,opw=None,upw=None,timeout=None):
10373 '''Reads in JSON and pages from PDF and stores information
10374 dictionary, which is returned
10375
10376 Parameters
10377 ----------
10378 opw : str
10379 Owner password (optional)
10380 upw : str
10381 User password (optional)
10382 timeout : int
10383 Time out in miliseconds for subprocesses
10384
10385 Returns
10386 -------
10387 info : dict
10388 Image information
10389 '''
10390 oargs = {'opw':opw,'upw':upw }
10391 docinfo = self.getPdfInfo()
10392 imgsinfo = self.getImagesInfo()
10393
10394 if len(imgsinfo) - 1 != docinfo['Pages']:
10395 raise RuntimeError(f'Number of pages in {self._pdfname} '
10396 f'{docinfo["Pages"]} not matched in JSON '
10397 f'{self._infoname} -> {len(imgsinfo)}')
10398
10399 with VerboseGuard(f'Converting {docinfo["Pages"]} '
10400 f'pages in {self._pdfname}') as v:
10401 for i,info in enumerate(imgsinfo):
10402 if self.ignoreEntry(info): continue
10403
10404 if i == 0: v(end='')
10405 v(f'[{info["number"]}]',end=' ',flush=True)
10406 info['img'] = self.convertPage(info['number'],**oargs)
10407
10408 v('done')
10409
10410 return imgsinfo
10411
10412 # ----------------------------------------------------------------
10413 @classmethod
10414 def isSVG(cls,buffer):
10415 return buffer[:5] == b'<?xml'
10416
10417 # ----------------------------------------------------------------
10418 def getBB(self,buffer):
10419 '''Get bounding box of image
10420
10421 Parameters
10422 ----------
10423 buffer : bytes
10424 The image bytes
10425
10426 Returns
10427 -------
10428 ulx, uly, lrx, lry : tuple
10429 The coordinates of the bounding box
10430 '''
10431 from io import BytesIO
10432
10433 with BytesIO(buffer) as inp:
10434 if LaTeXExporter.isSVG(buffer):
10435 from svgelements import SVG
10436
10437 svg = SVG.parse(inp)
10438 # bb = svg.bbox()
10439 # if bb is None:
10440 # print(f'No bounding box!')
10441 # bb = [0, 0, 1, 1]
10442 # else:
10443 # bb = [int(b) for b in bb]
10444 x, y, w, h = svg.x, svg.y, svg.width, svg.height
10445 bb = (x,y,x+w,y+h)
10446 else:
10447 from PIL import Image
10448
10449 with Image.open(inp) as img:
10450 bb = img.getbbox()
10451
10452 return bb
10453
10454 # ----------------------------------------------------------------
10455 def getWH(self,buffer):
10456 '''Get bounding box of image
10457
10458 Parameters
10459 ----------
10460 buffer : bytes
10461 The image bytes
10462
10463 Returns
10464 -------
10465 ulx, uly, lrx, lry : tuple
10466 The coordinates of the bounding box
10467 '''
10468 from io import BytesIO
10469
10470 with BytesIO(buffer) as inp:
10471 if LaTeXExporter.isSVG(buffer):
10472 from svgelements import SVG
10473
10474 svg = SVG.parse(inp)
10475 w, h = svg.x, svg.y, svg.width, svg.height
10476 # bb = svg.bbox()
10477 # w, h = int(bb[2]-bb[0]),int(bb[3]-bb[1])
10478 else:
10479 from PIL import Image
10480
10481 with Image.open(inp) as img:
10482 w, h = img.width, img.height
10483
10484 return w,h
10485
10486 # ----------------------------------------------------------------
10487 def getOutline(self,buffer):
10488 '''Get bounding box of image
10489
10490 Parameters
10491 ----------
10492 buffer : bytes
10493 The image bytes
10494
10495 Returns
10496 -------
10497 ulx, uly, lrx, lry : tuple
10498 The coordinates of the bounding box
10499 '''
10500 from PIL import Image
10501 from io import BytesIO
10502
10503 # print(buffer)
10504 with Image.open(BytesIO(buffer)) as img:
10505 bb = img.getbbox()
10506
10507 for r in range(bb[0],bb[2]):
10508 for c in range(bb[1],bb[3]):
10509 pass #print(img.getpixel((c,r)))
10510
10511 return None
10512
10513
10514 # ================================================================
10515 def writeImages(self,counterScale=1):
10516 '''From the information gathered about the images (including
10517 their bitmap representation, generate image files in the
10518 module
10519
10520 '''
10521 categories = {}
10522 unittypes = []
10523 echelons = []
10524 commands = []
10525
10526 with VerboseGuard(f'Writing images in VMod '
10527 f'{self._vmod.fileName()}',end=' ') as v:
10528 for info in self._info:
10529 if self.ignoreEntry(info): continue
10530
10531 typ = info.get('category','counter')
10532 sub = info.get('subcategory','all')
10533 nam = info['name']
10534 num = info['number']
10535
10536 info['filename'] = f'{nam.replace(" ","_")}.{self._img_format}'
10537 imgfn = 'images/'+info['filename']
10538 if imgfn not in self._vmod.getFileNames():
10539 if typ == 'counter' and self._img_format != 'svg':
10540 # print(f'Possibly scale file {imgfn}')
10541 info['img'] = self.scaleImage(info['img'],
10542 counterScale)
10543 # self.message(f'Writing image {imgfn}')
10544 self._vmod.addFile(imgfn,info['img'])
10545
10546 if sub == '':
10547 info['subcategory'] = 'all'
10548 sub = 'all'
10549
10550 # Add into catalogue
10551 if typ not in categories:
10552 v('')
10553 v(f'Adding category "{typ}"')
10554 v('',end=' ')
10555 categories[typ] = {}
10556 cat = categories[typ]
10557
10558 if sub not in cat:
10559 v('')
10560 v(f'Adding sub-category "{sub}"')
10561 v('',end=' ')
10562 cat[sub] = {}
10563 tgt = cat[sub]
10564
10565 v(f'[{nam}]',end=' ',flush=True,noindent=True)
10566 #self.message(f'Adding "{info["name"]}" to catalogue')
10567 #
10568 # Here we could handle multiple info's with the same
10569 # name by adding a unique postfix - e.g., for dices
10570 # what have non-uniform PMFs.
10571 #
10572 # if info['name'] in tgt:
10573 # n = len([i for k,i in tgt.items() if k.startswith(info['name'])])
10574 # info['name'] += '_' + str(n)
10575 # info['filename'] = info['name'].replace(' ','_') + '.png'
10576 unam = f'{nam}'
10577 tgt[unam] = info
10578
10579 if self._nonato: continue
10580
10581 # Get NATO App6c information, if any
10582 natoapp6c = info.get('natoapp6c',None)
10583 if natoapp6c is not None:
10584 from re import sub
10585 def clean(s):
10586 return sub('.*=','',
10587 (sub(r'\[[^]]+\]','',s.strip())
10588 .replace('{','')
10589 .replace('}','')
10590 .replace('/',' '))).strip()
10591 mains = clean(natoapp6c.get('main', ''))
10592 lower = clean(natoapp6c.get('lower', ''))
10593 upper = clean(natoapp6c.get('upper', ''))
10594 echelon = clean(natoapp6c.get('echelon',''))
10595 command = clean(natoapp6c.get('command',''))
10596
10597
10598 if mains is not None:
10599 if len(lower) > 0: mains += ' '+lower
10600 if len(upper) > 0: mains += ' '+upper
10601 mains = sub(r'\[[^]]+\]','',mains)\
10602 .replace('{','').replace('}','')#.split(',')
10603 unittypes.append(mains.replace(',',' '))
10604 unittypes.extend([s.strip().replace(',',' ')
10605 for s in mains.split(',')])
10606 #if len(mains) > 1:
10607 # unittypes.append('+'.join(mains))
10608 info['mains'] = mains
10609
10610 if len(echelon) > 0:
10611 echelons.append(echelon)
10612 info['echelon'] = echelon
10613
10614 if len(command) > 0:
10615 commands.append(command)
10616 info['command'] = command
10617
10618
10619 # Finished loop over infos. Make unit types, echelons,
10620 # commands unique
10621 v('done')
10622
10623 return categories, set(unittypes), set(echelons), set(commands)
10624
10625 # ================================================================
10626 def createModuleData(self):
10627 '''Create the `moduleData` file in the module
10628 '''
10629 with VerboseGuard(f'Creating module data'):
10630 self._moduleData = ModuleData()
10631 data = self._moduleData.addData()
10632 data.addVersion (version=self._version)
10633 data.addVASSALVersion(version=self._vassalVersion)
10634 data.addName (name=self._title)
10635 data.addDescription (description=self._description)
10636 data.addDateSaved ()
10637
10638 # ================================================================
10639 def createBuildFile(self,
10640 ignores = '(.*markers?|all|commons|.*hidden|[ ]+)'):
10641 '''Create the `buildFile.xml` file in the module.
10642
10643 Parameters
10644 ----------
10645 ignores : str
10646 Regular expression to match ignored categories for factions
10647 determination. Python's re.fullmatch is applied to this
10648 regular exression against chit categories. If the pattern
10649 is matched, then the chit is not considered to belong to a
10650 faction.
10651
10652 '''
10653 from re import fullmatch, IGNORECASE
10654 with VerboseGuard(f'Creating build file') as v:
10655 self._build = BuildFile() # 'buildFile.xml')
10656 self._game = self._build.addGame(name = self._title,
10657 version = self._version,
10658 description = self._description)
10659 doc = self.addDocumentation()
10660 self._game.addBasicCommandEncoder()
10661
10662 # Extract the sides
10663 self._sides = [ k
10664 for k in self._categories.get('counter',{}).keys()
10665 if fullmatch(ignores, k, IGNORECASE) is None]
10666 v(f'Got sides: {", ".join(self._sides)}')
10667
10668 v(f'Adding Global options')
10669 go = self._game.addGlobalOptions(
10670 autoReport = GlobalOptions.PROMPT,
10671 centerOnMove = GlobalOptions.PROMPT,
10672 nonOwnerUnmaskable = GlobalOptions.PROMPT,
10673 playerIdFormat = '$playerName$')
10674 go.addOption(name='undoHotKey',value=key('Z'))
10675 go.addOption(name='undoIcon', value='/images/Undo16.gif')
10676 # go.addOptoin(name='stepHotKey',value='')
10677 go.addBoolPreference(name = self._verbose,
10678 default = True,
10679 desc = 'Be verbose',
10680 tab = self._title)
10681 go.addBoolPreference(name = self._debug,
10682 default = False,
10683 desc = 'Show debug chat messages',
10684 tab = self._title)
10685 go.addBoolPreference(name = self._autoOdds,
10686 default = False,
10687 desc = 'Calculate Odds on battle declaration',
10688 tab = self._title)
10689 go.addBoolPreference(name = self._autoResults,
10690 default = False,
10691 desc = 'Resolve battle results automatically',
10692 tab = self._title)
10693 go.addBoolPreference(name = self._noClearMoves,
10694 default = False,
10695 desc = ('Do not remove moved markers '
10696 'on phase change'),
10697 tab = self._title)
10698 go.addBoolPreference(name = self._noClearBattles,
10699 default = False,
10700 desc = ('Do not remove battle markers '
10701 'on phase change'),
10702 tab = self._title)
10703
10704 v(f'Adding player roster')
10705 roster = self._game.addPlayerRoster()
10706 for side in self._sides:
10707 roster.addSide(side)
10708
10709 v(f'Adding global properties')
10710 glob = self._game.addGlobalProperties()
10711 glob.addProperty(name='TurnTracker.defaultDocked',
10712 initialValue=True)
10713
10714 self._battleMarks = self._categories\
10715 .get('counter',{})\
10716 .get('BattleMarkers',[])
10717 if len(self._battleMarks) > 0:
10718 v(f'We have battle markers')
10719
10720 glob.addProperty(name = self._battleCounter,
10721 initialValue = 0,
10722 isNumeric = True,
10723 min = 0,
10724 max = len(self._battleMarks),
10725 wrap = True,
10726 description = 'Counter of battles')
10727 glob.addProperty(name = self._currentBattle,
10728 initialValue = 0,
10729 isNumeric = True,
10730 min = 0,
10731 max = len(self._battleMarks),
10732 wrap = True,
10733 description = 'Current battle number')
10734 glob.addProperty(name = self._currentAttacker,
10735 initialValue = 0,
10736 isNumeric = True,
10737 min = 0,
10738 max = 1,
10739 wrap = True,
10740 description = 'Current unit is attacker')
10741 glob.addProperty(name = self._battleAF,
10742 initialValue = 0,
10743 isNumeric = True,
10744 description = 'Current battle AF')
10745 glob.addProperty(name = self._battleDF,
10746 initialValue = 0,
10747 isNumeric = True,
10748 description = 'Current battle DF')
10749 glob.addProperty(name = self._battleFrac,
10750 initialValue = 0,
10751 isNumeric = True,
10752 description = 'Current battle fraction')
10753 glob.addProperty(name = self._battleShift,
10754 initialValue = 0,
10755 isNumeric = True,
10756 description = 'Current battle odds shift')
10757 glob.addProperty(name = self._battleOdds,
10758 initialValue = '',
10759 isNumeric = False,
10760 description = 'Current battle odds')
10761 glob.addProperty(name = self._battleResult,
10762 initialValue = '',
10763 isNumeric = False,
10764 description = 'Current battle results')
10765 glob.addProperty(name = self._battleIdx,
10766 initialValue = 0,
10767 isNumeric = True,
10768 description = 'Current battle odds index')
10769
10770 self._oddsMarks = self._categories\
10771 .get('counter',{})\
10772 .get('OddsMarkers',[])
10773 if len(self._oddsMarks) > 0:
10774 v(f'We have odds markers')
10775
10776 self._resultMarks = self._categories\
10777 .get('counter',{})\
10778 .get('ResultMarkers',[])
10779 if len(self._resultMarks) > 0:
10780 v(f'We have result markers')
10781
10782 self.addNotes()
10783 v(f'Adding turn track')
10784 turns = self._game.addTurnTrack(name='Turn',
10785 counter={
10786 'property': 'Turn',
10787 'phases': {
10788 'property': 'Phase',
10789 'names': self._sides } })
10790 turns.addHotkey(hotkey = self._clearMoved+'Phase',
10791 name = 'Clear moved markers',
10792 reportFormat = (f'{{{self._verbose}?('
10793 f'"`Clear all moved markers, "+'
10794 f'""):""}}'))
10795 if len(self._battleMarks) > 0:
10796 turns.addHotkey(hotkey = self._clearBattlePhs,
10797 name = 'Clear battle markers',
10798 reportFormat = (f'{{{self._verbose}?('
10799 f'"`Clear all battle markers, "+'
10800 f'""):""}}'))
10801
10802 self._dice = self._categories\
10803 .get('die-roll',{})
10804 if len(self._dice) > 0:
10805 v(f'We have symbolic dice')
10806 self._diceInit = []
10807 # from pprint import pprint
10808 # pprint(self._dice,depth=2)
10809 for die, faces in self._dice.items():
10810 ico = self.getIcon(die+'-die-icon','')
10811 # print(f'Die {die} icon="{ico}"')
10812
10813 dmin = +100000
10814 dmax = -100000
10815 symb = self._game.addSymbolicDice(
10816 name = die+'Dice',
10817 text = die if ico == '' else '',
10818 icon = ico,
10819 tooltip = f'{die} die roll',
10820 format = (f'{{"<b>"+PlayerSide+"</b> "+'
10821 f'"(<i>"+PlayerName+"</i>): "+'+
10822 f'"{die} die roll: "+result1'
10823 # f'+" <img src=\'{die}-"+result1'
10824 # f'+".png\' width=24 height=24>"'
10825 f'}}'),
10826 resultWindow = True,
10827 windowX = str(int(67 * self._resolution/150)),
10828 windowY = str(int(65 * self._resolution/150)));
10829 sdie = symb.addDie(name = die);
10830 for face, fdata in faces.items():
10831 fn = fdata['filename']
10832 val = int(fn.replace(f'.{self._img_format}','')
10833 .replace(die+'-',''))
10834 dmin = min(dmin,val)
10835 dmax = min(dmax,val)
10836 sdie.addFace(icon = fn,
10837 text = str(val),
10838 value = val);
10839
10840 self._diceInit.extend([
10841 GlobalPropertyTrait(
10842 ['',self._diceInitKey,
10843 GlobalPropertyTrait.DIRECT,
10844 f'{{{dmin}}}'],
10845 name = die+'Dice_result',
10846 numeric = True,
10847 min = dmin,
10848 max = dmax,
10849 description = f'Initialize {die}Dice'),
10850 ReportTrait(
10851 self._diceInitKey,
10852 report=(f'{{{self._debug}?("Initialize '
10853 f'{die}Dice_result to {dmin}"):""}}'))
10854 ])
10855
10856
10857 # Add start-up key
10858 self._game.addStartupMassKey(
10859 name = 'Initialise dice results',
10860 hotkey = self._diceInitKey,
10861 target = '',
10862 filter = f'{{BasicName=="{self._hiddenName}"}}',
10863 whenToApply = StartupMassKey.EVERY_LAUNCH,
10864 reportFormat=f'{{{self._debug}?("Init Dice results"):""}}')
10865
10866
10867
10868
10869
10870
10871 self.addKeybindings(doc)
10872 self.addCounters()
10873 self.addInventory()
10874 self.addBoards()
10875 self.addDeadMap()
10876 self.addOOBs()
10877 self.addCharts()
10878 self.addDie()
10879
10880 # ----------------------------------------------------------------
10881 def addDocumentation(self):
10882 '''Add documentation to the module. This includes rules,
10883 key-bindings, and about elements.
10884 '''
10885 with VerboseGuard('Adding documentation') as v:
10886 doc = self._game.addDocumentation()
10887 if self._rules is not None:
10888 self._vmod.addExternalFile(self._rules,'rules.pdf')
10889 doc.addBrowserPDFFile(title = 'Show rules',
10890 pdfFile = 'rules.pdf')
10891
10892 if self._tutorial is not None:
10893 self._vmod.addExternalFile(self._tutorial,'tutorial.vlog')
10894 doc.addTutorial(name = 'Tutorial',
10895 logfile = 'tutorial.vlog',
10896 launchOnStartup = True)
10897
10898
10899 fronts = self._categories.get('front',{}).get('all',[])
10900 front = list(fronts.values())[0] if len(fronts) > 0 else None
10901 if front is not None:
10902 v(f'Adding about page')
10903 doc.addAboutScreen(title=f'About {self._title}',
10904 fileName = front['filename'])
10905
10906 return doc
10907
10908 # ----------------------------------------------------------------
10909 def addKeybindings(self,doc):
10910 keys = [
10911 ['Alt-A', '-', 'Show the charts panel'],
10912 ['Alt-B', '-', 'Show the OOBs'],
10913 ['Alt-C', '-', 'Show the counters panel'],
10914 ['Alt-E', '-', 'Show the eliminated units'],
10915 ['Alt-I', '-', 'Show/refresh inventory window'],
10916 ['Alt-M', '-', 'Show map'],
10917 ['Alt-T', '-', 'Increase turn track'],
10918 ['Alt-Shift-T', '-', 'Decrease turn track'],
10919 ['Alt-6', '-', 'Roll the dice'],
10920 ['Ctrl-D', 'Board,Counter','Delete counters'],
10921 ['Ctrl-E', 'Board,Counter','Eliminate counters'],
10922 ['Ctrl-F', 'Board,Counter','Flip counters'],
10923 ['Ctrl-M', 'Board,Counter','Toggle "moved" markers'],
10924 ['Ctrl-O', 'Board', 'Hide/show counters'],
10925 ['Ctrl-R', 'Board,Counter','Restore unit'],
10926 ['Ctrl-T', 'Board,Counter','Toggle move trail'],
10927 ['Ctrl-Z', 'Board', 'Undo last move'],
10928 ['Ctrl-+', 'Board', 'Zoom in'],
10929 ['Ctrl--', 'Board', 'Zoom out'],
10930 ['Ctrl-=', 'Board', 'Select zoom'],
10931 ['Ctrl-Shift-O', 'Board','Show overview map'],
10932 ['&larr;,&rarr;,&uarr;&darr;','Board',
10933 'Scroll board left, right, up, down (slowly)'],
10934 ['PnUp,PnDn','Board', 'Scroll board up/down (fast)'],
10935 ['Ctrl-PnUp,Ctrl-PnDn','Board', 'Scroll board left/right (fast)'],
10936 ['Mouse-scroll up/down', 'Board', 'Scroll board up//down'],
10937 ['Shift-Mouse-scroll up/down','Board','Scroll board right/leftown'],
10938 ['Ctrl-Mouse-scroll up/down','Board','Zoom board out/in'],
10939 ['Mouse-2', 'Board', 'Centre on mouse']]
10940 if self._battleMarks:
10941 for a,l in zip(['Ctrl-D','Ctrl-Shift-O', 'Ctrl-+', 'Ctrl-+'],
10942 [['Ctrl-C', 'Counter', 'Clear battle'],
10943 ['Ctrl-Shift-C','Board', 'Clear all battle'],
10944 ['Ctrl-X', 'Board,Counter','Mark battle'],
10945 ['Ctrl-Shift-X','Board,Counter','Recalculate Odds'],
10946 ['Ctrl-Y', 'Board,Counter','Resolve battle'],
10947 ]):
10948 ks = [k[0] for k in keys]
10949 didx = ks.index(a)
10950 keys.insert(didx,l)
10951
10952 self._vmod.addFile('help/keys.html',
10953 Documentation.createKeyHelp(
10954 keys,
10955 title=self._title,
10956 version=self._version))
10957 doc.addHelpFile(title='Key bindings',fileName='help/keys.html')
10958
10959 # ----------------------------------------------------------------
10960 def addNatoPrototypes(self,prototypes):
10961 # Add unit categories as prototypes
10962 for n,c in zip(['Type','Echelon','Command'],
10963 [self._mains, self._echelons, self._commands]):
10964 sc = set([cc.strip() for cc in c])
10965 with VerboseGuard(f'Adding prototypes for "{n}"') as vv:
10966 for i,cc in enumerate(sc):
10967 cc = cc.strip()
10968 if len(cc) <= 0: continue
10969 vv(f'[{cc}] ',end='',flush=True,noindent=True)
10970 p = prototypes.addPrototype(name = f'{cc} prototype',
10971 description = '',
10972 traits = [MarkTrait(n,cc),
10973 BasicTrait()])
10974 vv('')
10975
10976 # ----------------------------------------------------------------
10977 def addBattleControlPrototype(self,prototypes):
10978 # Control of battles.
10979 #
10980 # This has traits to
10981 #
10982 # - Zero battle counter
10983 # - Increment battle counter
10984 # - Set current battle number
10985 # - Mark battle
10986 # - Calculate odds
10987 #
10988 # When wgMarkBattle is issued to this piece, then
10989 #
10990 # - Increment battle counter
10991 # - Set global current battle
10992 # - Trampoline to GCK markBattle
10993 # - For all selected pieces, issue markBattle
10994 # - All wgBattleUnit pieces then
10995 # - Get current battle # and store
10996 # - Add marker on top of it self
10997 # - Issue calculateOddsAuto
10998 # - If auto odds on, go to calcOddsStart,
10999 # - Trampoline to GCK calcOddsAuto
11000 # - Which sends calcOddsStart to all markers
11001 # - For each mark
11002 # - Set current battle to current global
11003 # - Trampoline calcOdds via GKC
11004 # - Send calcBattleOdds to wgBattleCalc
11005 # - Zero odds
11006 # - Calculate fraction
11007 # - Zero fraction
11008 # - Calculate total AF
11009 # - Zero AF
11010 # - via trampoline to GKC
11011 # - Calculate total DF
11012 # - Zero DF
11013 # - via trampoline to GKC
11014 # - Real fraction calculation
11015 # - From calculate fraction
11016 # - Access via calculate trait
11017 # - Calculate shift
11018 # - Zero shift
11019 # - Trampoline to GKC
11020 # - Access via calculate trait
11021 # - Calculate index
11022 # - Via calculated OddsIndex
11023 # - Calculate odds real
11024 # - Via calculated Index to odds
11025 # - Do markOddsAuto which selects between odds
11026 # - Do markOddsReal+OddsIndex
11027 # - Set global battle #
11028 # - Place marker
11029 # - Take global battle #
11030 # - De-select all other marks to prevent
11031 # further propagation
11032 #
11033 if len(self._battleMarks) <= 0:
11034 return False
11035
11036 n = len(self._battleMarks)
11037 # --- Battle counter control - reset and increment -----------
11038 traits = [
11039 GlobalPropertyTrait(
11040 ['',self._zeroBattle,GlobalPropertyTrait.DIRECT,'{0}'],
11041 ['',self._incrBattle,GlobalPropertyTrait.DIRECT,
11042 f'{{({self._battleCounter}%{n})+1}}'],
11043 name = self._battleCounter,
11044 numeric = True,
11045 min = 0,
11046 max = n,
11047 wrap = True,
11048 description = 'Zero battle counter',
11049 ),
11050 # Set global property combat # from this
11051 GlobalPropertyTrait(
11052 ['',self._setBattle,GlobalPropertyTrait.DIRECT,
11053 f'{{{self._battleCounter}}}'],
11054 name = self._currentBattle,
11055 numeric = True,
11056 min = 0,
11057 max = n,
11058 wrap = True,
11059 description = 'Zero battle counter',
11060 ),
11061 ReportTrait(self._zeroBattle,
11062 report=(f'{{{self._debug}?'
11063 f'("~ "+BasicName+": zero battle counter: "'
11064 f'+{self._battleCounter}):""}}')),
11065 ReportTrait(self._incrBattle,
11066 report=(f'{{{self._debug}?'
11067 f'("~ "+BasicName+": '
11068 f'increment battle counter: "'
11069 f'+{self._battleCounter}):""}}')),
11070 ReportTrait(self._setBattle,
11071 report=(f'{{{self._debug}?'
11072 f'("~ "+BasicName+": set current battle: "+'
11073 f'{self._battleCounter}+" -> "+'
11074 f'{self._currentBattle}):""}}')),
11075 GlobalHotkeyTrait(name = '',
11076 key = self._markBattle+'Trampoline',
11077 globalHotkey = self._markBattle,
11078 description = 'Mark selected for battle'),
11079 ReportTrait(self._markBattle+'Trampoline',
11080 report=(f'{{{self._debug}?'
11081 f'("~ "+BasicName+": forward mark battle: "+'
11082 f'{self._battleCounter}):""}}')),
11083 GlobalHotkeyTrait(name = '',
11084 key = self._calcBattleOdds+'Start',
11085 globalHotkey = self._calcBattleOdds+'Auto',
11086 description = 'Trampoline to global'),
11087 ReportTrait(self._calcBattleOdds+'Start',
11088 report=(f'{{{self._debug}?'
11089 f'("~ "+BasicName+": forward odds: "+'
11090 f'{self._battleCounter}):""}}')),
11091 DeselectTrait(command = '',
11092 key = self._calcBattleOdds+'Deselect',
11093 deselect = DeselectTrait.ALL),
11094 ReportTrait(self._calcBattleOdds+'Deselect',
11095 report=(f'{{{self._debug}?'
11096 f'("~ "+BasicName+": select only this: "+'
11097 f'{self._battleCounter}):""}}')),
11098 TriggerTrait(command = '',
11099 key = self._calcBattleOdds+'Auto',
11100 actionKeys = [self._calcBattleOdds+'Start'],
11101 property = f'{{{self._autoOdds}==true}}'),
11102 ReportTrait(self._calcBattleOdds+'Auto',
11103 report=(f'{{{self._debug}?'
11104 f'("~ "+BasicName+": forward odds: "+'
11105 f'{self._battleCounter}):""}}')),
11106 TriggerTrait(command = '',
11107 key = self._markBattle,
11108 actionKeys = [self._incrBattle,
11109 self._setBattle,
11110 self._markBattle+'Trampoline',
11111 self._calcBattleOdds+'Auto']),
11112 ReportTrait(self._markBattle,
11113 report=(f'{{{self._debug}?'
11114 f'("~ "+BasicName+": mark battle: "+'
11115 f'{self._battleCounter}):""}}')),
11116 GlobalHotkeyTrait(name = '',
11117 key = self._clearAllBattle+'Trampoline',
11118 globalHotkey = self._clearAllBattle,
11119 description = 'Mark selected for battle'),
11120 TriggerTrait(command = '',
11121 key = self._clearAllBattle,
11122 actionKeys = [self._clearAllBattle+'Trampoline',
11123 self._zeroBattle]),
11124 ReportTrait(self._clearBattle,
11125 report=(f'{{{self._debug}?'
11126 f'("~ "+BasicName+": clear battle: "+'
11127 f'{self._battleCounter}):""}}')),
11128 GlobalHotkeyTrait(name = '',
11129 key = self._clearMoved+'Trampoline',
11130 globalHotkey = self._clearMoved,
11131 description = 'Clear moved markers'),
11132 MarkTrait(name=self._battleCtrl,value=True),
11133 BasicTrait()]
11134 prototypes.addPrototype(name = self._battleCtrl,
11135 description = '',
11136 traits = traits)
11137 return True
11138
11139 # ----------------------------------------------------------------
11140 def addBattleCalculatePrototype(self,prototypes):
11141 # --- Batttle AF, DF, Odds -----------------------------------
11142 # This calculate odds derivation from stated odds.
11143 calcIdx = 0
11144 maxIdx = len(self._oddsMarks)+1
11145 minIdx = 0
11146 idx2Odds = '""'
11147 calcFrac = 1
11148 if len(self._oddsMarks) > 0:
11149 odds = [o.replace('odds marker','').strip() for
11150 o in self._oddsMarks]
11151 ratios = all([':' in o for o in odds])
11152 if ratios: # All is ratios!
11153 def calc(s):
11154 num, den = [float(x.strip()) for x in s.split(':')]
11155 return num/den
11156 ratios = [[calc(s),s] for s in odds]
11157 ind = [i[0] for i in sorted(enumerate(ratios),
11158 key=lambda x:x[1][0])]
11159 #print(f'=== Rations: {ratios}, Index: {ind[::-1]}')
11160 calcIdx = ':'.join([f'{self._battleFrac}>={ratios[i][0]}?'
11161 f'({i+1})'
11162 for i in ind[::-1]]) + ':0'
11163 idx2Odds = ':'.join([f'OddsIndex=={i+1}?'
11164 f'"{ratios[i][1]}"'
11165 for i in ind[::-1]]) + ':""'
11166 calcFrac = (f'{{{self._battleDF}==0?0:'
11167 f'(((double)({self._battleAF}))'
11168 fr'\/{self._battleDF})}}')
11169 #print(calcIdx,idx2Odds)
11170 else:
11171 try:
11172 nums = [[int(o),o] for o in odds]
11173 calcFrac = f'{{{self._battleAF}-{self._battleDF}}}'
11174 ind = [i[0] for i in sorted(enumerate(nums),
11175 key=lambda x:x[1])]
11176 calcIdx = ':'.join([f'{self._battleFrac}>={nums[i][0]}?'
11177 f'({i+1})'
11178 for i in ind[::-1]])+':0'
11179 idx2Odds = ':'.join([f'OddsIndex=={i+1}?"{nums[i][1]}"'
11180 for i in ind[::-1]]) + ':""'
11181 vidx2Odds = '\t'+idx2Odds.replace(':',':\n\t')
11182 #print(f'Index to odds: {vidx2Odds}')
11183 except:
11184 pass
11185
11186 traits = [
11187 CalculatedTrait(# This should be changed to game rules
11188 name = 'OddsShift',
11189 expression = f'{{{self._battleShift}}}',
11190 description = 'Calculated internal oddsshift'),
11191 CalculatedTrait(# This should be changed to game rules
11192 name = 'OddsIndexRaw',
11193 expression = f'{{{calcIdx}}}',
11194 description = 'Calculated internal odds index'),
11195 CalculatedTrait(# This should be changed to game rules
11196 name = 'OddsIndexLimited',
11197 expression = (f'{{OddsIndexRaw>{maxIdx}?{maxIdx}:'
11198 f'OddsIndexRaw<{minIdx}?{minIdx}:'
11199 f'OddsIndexRaw}}'),
11200 description = 'Calculated internal limited odds index'),
11201 CalculatedTrait(# This should be changed to game rules
11202 name = 'OddsIndex',
11203 expression = (f'{{OddsIndexLimited+OddsShift}}'),
11204 description = 'Calculated internal odds index (with shift)'),
11205 CalculatedTrait(# This should be changed to game rules
11206 name = 'BattleFraction',
11207 expression = calcFrac,
11208 description = 'Calculated fraction off battle'),
11209 GlobalPropertyTrait(
11210 ['',self._zeroBattleShft,GlobalPropertyTrait.DIRECT,'{0}'],
11211 name = self._battleShift,
11212 numeric = True,
11213 description = 'Zero battle odds shift',
11214 ),
11215 GlobalPropertyTrait(
11216 ['',self._zeroBattleAF,GlobalPropertyTrait.DIRECT,'{0}'],
11217 name = self._battleAF,
11218 numeric = True,
11219 description = 'Zero battle AF',
11220 ),
11221 GlobalPropertyTrait(
11222 ['',self._zeroBattleDF,GlobalPropertyTrait.DIRECT,'{0}'],
11223 name = self._battleDF,
11224 numeric = True,
11225 description = 'Zero battle AF',
11226 ),
11227 # {wgBattleDF==0?0:(double(wgBattleAF)/wgBattleDF)}
11228 GlobalPropertyTrait(
11229 ['',self._zeroBattleFrac,GlobalPropertyTrait.DIRECT,'{0}'],
11230 ['',self._calcBattleFrac+'Real',GlobalPropertyTrait.DIRECT,
11231 '{BattleFraction}'],
11232 name = self._battleFrac,
11233 description = 'Calculate battle fraction',
11234 ),
11235 GlobalPropertyTrait(
11236 ['',self._zeroBattleIdx,GlobalPropertyTrait.DIRECT,'{0}'],
11237 ['',self._calcBattleIdx,GlobalPropertyTrait.DIRECT,
11238 '{OddsIndex}'],
11239 name = self._battleIdx,
11240 description = 'Calculate battle odds index',
11241 ),
11242 GlobalPropertyTrait(
11243 ['',self._zeroBattleOdds,GlobalPropertyTrait.DIRECT,'{""}'],
11244 ['',self._calcBattleOdds+'Real',GlobalPropertyTrait.DIRECT,
11245 f'{{{idx2Odds}}}'],
11246 name = self._battleOdds,
11247 description = 'Calculate battle odds',
11248 ),
11249 GlobalHotkeyTrait(name = '',# Forward to units
11250 key = self._calcBattleAF+'Trampoline',
11251 globalHotkey = self._calcBattleAF,
11252 description = 'Calculate total AF'),
11253 GlobalHotkeyTrait(name = '',# Forward to units
11254 key = self._calcBattleDF+'Trampoline',
11255 globalHotkey = self._calcBattleDF,
11256 description = 'Calculate total DF'),
11257 GlobalHotkeyTrait(name = '',# Forward to units
11258 key = self._calcBattleShft+'Trampoline',
11259 globalHotkey = self._calcBattleShft,
11260 description = 'Calculate total shift'),
11261 TriggerTrait(command = '',
11262 key = self._calcBattleAF,
11263 actionKeys = [self._zeroBattleAF,
11264 self._calcBattleAF+'Trampoline']),
11265 TriggerTrait(command = '',
11266 key = self._calcBattleDF,
11267 actionKeys = [self._zeroBattleDF,
11268 self._calcBattleDF+'Trampoline']),
11269 TriggerTrait(command = '',
11270 key = self._calcBattleShft,
11271 actionKeys = [self._zeroBattleShft,
11272 self._calcBattleShft+'Trampoline']),
11273 TriggerTrait(command = '',
11274 key = self._calcBattleFrac,
11275 actionKeys = [self._zeroBattleFrac,
11276 self._calcBattleAF,
11277 self._calcBattleDF,
11278 self._calcBattleFrac+'Real']),
11279 TriggerTrait(command = '',
11280 key = self._calcBattleOdds,
11281 actionKeys = [self._zeroBattleOdds,
11282 self._calcBattleFrac,
11283 self._calcBattleShft,
11284 self._calcBattleIdx,
11285 self._calcBattleOdds+'Real']),
11286 ReportTrait(self._zeroBattleAF,
11287 report=(f'{{{self._debug}?'
11288 f'("~ "+BasicName+": Reset AF: "+'
11289 f'{self._battleAF}):""}}')),
11290 ReportTrait(self._zeroBattleDF,
11291 report=(f'{{{self._debug}?'
11292 f'("~ "+BasicName+": Reset DF: "+'
11293 f'{self._battleDF}):""}}')),
11294 ReportTrait(self._zeroBattleFrac,
11295 report=(f'{{{self._debug}?'
11296 f'("~ "+BasicName+": Reset fraction: "+'
11297 f'{self._battleFrac}):""}}')),
11298 ReportTrait(self._zeroBattleOdds,
11299 report=(f'{{{self._debug}?'
11300 f'("~ "+BasicName+": Reset odds: "+'
11301 f'{self._battleOdds}):""}}')),
11302 ReportTrait(self._calcBattleAF,
11303 report=(f'{{{self._debug}?'
11304 f'("~ "+BasicName+": Total AF: "+'
11305 f'{self._battleAF}):""}}')),
11306 ReportTrait(self._calcBattleDF,
11307 report=(f'{{{self._debug}?'
11308 f'("~ "+BasicName+": Total DF: "+'
11309 f'{self._battleDF}):""}}')),
11310 ReportTrait(self._calcBattleShft,
11311 report=(f'{{{self._debug}?'
11312 f'("~ "+BasicName+": Battle odds shift: "+'
11313 f'{self._battleShift}):""}}')),
11314 ReportTrait(self._calcBattleFrac,
11315 report=(f'{{{self._debug}?'
11316 f'("~ "+BasicName+": Battle fraction: "+'
11317 f'{self._battleFrac}):""}}')),
11318 ReportTrait(self._calcBattleOdds,
11319 report=(f'{{{self._debug}?'
11320 f'("~ "+BasicName+": Battle odds: "+'
11321 f'{self._battleOdds}+" ("+'
11322 f'{self._battleIdx}+")"):""}}')),
11323 ReportTrait(self._calcBattleFrac+'Real',
11324 report=(f'{{{self._debug}?'
11325 f'("~ "+BasicName+": Battle fraction: "+'
11326 f'{self._battleFrac}+'
11327 f'" AF="+{self._battleAF}+'
11328 f'" DF="+{self._battleDF}'
11329 f'):""}}')),
11330 ReportTrait(self._calcBattleOdds+'Real',
11331 report=(f'{{{self._debug}?'
11332 f'("~ "+BasicName+": Battle odds: "+'
11333 f'{self._battleOdds}+'
11334 f'" ("+{self._battleIdx}+","+OddsShift+","+'
11335 f'" raw="+OddsIndexRaw+","+'
11336 f'" limited="+OddsIndexLimited+","+'
11337 f'" -> "+OddsIndex+","+'
11338 f'{self._battleShift}+")"+'
11339 f'" Fraction="+{self._battleFrac}+'
11340 f'" AF="+{self._battleAF}+'
11341 f'" DF="+{self._battleDF}'
11342 f'):""}}')),
11343 ReportTrait(self._calcBattleOdds+'Real',
11344 report=(f'{{{self._verbose}?'
11345 f'("! Battle # "'
11346 f'+{self._battleNo}'
11347 f'+" AF="+{self._battleAF}'
11348 f'+" DF="+{self._battleDF}'
11349 f'+" => "+{self._battleOdds}'
11350 # f'+" <img src=\'odds_marker_"'
11351 # f'+{self._battleOdds}+".png\' "'
11352 # f'+" width=24 height=24>"'
11353 f'):""}}')),
11354 MarkTrait(name=self._battleCalc,value=True),
11355 BasicTrait()]
11356 prototypes.addPrototype(name = self._battleCalc,
11357 description = '',
11358 traits = traits)
11359
11360 # ----------------------------------------------------------------
11361 def addBattleUnitPrototype(self,prototypes):
11362 # --- Battle units that set battle markers -------------------
11363 #
11364 # - Trait to add battle number 1 to max
11365 #
11366 # - Trigger trait for each of these using the global property
11367 # for the current battle
11368 #
11369 traits = [
11370 # getBattle retrieves the battle number from the global property.
11371 # clearBattle sets piece battle to -1
11372 DynamicPropertyTrait(['',self._getBattle,
11373 DynamicPropertyTrait.DIRECT,
11374 f'{{{self._currentBattle}}}'],
11375 ['',self._clearBattle,
11376 DynamicPropertyTrait.DIRECT,
11377 f'{{-1}}'],
11378 name = self._battleNo,
11379 numeric = True,
11380 value = f'{{-1}}',
11381 description = 'Set battle number'),
11382 # This setBattle sets current attacker in global property
11383 GlobalPropertyTrait(['',self._setBattle,
11384 GlobalPropertyTrait.DIRECT,
11385 '{IsAttacker}'],
11386 name = self._currentAttacker,
11387 numeric = True,
11388 description = 'Set attacker'),
11389 ReportTrait(self._getBattle,
11390 report=(f'{{{self._debug}?'
11391 f'("~ "+BasicName+" current battle # "+'
11392 f'{self._currentBattle}+" -> "+'
11393 f'{self._battleNo}):""}}')),
11394 ReportTrait(self._clearBattle,
11395 report=(f'{{{self._debug}?'
11396 f'("~ "+BasicName+" Clear this global="+'
11397 f'{self._currentBattle}+" this="+'
11398 f'{self._battleNo}):""}}')),
11399 ]
11400 place = []
11401 trig = []
11402 rept = []
11403 for i, bm in enumerate(self._battleMarks):
11404 kn = self._markBattle+str(i+1)
11405 path = PlaceTrait.SKEL_PATH.format('BattleMarkers',bm)
11406
11407 place.append(
11408 PlaceTrait(command = '',#f'Add battle marker {i}',
11409 key = kn,
11410 markerSpec = path,
11411 markerText = 'null',
11412 xOffset = -8,
11413 yOffset = -16,
11414 matchRotation = False,
11415 afterKey = self._getBattle,
11416 gpid = self._game.nextPieceSlotId(),
11417 description = f'Add battle marker {i+1}',
11418 placement = PlaceTrait.ABOVE,
11419 above = False))
11420 # Get current global battle number
11421 # Set current battle
11422 # Filtered on current global battle # is equal to
11423 trig.append(
11424 TriggerTrait(command = '',#Mark battle',
11425 key = self._markBattle,
11426 actionKeys = [self._getBattle,
11427 self._setBattle,kn],
11428 property = f'{{{self._currentBattle}=={i+1}}}'))
11429 rept.append(
11430 ReportTrait(kn,
11431 report=(f'{{{self._debug}?'
11432 f'("~ "+BasicName+" placing marker ({i+1})'
11433 f' ="+ {self._currentBattle}+"'
11434 f'={kn}"):""}}')))
11435
11436 oth = [
11437 GlobalHotkeyTrait(name = 'Declare battle',
11438 key = self._markKey,
11439 globalHotkey = self._markKey,
11440 description = 'Mark for combat'),
11441 GlobalPropertyTrait(
11442 ['',self._calcBattleAF,GlobalPropertyTrait.DIRECT,
11443 f'{{EffectiveAF+{self._battleAF}}}'],
11444 name = self._battleAF,
11445 numeric = True,
11446 description = 'Update battle AF'),
11447 GlobalPropertyTrait(
11448 ['',self._calcBattleDF,GlobalPropertyTrait.DIRECT,
11449 f'{{EffectiveDF+{self._battleDF}}}'],
11450 name = self._battleDF,
11451 numeric = True,
11452 description = 'Update battle AF'),
11453 GlobalPropertyTrait(
11454 ['',self._calcBattleShft,GlobalPropertyTrait.DIRECT,
11455 f'{{OddsShift}}'],
11456 name = self._battleShift,
11457 numeric = True,
11458 description = 'Update battle shift',
11459 ),
11460 CalculatedTrait(#This could be redefined in module
11461 name = 'EffectiveAF',
11462 expression = '{CF}',
11463 description = 'Current attack factor'),
11464 CalculatedTrait(#This could be redefined in module
11465 name = 'EffectiveDF',
11466 expression = '{DF}',
11467 description = 'Current defence factor'),
11468 CalculatedTrait(#This could be redefined in module
11469 name = 'IsAttacker',
11470 expression = '{Phase.contains(Faction)}',
11471 description = 'Check if current phase belongs to faction'),
11472 CalculatedTrait(#This could be redefined in module
11473 name = 'OddsShift',
11474 expression = f'{{{self._battleShift}}}',
11475 description = 'Check if current phase belongs to faction'),
11476 ReportTrait(self._calcBattleAF,
11477 report=(f'{{{self._verbose}?'
11478 f'("! "+BasicName+'
11479 f'" add "+EffectiveAF+'
11480 f'" to total attack factor -> "+'
11481 f'{self._battleAF}'
11482 f'):""}}')),
11483 ReportTrait(self._calcBattleDF,
11484 report=(f'{{{self._verbose}?'
11485 f'("! "+BasicName+'
11486 f'" add "+EffectiveDF+'
11487 f'" to total defence factor -> "+'
11488 f'{self._battleDF}'
11489 f'):""}}')),
11490 ReportTrait(self._calcBattleShft,
11491 report=(f'{{{self._debug}?'
11492 f'("~ "+BasicName+'
11493 f'" Updating odds shift with "+OddsShift+'
11494 f'" -> "+{self._battleShift}):""}}')),
11495 ]
11496 traits.extend(
11497 place+
11498 trig+
11499 oth+
11500 [MarkTrait(name=self._battleUnit,value=True),
11501 BasicTrait()])
11502 prototypes.addPrototype(name = self._battleUnit,
11503 description = '',
11504 traits = traits)
11505 # ----------------------------------------------------------------
11506 def addBattleCorePrototype(self,prototypes):
11507 # --- Core traits for battle markers (number, odds, results)
11508 # - Set the global current battle number
11509 # - Get the current global battle number
11510 # - Clear this counter
11511 # - Trampoline to global command to clear all marks for this battle
11512 traits = [
11513 # NoStackTrait(select = NoStackTrait.NORMAL_SELECT,
11514 # move = NoStackTrait.NORMAL_MOVE,
11515 # canStack = False,
11516 # ignoreGrid = False),
11517 GlobalPropertyTrait(['',self._setBattle,GlobalPropertyTrait.DIRECT,
11518 f'{{{self._battleNo}}}'],
11519 name = self._currentBattle,
11520 numeric = True,
11521 description = 'Set current battle'),
11522 GlobalPropertyTrait(['',self._setBattle, GlobalPropertyTrait.DIRECT,
11523 '{IsAttacker}'],
11524 name = self._currentAttacker,
11525 numeric = True,
11526 description = 'Set attacker'),
11527 DynamicPropertyTrait(['',self._getBattle,
11528 DynamicPropertyTrait.DIRECT,
11529 f'{{{self._currentBattle}}}'],
11530 name = self._battleNo,
11531 numeric = True,
11532 value = f'{{{self._battleNo}}}',
11533 description = 'Set battle number'),
11534 DynamicPropertyTrait(['',self._getBattle,
11535 DynamicPropertyTrait.DIRECT,
11536 f'{{{self._currentAttacker}}}'],
11537 name = 'IsAttacker',
11538 numeric = True,
11539 value = 'false',
11540 description = 'Set attacker'),
11541 DeleteTrait('',self._clearBattle),
11542 GlobalHotkeyTrait(name = '',
11543 key = self._clearBattle+'Trampo',
11544 globalHotkey = self._clearBattle,
11545 description = 'Clear selected battle'),
11546 TriggerTrait(command = 'Clear',
11547 key = self._clearKey,
11548 actionKeys = [self._setBattle,
11549 self._clearBattle+'Trampo']),
11550 ReportTrait(self._setBattle,
11551 report=(f'{{{self._debug}?'
11552 f'("~ "+BasicName+" battle # "+'
11553 f'{self._battleNo}+" -> "+'
11554 f'{self._currentBattle}):""}}')),
11555 ReportTrait(self._getBattle,
11556 report=(f'{{{self._debug}?'
11557 f'("~ "+BasicName+" current battle # "+'
11558 f'{self._currentBattle}+" -> "+'
11559 f'{self._battleNo}):""}}')),
11560 ReportTrait(self._clearBattle,
11561 report=(f'{{{self._debug}?'
11562 f'("~ "+BasicName+" Clear this global="+'
11563 f'{self._currentBattle}+" this="+'
11564 f'{self._battleNo}):""}}')),
11565 ReportTrait(self._clearKey,
11566 report=(f'{{{self._debug}?'
11567 f'("~ "+BasicName+" To clear battle # global="+'
11568 f'{self._currentBattle}+" this="+'
11569 f'{self._battleNo}):""}}')),
11570 ReportTrait(self._clearBattle+'Trampo',
11571 report=(f'{{{self._debug}?'
11572 f'("~ "+BasicName+" '
11573 f'Forward clear battle # global="+'
11574 f'{self._currentBattle}+" this="+'
11575 f'{self._battleNo}):""}}')),
11576 MarkTrait(name=self._battleMark,value=True),
11577 BasicTrait()
11578 ]
11579 prototypes.addPrototype(name = self._currentBattle,
11580 description = '',
11581 traits = traits)
11582
11583 # ----------------------------------------------------------------
11584 def addBattlePrototypes(self,prototypes):
11585 if not self.addBattleControlPrototype(prototypes):
11586 return
11587
11588 self.addBattleCalculatePrototype(prototypes)
11589 self.addBattleUnitPrototype(prototypes)
11590 self.addBattleCorePrototype(prototypes)
11591
11592 # ----------------------------------------------------------------
11593 def markerTraits(self):
11594 return [DeleteTrait(),
11595 RotateTrait()]
11596
11597 # ----------------------------------------------------------------
11598 def battleMarkerTraits(self,c):
11599 '''Derives from the CurrentBattle prototype and adds a submenu
11600 to place odds counter on the battle marker'''
11601 traits = [PrototypeTrait(name=self._currentBattle),
11602 NonRectangleTrait(filename = c['filename'],
11603 image = c['img'])]
11604
11605 subs = []
11606 ukeys = []
11607 place = []
11608 trig = []
11609 rept = []
11610 repp = []
11611 for i, odds in enumerate(self._oddsMarks):
11612 on = odds.replace('odds marker','').strip()
11613 om = odds.replace(':',r'\:')
11614 kn = self._markOdds+str(i+1)
11615 gpid = self._game.nextPieceSlotId()
11616 path = PlaceTrait.SKEL_PATH.format('OddsMarkers',om)
11617 subs.append(on)
11618
11619 place.append(
11620 PlaceTrait(command = '',
11621 key = kn,
11622 markerSpec = path,
11623 markerText = 'null',
11624 xOffset = -6,
11625 yOffset = -8,
11626 matchRotation = False,
11627 afterKey = self._getBattle+'Details',
11628 gpid = gpid,
11629 placement = PlaceTrait.ABOVE,
11630 description = f'Add odds marker {on}'))
11631 trig.append(
11632 TriggerTrait(name = '',
11633 command = on,
11634 key = kn+'real',
11635 actionKeys = [
11636 self._setBattle,
11637 kn]))
11638 rept.append(
11639 ReportTrait(kn+'real',
11640 report=(f'{{{self._debug}?'
11641 f'("~ "+BasicName+": Set odds '
11642 f'{on} ({kn})"):""}}')))
11643 repp.append(
11644 ReportTrait(kn,
11645 report=(f'{{{self._debug}?'
11646 f'("~ "+BasicName+": Place odds '
11647 f'{on} ({kn})"):""}}')))
11648 ukeys.append(kn+'real')
11649
11650 auto = []
11651 auton = []
11652 if len(self._oddsMarks) > 0:
11653 auton = ['Auto']
11654 for i, odds in enumerate(self._oddsMarks):
11655 trig.append(
11656 TriggerTrait(name = '',
11657 command = '',
11658 key = self._markOdds+'Auto',
11659 property = f'{{{self._battleIdx}=={i+1}}}',
11660 actionKeys = [self._markOdds+str(i+1)]))
11661
11662 auto = [GlobalHotkeyTrait(name = '',
11663 key = self._calcBattleOdds,
11664 globalHotkey = self._calcBattleOdds,
11665 description = 'Calculate fraction'),
11666 DeselectTrait(command = '',
11667 key = self._calcBattleOdds+'Deselect',
11668 deselect = DeselectTrait.ONLY),
11669 ReportTrait(self._calcBattleOdds+'Deselect',
11670 report=(f'{{{self._debug}?'
11671 f'("~ "+BasicName+": Select only this "'
11672 f'+" Attacker="+IsAttacker'
11673 f'):""}}')),
11674 TriggerTrait(name = '',
11675 command = '',
11676 key = self._markOdds+'Trampoline',
11677 actionKeys = [
11678 self._calcBattleOdds,
11679 self._markOdds+'Auto',
11680 self._calcBattleOdds+'Deselect'],
11681 property = f'{{!IsAttacker}}'
11682 ),
11683 TriggerTrait(name = '',
11684 command = 'Auto',
11685 key = self._calcBattleOdds+'Start',
11686 actionKeys = [
11687 self._setBattle,
11688 self._markOdds+'Trampoline',
11689 ]),
11690 ReportTrait(self._calcBattleOdds+'Start',
11691 report=(f'{{{self._debug}?'
11692 f'("~ "+BasicName+": Battle odds "+'
11693 f'{self._battleOdds}):""}}')),
11694 ReportTrait(self._markOdds+'Auto',
11695 report=(f'{{{self._debug}?'
11696 f'("~ "+BasicName+": '
11697 f'Auto battle odds "+'
11698 f'{self._battleOdds}):""}}'))
11699 ]
11700
11701 traits.extend([
11702 RestrictCommandsTrait(
11703 name='Hide when auto-odds are enabled',
11704 hideOrDisable = RestrictCommandsTrait.HIDE,
11705 expression = f'{{{self._autoOdds}==true}}',
11706 keys = ukeys)]+
11707 place
11708 +trig
11709 +auto
11710 +rept
11711 +repp)
11712 if len(subs) > 0:
11713 traits.extend([
11714 SubMenuTrait(subMenu = 'Odds',
11715 keys = auton+subs),
11716 ])
11717
11718 return traits
11719
11720 # ----------------------------------------------------------------
11721 def oddsMarkerTraits(self,c=None):
11722 '''Derives from the CurrentBattle prototype and adds a submenu
11723 to replace odds counter with result marker'''
11724 gpid = self._game.nextPieceSlotId()
11725 traits = [PrototypeTrait(name=self._currentBattle),
11726 MarkTrait(self._oddsMark,'true'),
11727 NonRectangleTrait(filename = c['filename'],
11728 image = c['img']),
11729 DynamicPropertyTrait(
11730 ['',self._getBattle+'More',DynamicPropertyTrait.DIRECT,
11731 (f'{{{self._battleAF}+" vs "+{self._battleDF}+'
11732 f'" (odds "+{self._battleOdds}+" shift "+'
11733 f'{self._battleShift}+")"}}')],
11734 name = 'BattleDetails',
11735 value = '',
11736 numeric = False,
11737 description = 'Stored battle details'),
11738 TriggerTrait(command = '',
11739 key = self._getBattle+'Details',
11740 actionKeys = [self._getBattle,
11741 self._getBattle+'More']),
11742 # DeleteTrait('',self._recalcOdds+'Delete'),
11743 # ReplaceTrait(command = '',
11744 # key = self._recalcOdds+'Replace',
11745 # markerSpec = '',
11746 # markerText = 'null',
11747 # xOffset = 0,
11748 # yOffset = 0,
11749 # matchRotation = False,
11750 # afterKey = '',
11751 # gpid = gpid,
11752 # description = f'Replace with nothing'),
11753 GlobalHotkeyTrait(name = '',
11754 key = self._calcBattleOdds+'Start',
11755 globalHotkey = self._calcBattleOdds+'ReAuto',
11756 description = 'Trampoline to global'),
11757 # Recalculate odds
11758 # First setBatle to make battle No global
11759 # Then delete this
11760 # Then send global key command
11761 TriggerTrait(command = 'Recalculate',
11762 key = self._recalcOdds,
11763 actionKeys = [self._setBattle,
11764 self._calcBattleOdds+'Start',
11765 self._clearBattle,
11766 ]),
11767 ReportTrait(self._recalcOdds+'Delete',
11768 report=(f'{{{self._debug}?'
11769 f'("~ "+BasicName+'
11770 f'": Deleting self"):""}}')),
11771 ReportTrait(self._clearBattle,
11772 report=(f'{{{self._debug}?'
11773 f'("~ "+BasicName+'
11774 f'": Remove"):""}}')),
11775 ReportTrait(self._recalcOdds,
11776 report=(f'{{{self._debug}?'
11777 f'("! Recalculate Odds"):""}}')),
11778 ReportTrait(self._calcBattleOdds+'Start',
11779 report=(f'{{{self._debug}?'
11780 f'("~ Start auto recalculate Odds"):""}}')),
11781 ]
11782
11783 subs = []
11784 place = []
11785 trig = []
11786 rept = []
11787 ukeys = [self._recalcOdds]
11788 first = ''
11789 for i, result in enumerate(self._resultMarks):
11790 r = result.replace('result marker','').strip()
11791 kn = self._markResult+str(i+1)
11792 gpid = self._game.nextPieceSlotId()
11793 ukeys.append(kn+'real')
11794 subs.append(r)
11795 if first == '': first = r
11796
11797 path = PlaceTrait.SKEL_PATH.format('ResultMarkers',result)
11798
11799 place.append(
11800 ReplaceTrait(command = '',
11801 key = kn,
11802 markerSpec = path,
11803 markerText = 'null',
11804 xOffset = -6,
11805 yOffset = -8,
11806 matchRotation = False,
11807 afterKey = self._getBattle,
11808 gpid = gpid,
11809 description = f'Add result marker {r}'))
11810 trig.append(
11811 TriggerTrait(name = '',
11812 command = r,
11813 key = kn+'real',
11814 actionKeys = [
11815 self._setBattle,
11816 kn]))
11817 rept.append(
11818 ReportTrait(kn+'real',
11819 report=(f'{{{self._debug}?'
11820 f'("~ "+BasicName+" setting result '
11821 f'{r}"):""}}')))
11822
11823 auto = []
11824 auton = []
11825 if len(self._resultMarks) > 0:
11826 auton = ['Auto']
11827 for i, res in enumerate(self._resultMarks):
11828 r = res.replace('result marker','').strip()
11829 trig.append(
11830 TriggerTrait(
11831 name = '',
11832 command = '',
11833 key = self._markResult+'Auto',
11834 property = f'{{{self._battleResult}=="{r}"}}',
11835 actionKeys = [self._markResult+str(i+1)]))
11836
11837 auto = [ # Override in the module
11838 CalculatedTrait(
11839 name = 'Die',
11840 expression = '{GetProperty("1d6_result")}',
11841 description = 'Die roll'),
11842 GlobalHotkeyTrait(
11843 name = '',
11844 key = self._rollDice,
11845 globalHotkey = self._diceKey,
11846 description = 'Roll dice'),
11847 CalculatedTrait(
11848 name = 'BattleResult',
11849 expression = f'{{"{first}"}}',
11850 ),
11851 GlobalPropertyTrait(
11852 ['',self._calcBattleRes+'real',GlobalPropertyTrait.DIRECT,
11853 '{BattleResult}'],
11854 name = self._battleResult,
11855 numeric = False,
11856 description = 'Set combat result'),
11857 TriggerTrait(name = '',
11858 command = 'Resolve',
11859 key = self._resolveKey,
11860 property = f'{{{self._autoResults}==true}}',
11861 actionKeys = [
11862 self._setBattle,
11863 self._rollDice,
11864 self._calcBattleRes+'real',
11865 self._markResult+'Auto',
11866 ]),
11867 ReportTrait(self._calcBattleRes,
11868 report=(f'{{{self._debug}?'
11869 f'("~ "+BasicName+": Battle result "+'
11870 f'{self._battleOdds}):""}}')),
11871 ReportTrait(self._markResult+'Auto',
11872 report=(f'{{{self._debug}?'
11873 f'("~ "+BasicName+": Auto battle result "+'
11874 f'{self._battleResult}):""}}')),
11875 ReportTrait(self._markResult+'Auto',
11876 report=(f'{{"` Battle # "+{self._battleNo}+": "+'
11877 f'BattleDetails+'
11878 f'" with die roll "+Die+": "+'
11879 f'{self._battleResult}'
11880 # f'+ "<img src=\'result_marker_"'
11881 # f'+{self._battleResult}+".png\'"'
11882 # f'+" width=24 height=24>"'
11883 f'}}')),
11884 MarkTrait(name=self._battleOddsM,value='true')
11885 ]
11886
11887 traits.extend(
11888 [RestrictCommandsTrait(
11889 name='Hide when auto-results are enabled',
11890 hideOrDisable = RestrictCommandsTrait.HIDE,
11891 expression = f'{{{self._autoResults}==true}}',
11892 keys = ukeys)]+
11893 place
11894 +trig
11895 +auto)
11896
11897 if len(subs) > 0:
11898 traits.append(SubMenuTrait(subMenu = 'Result',
11899 keys = subs))
11900
11901 return traits
11902
11903 # ----------------------------------------------------------------
11904 def resultMarkerTraits(self,c=None):
11905 traits = [PrototypeTrait(name=self._currentBattle),
11906 NonRectangleTrait(filename = c['filename'],
11907 image = c['img'])]
11908
11909 return traits
11910
11911 # ----------------------------------------------------------------
11912 def factionTraits(self,faction):
11913 offX = 36 * self._counterScale * self._resolution/150
11914 offY = -38 * self._counterScale * self._resolution/150
11915 traits = [#ReportTrait(self._eliminateKey,
11916 # self._restoreKey,
11917 # self._trailKey),
11918 TrailTrait(lineWidth = 5,
11919 radius = 10,
11920 key = self._trailKey),
11921 RotateTrait(),
11922 MovedTrait(xoff = int(offX),yoff = int(offY)),
11923 DeleteTrait(),
11924 SendtoTrait(mapName = 'DeadMap',
11925 boardName = f'{faction} pool',
11926 name = 'Eliminate',
11927 key = self._eliminateKey,
11928 restoreName = 'Restore',
11929 restoreKey = self._restoreKey,
11930 description = 'Eliminate unit'),
11931 # ReportTrait(self._trailKey,
11932 # f'{{"Enabling trail on "+BasicName}}'),
11933 PrototypeTrait(name=self._battleUnit),
11934 MarkTrait(name='Faction',value=faction)]
11935
11936 return traits
11937
11938 # ----------------------------------------------------------------
11939 def getFactors(self,val):
11940 cf = None
11941 mf = None
11942 df = None
11943 ra = None
11944 try:
11945 if 'chit 1 factor' in val:
11946 vv = val.replace('chit 1 factor=','')
11947 cf = int(vv)
11948 elif 'chit 2 factors artillery' in val:
11949 vv = val.replace('chit 2 factors artillery=','')
11950 cf,mf,ra = [int(v) for v in vv.strip('=').split()]
11951 elif 'chit 2 factors' in val:
11952 vv = val.replace('chit 2 factors=','')
11953 cf,mf = [int(v) for v in vv.split()]
11954 elif 'chit 3 factors' in val:
11955 vv = val.replace('chit 3 factors=','')
11956 cf,df,mf = [int(v) for v in vv.split()]
11957
11958 # Set defensive factor combat factor if not defined.
11959 if df is None and cf is not None:
11960 df = cf
11961
11962
11963 except Exception as e:
11964 print(f'\nWarning when extracting factors: {e} '
11965 f'in "{val}" -> "{vv}"')
11966 return None,None,None,None
11967 pass
11968
11969 return cf,df,mf,ra
11970
11971 # ----------------------------------------------------------------
11972 def pieceTraits(self,subn,subc,cn,c):
11973 from re import sub
11974
11975 bb = self.getBB(c['img'])
11976 height = bb[3]-bb[1] if bb is not None else 1
11977 width = bb[2]-bb[0] if bb is not None else 1
11978
11979 cf = subc.get(cn + ' flipped', None)
11980 traits = [PrototypeTrait(name=f'{subn} prototype')]
11981
11982 def clean(s):
11983 return s.strip().replace(',',' ').replace('/',' ').strip()
11984
11985 if not self._nonato:
11986 mains = c.get('mains','')
11987 mm = clean(mains).strip()
11988 traits.append(PrototypeTrait(name=f'{mm} prototype'))
11989 # Commented code adds all 'main' types as prototypes, which
11990 # doesn't make so much sense
11991 #
11992 # m = set([clean(m) for m in mains.split(',')])
11993 # traits.extend([PrototypeTrait(name=f'{m.strip()} prototype')
11994 # for m in set(m)])
11995 for p in ['echelon','command']:
11996 val = c.get(p,None)
11997 if val is not None:
11998 pv = f'{val.strip()} prototype'
11999 traits.append(PrototypeTrait(name=pv))
12000
12001 if cf is not None:
12002 traits.extend([
12003 LayerTrait(images = [c['filename'],
12004 cf['filename']],
12005 newNames = ['','Reduced +'],
12006 activateName = '',
12007 decreaseName = '',
12008 increaseName = 'Flip',
12009 increaseKey = self._flipKey,
12010 decreaseKey = '',
12011 name = 'Step'),
12012 ReportTrait(self._flipKey)])
12013
12014 if not self._nochit:
12015 def clean(value):
12016 return sub(r'\[[^=]+\]=','',value)\
12017 .replace('{','')\
12018 .replace('}','')\
12019 .replace('/',' ')\
12020 .replace(',',' ')\
12021 .replace('\\',' ')
12022
12023 # Add extra marks. This may be useful later on.
12024 for field in ['upper left', 'upper right',
12025 'lower left', 'lower right',
12026 'left', 'right',
12027 'factors']:
12028 value = c.get('chit',{}).get(field,None)
12029 if value is None:
12030 continue
12031 val = clean(value)
12032 val = val\
12033 .replace('chit identifier=','')\
12034 .replace('chit small identifier=','')
12035
12036 traits.append(MarkTrait(name = field, value = val))
12037
12038 if field != 'factors': continue
12039
12040 af, df, mf, ra = self.getFactors(val)
12041 saf, sdf, smf, sra = None,None,None,None
12042 if cf is not None:
12043 value = cf.get('chit',{}).get(field,None)
12044 if value is not None:
12045 val = clean(value)
12046 val = val\
12047 .replace('chit identifier=','')\
12048 .replace('chit small identifier=','')
12049 saf, sdf, smf, sra = self.getFactors(val)
12050
12051 rf = []
12052 srf = []
12053 for f,sf,n in [[af,saf,'CF'],
12054 [df,sdf,'DF'],
12055 [mf,smf,'MF'],
12056 [ra,sra,'Range']]:
12057 if f is None: continue
12058
12059 if sf is None:
12060 rf.append(MarkTrait(name=n,value=f))
12061 else:
12062 rf .append(MarkTrait(name='Full'+n, value=f))
12063 srf.append(MarkTrait(name='Reduced'+n,value=sf))
12064 traits.append(CalculatedTrait(
12065 name = n,
12066 expression = (f'{{(Step_Level==2)?'
12067 f'Reduced{n}:Full{n}}}')))
12068
12069 traits.extend(rf+srf)
12070
12071
12072
12073
12074
12075
12076 return height, width, traits
12077
12078 # ----------------------------------------------------------------
12079 def addCounters(self):
12080 '''Add all counters (pieces) element to the module.
12081 Prototypes are also created as part of this.
12082 '''
12083 from re import sub
12084
12085 with VerboseGuard('Adding counters') as v:
12086 protos = self._game.addPrototypes()
12087
12088 self.addNatoPrototypes(protos)
12089 self.addBattlePrototypes(protos)
12090
12091 pieces = self._game.addPieceWindow(name = 'Counters',
12092 icon = self.getIcon('unit-icon',
12093 '/images/counter.gif'),
12094 hotkey = self._countersKey)
12095 tabs = pieces.addTabs(entryName='Counters')
12096
12097 for subn, subc in self._categories.get('counter',{}).items():
12098
12099 subn = subn.strip()
12100 panel = tabs.addPanel(entryName = subn, fixed = False)
12101 plist = panel.addList(entryName = f'{subn} counters')
12102
12103 traits = []
12104 if subn in ['BattleMarkers']:
12105 traits = self.battleMarkerTraits(list(subc.values())[0])
12106 elif subn in ['OddsMarkers']:
12107 traits = self.oddsMarkerTraits(list(subc.values())[0])
12108 elif subn in ['ResultMarkers']:
12109 traits = self.resultMarkerTraits(list(subc.values())[0])
12110 elif subn.lower() in ['marker', 'markers']:
12111 traits = self.markerTraits()
12112 else:
12113 traits = self.factionTraits(subn)
12114
12115 traits.append(BasicTrait())
12116
12117 p = protos.addPrototype(name = f'{subn} prototype',
12118 description = f'Prototype for {subn}',
12119 traits = traits)
12120 v('')
12121
12122 with VerboseGuard(f'Adding pieces for "{subn}"') as vv:
12123 for i, (cn, c) in enumerate(subc.items()):
12124 if cn.endswith('flipped'): continue
12125
12126 if i == 0: v('',end='')
12127 vv(f'[{cn}',end='',flush=True,noindent=True)
12128
12129 height, width, traits = self.pieceTraits(subn,subc,cn,c)
12130 if cn == self._hiddenName:
12131 traits = [
12132 PrototypeTrait(name=self._battleCtrl),
12133 PrototypeTrait(name=self._battleCalc)]
12134 if self._diceInit is not None:
12135 traits.extend(self._diceInit)
12136 traits.append(
12137 RestrictAccessTrait(sides=[],
12138 description='Fixed'))
12139
12140
12141 #if cn.startswith('odds marker'):
12142 # cn = cn.replace(':','_')
12143
12144 gpid = self._game.nextPieceSlotId()
12145 traits.extend([BasicTrait(name = c['name'],
12146 filename = c['filename'],
12147 gpid = gpid)])
12148
12149 ps = plist.addPieceSlot(entryName = cn,
12150 gpid = gpid,
12151 height = height,
12152 width = width,
12153 traits = traits)
12154 if cn == self._hiddenName:
12155 self._hidden = ps
12156 vv('] ',end='',flush=True,noindent=True)
12157
12158 vv('')
12159
12160
12161 # ----------------------------------------------------------------
12162 def addNotes(self,**kwargs):
12163 '''Add a `Notes` element to the module
12164
12165 Parameters
12166 ----------
12167 kwargs : dict
12168 Dictionary of attribute key-value pairs
12169 '''
12170 self._game.addNotes(**kwargs)
12171
12172 # ----------------------------------------------------------------
12173 def addInventory(self,**kwargs):
12174 '''Add a `Inventory` element to module
12175
12176 Parameters
12177 ----------
12178 kwargs : dict
12179 Dictionary of attribute key-value pairs
12180 '''
12181 filt = '{' + '||'.join([f'Faction=="{s}"' for s in self._sides])+'}'
12182 grp = 'Faction,Command,Echelon,Type'
12183 self._game.addInventory(include = filt,
12184 groupBy = grp,
12185 sortFormat = '$PieceName$',
12186 tooltip ='Show inventory of all pieces',
12187 zoomOn = True,
12188 **kwargs)
12189
12190 # ----------------------------------------------------------------
12191 def addBoard(self,name,info,hasFlipped=False):
12192 '''Add a `Board` element to module
12193
12194 Parameters
12195 ----------
12196 name : str
12197 Name of board
12198 info : dict
12199 Information on board image
12200 hasFlipped : bool
12201 True if any piece can be flipped
12202 '''
12203 with VerboseGuard(f'Adding board {name}') as v:
12204 # from pprint import pprint
12205 # pprint(info)
12206 map = self._game.addMap(mapName=name,
12207 markUnmovedHotkey=self._clearMoved)
12208 map.addCounterDetailViewer(
12209 propertyFilter=f'{{{self._battleMark}!=true}}',
12210 fontSize = 14,
12211 summaryReportFormat = '<b>$LocationName$</b>',
12212 hotkey = key('\n'),
12213 stopAfterShowing = True
12214 )
12215 map.addHidePiecesButton()
12216 map.addGlobalMap()
12217 # Basics
12218 map.addStackMetrics()
12219 map.addImageSaver()
12220 map.addTextSaver()
12221 map.addForwardToChatter()
12222 map.addMenuDisplayer()
12223 map.addMapCenterer()
12224 map.addStackExpander()
12225 map.addPieceMover()
12226 map.addKeyBufferer()
12227 map.addSelectionHighlighters()
12228 map.addHighlightLastMoved()
12229 map.addZoomer()
12230
12231 map.addMassKey(name = 'Eliminate',
12232 buttonHotkey = self._eliminateKey,
12233 hotkey = self._eliminateKey,
12234 icon = self.getIcon('eliminate-icon',
12235 '/icons/16x16/edit-undo.png'),
12236 tooltip = 'Eliminate selected units')
12237 map.addMassKey(name = 'Delete',
12238 buttonHotkey = self._deleteKey,
12239 hotkey = self._deleteKey,
12240 icon = self.getIcon('delete-icon',
12241 '/icons/16x16/no.png'),
12242 tooltip = 'Delete selected units')
12243 map.addMassKey(name = 'Trail',
12244 buttonHotkey = self._trailKey,
12245 hotkey = self._trailKey,
12246 icon = '',
12247 tooltip = '')
12248 map.addMassKey(name='Rotate CW',
12249 buttonHotkey = self._rotateCWKey,
12250 hotkey = self._rotateCWKey,
12251 icon = '', #/icons/16x16/no.png',
12252 tooltip = 'Rotate selected units')
12253 map.addMassKey(name='Rotate CCW',
12254 buttonHotkey = self._rotateCCWKey,
12255 hotkey = self._rotateCCWKey,
12256 icon = '', #/icons/16x16/no.png',
12257 tooltip = 'Rotate selected units')
12258 map.addMassKey(name='Phase clear moved markers',
12259 buttonHotkey = self._clearMoved+'Phase',
12260 hotkey = self._clearMoved+'Trampoline',
12261 canDisable = True,
12262 target = '',
12263 filter = f'{{{self._battleCtrl}==true}}',
12264 propertyGate = f'{self._noClearMoves}',
12265 icon = '', #/icons/16x16/no.png',
12266 tooltip = 'Phase clear moved markers',
12267 reportFormat = (f'{{{self._debug}?'
12268 f'("~ {name}: '
12269 f'Phase Clear moved markers "+'
12270 f'{self._noClearMoves})'
12271 f':""}}'))
12272 if hasFlipped:
12273 map.addMassKey(name = 'Flip',
12274 buttonHotkey = self._flipKey,
12275 hotkey = self._flipKey,
12276 icon = self.getIcon('flip-icon',
12277 '/images/Undo16.gif'),
12278 tooltip = 'Flip selected units')
12279
12280 if len(self._battleMarks) > 0:
12281 v(f'Adding battle mark interface')
12282 ctrlSel = f'{{{self._battleCtrl}==true}}'
12283 oddsSel = f'{{{self._battleMark}==true}}'
12284 calcSel = f'{{{self._battleCalc}==true}}'
12285 curSel = (f'{{{self._battleNo}=={self._currentBattle}}}')
12286 curAtt = (f'{{{self._battleNo}=={self._currentBattle}&&'
12287 f'{self._battleUnit}==true&&'
12288 f'IsAttacker==true}}')
12289 curDef = (f'{{{self._battleNo}=={self._currentBattle}&&'
12290 f'{self._battleUnit}==true&&'
12291 f'IsAttacker==false}}')
12292 curUnt = (f'{{{self._battleNo}=={self._currentBattle}&&'
12293 f'{self._battleUnit}==true}}')
12294 markSel = (f'{{{self._battleNo}=={self._currentBattle}&&'
12295 f'{self._battleMark}==true&&'
12296 f'{self._oddsMark}!=true}}')
12297
12298 # ctrlSel = '{BasicName=="wg hidden unit"}'
12299 map.addMassKey(name = 'User mark battle',
12300 buttonHotkey = self._markKey,
12301 buttonText = '',
12302 hotkey = self._markBattle,
12303 icon = f'battle-marker-icon.{self._img_format}',
12304 tooltip = 'Mark battle',
12305 target = '',
12306 singleMap = False,
12307 filter = ctrlSel,
12308 reportFormat = (f'{{{self._debug}?'
12309 f'("~ {name}: '
12310 f'User marks battle # "+'
12311 f'{self._currentBattle})'
12312 f':""}}'))
12313 map.addMassKey(name = 'Selected mark battle',
12314 buttonHotkey = self._markBattle,
12315 hotkey = self._markBattle,
12316 icon = '',
12317 tooltip = '',
12318 singleMap = False,
12319 reportFormat = (f'{{{self._debug}?'
12320 f'("~ {name}: '
12321 f'Mark battle # "+'
12322 f'{self._currentBattle})'
12323 f':""}}'))
12324 map.addMassKey(name = 'Clear current battle',
12325 buttonText = '',
12326 buttonHotkey = self._clearBattle,
12327 hotkey = self._clearBattle,
12328 icon = '',
12329 tooltip = '',
12330 target = '',
12331 singleMap = False,
12332 filter = curSel,
12333 reportFormat = (f'{{{self._debug}?'
12334 f'("~ {name}: '
12335 f'Clear battle # "+'
12336 f'{self._currentBattle})'
12337 f':""}}'))
12338 map.addMassKey(name = 'Clear selected battle',
12339 buttonText = '',
12340 buttonHotkey = self._clearKey,
12341 hotkey = self._clearKey,
12342 icon = '',
12343 tooltip = '',
12344 singleMap = False,
12345 reportFormat = (f'{{{self._debug}?'
12346 f'("~ {name}: '
12347 f'Clear battle # "+'
12348 f'{self._currentBattle})'
12349 f':""}}'))
12350 map.addMassKey(name = 'Clear all battles',
12351 buttonText = '',
12352 buttonHotkey = self._clearAllBattle,
12353 hotkey = self._clearBattle,
12354 icon = '',
12355 tooltip = '',
12356 target = '',
12357 singleMap = False,
12358 reportFormat = (f'{{{self._debug}?'
12359 f'("~ {name}: '
12360 f'Clear all battle markers")'
12361 f':""}}'))
12362 map.addMassKey(name = 'User clear all battles',
12363 buttonText = '',
12364 buttonHotkey = self._clearAllKey,
12365 hotkey = self._clearAllBattle,
12366 icon = f'clear-battles-icon.{self._img_format}',
12367 tooltip = 'Clear all battles',
12368 target = '',
12369 singleMap = False,
12370 filter = ctrlSel,
12371 reportFormat = (f'{{{self._debug}?'
12372 f'("~ {name}: '
12373 f'User clears battle markers")'
12374 f':""}}'))
12375 map.addMassKey(name = 'Phase clear all battles',
12376 buttonText = '',
12377 buttonHotkey = self._clearBattlePhs,
12378 hotkey = self._clearAllBattle,
12379 icon = '',
12380 tooltip = 'Clear all battles',
12381 canDisable = True,
12382 propertyGate = f'{self._noClearBattles}',
12383 target = '',
12384 singleMap = False,
12385 filter = ctrlSel,
12386 reportFormat = (f'{{{self._debug}?'
12387 f'("~ {name}: '
12388 f'Phase clears battle markers "+'
12389 f'{self._noClearBattles})'
12390 f':""}}'))
12391 map.addMassKey(name = 'Selected resolve battle',
12392 buttonHotkey = self._resolveKey,
12393 hotkey = self._resolveKey,
12394 icon = f'resolve-battles-icon.{self._img_format}',
12395 tooltip = 'Resolve battle',
12396 singleMap = False,
12397 filter = oddsSel,
12398 reportFormat = (f'{{{self._debug}?'
12399 f'("~ {name}: '
12400 f'Resolve battle # "+'
12401 f'{self._currentBattle})'
12402 f':""}}'))
12403 map.addMassKey(name = 'Sum AFs',
12404 buttonText = '',
12405 buttonHotkey = self._calcBattleAF,
12406 hotkey = self._calcBattleAF,
12407 icon = '',
12408 tooltip = '',
12409 target = '',
12410 singleMap = False,
12411 filter = curAtt,
12412 reportFormat = (f'{{{self._debug}?'
12413 f'("~ {name}: '
12414 f'Calculate total AF"):""}}'))
12415 map.addMassKey(name = 'Sum DFs',
12416 buttonText = '',
12417 buttonHotkey = self._calcBattleDF,
12418 hotkey = self._calcBattleDF,
12419 icon = '',
12420 tooltip = '',
12421 target = '',
12422 singleMap = False,
12423 filter = curDef,
12424 reportFormat = (f'{{{self._debug}?'
12425 f'("~ {name}: '
12426 f'Calculate total DF"):""}}'))
12427 map.addMassKey(name = 'Sum odds shifts',
12428 buttonText = '',
12429 buttonHotkey = self._calcBattleShft,
12430 hotkey = self._calcBattleShft,
12431 icon = '',
12432 tooltip = '',
12433 target = '',
12434 singleMap = False,
12435 filter = curUnt,
12436 reportFormat = (f'{{{self._debug}?'
12437 f'("~ {name}: '
12438 f'Calculate odds shift"):""}}'))
12439 map.addMassKey(name = 'Calc battle odds',
12440 buttonText = '',
12441 buttonHotkey = self._calcBattleOdds,
12442 hotkey = self._calcBattleOdds,
12443 icon = '',
12444 tooltip = '',
12445 target = '',
12446 singleMap = False,
12447 filter = calcSel,
12448 reportFormat = (f'{{{self._debug}?'
12449 f'("~ {name}: '
12450 f'Calculate odds"):""}}'))
12451 map.addMassKey(name = 'Auto calc battle odds',
12452 buttonText = '',
12453 buttonHotkey = self._calcBattleOdds+'Auto',
12454 hotkey = self._calcBattleOdds+'Start',
12455 icon = '',
12456 tooltip = '',
12457 # target = '',
12458 singleMap = False,
12459 filter = markSel,
12460 reportFormat = (f'{{{self._debug}?'
12461 f'("~ {name}: '
12462 f'Auto calculate odds"):""}}'))
12463 map.addMassKey(name = 'User recalc',
12464 buttonHotkey = self._recalcOdds,
12465 buttonText = '',
12466 hotkey = self._recalcOdds,
12467 icon = '',
12468 tooltip = 'Recalculate odds',
12469 singleMap = False,
12470 filter = '',
12471 reportFormat = (f'{{{self._debug}?'
12472 f'("~ {name}: '
12473 f'Recalculate odds"):""}}'))
12474 map.addMassKey(name = 'Auto recalc battle odds',
12475 buttonText = '',
12476 buttonHotkey = self._calcBattleOdds+'ReAuto',
12477 hotkey = self._calcBattleOdds+'Start',
12478 icon = '',
12479 tooltip = '',
12480 target = '',
12481 singleMap = False,
12482 filter = markSel,
12483 reportFormat = (f'{{{self._debug}?'
12484 f'("~ {name}: '
12485 f'Auto re-calculate odds"):""}}'))
12486
12487
12488 v(f'Getting the board dimensions')
12489 ulx,uly,lrx,lry = self.getBB(info['img'])
12490 width = int(abs(ulx - lrx))
12491 height = int(abs(uly - lry))
12492 # Why is it we take the width and height like this?
12493 # Do they every differ from the above?
12494 # This is the only place that we actually use this
12495 #
12496 # width, height = self.getWH(info['img'])
12497 height += 20
12498 width += 5
12499 # v(f'{ulx},{uly},{lrx},{lry}')
12500
12501 v(f'Board BB=({lrx},{lry})x({ulx},{uly}) {width}x{height}')
12502 picker = map.addBoardPicker()
12503 board = picker.addBoard(name = name,
12504 image = info['filename'],
12505 width = width,
12506 height = height)
12507 zoned = board.addZonedGrid()
12508 zoned.addHighlighter()
12509
12510 if not 'zones' in info:
12511 color = rgb(255,0,0)
12512 full = zoned.addZone(name = 'full',
12513 useParentGrid = False,
12514 path=(f'{ulx},{uly};' +
12515 f'{lrx},{uly};' +
12516 f'{lrx},{lry};' +
12517 f'{ulx},{lry}'))
12518 grid = full.addHexGrid(color = color,
12519 dx = HEX_WIDTH,
12520 dy = HEX_HEIGHT,
12521 visible = self._visible)
12522 grid.addNumbering(color = color,
12523 hType = 'A',
12524 hOff = -1,
12525 vType = 'N',
12526 vOff = -1,
12527 visible = self._visible)
12528 return
12529
12530 w = abs(ulx-lrx)
12531 h = abs(uly-lry)
12532 self.addZones(zoned,name,info['zones'],w,h)
12533
12534 if self._hidden is not None:
12535 v(f'Adding hidden unit to map {name}')
12536 at = map.addAtStart(name = self._hiddenName,
12537 location = '',
12538 useGridLocation = False,
12539 owningBoard = name,
12540 x = 0,
12541 y = 0)
12542 at.addPieces(self._hidden)
12543
12544
12545 # ----------------------------------------------------------------
12546 def addDeadMap(self):
12547 '''Add a "Dead Map" element to the module
12548 '''
12549 name = 'DeadMap'
12550 with VerboseGuard(f'Adding deadmap {name}') as v:
12551 map = self._game.addMap(mapName = name,
12552 buttonName = '',
12553 markMoved = 'Never',
12554 launch = True,
12555 icon = self.getIcon('pool-icon',
12556 '/images/playerAway.gif'),
12557 allowMultiple = True,
12558 hotkey = self._deadKey)
12559 # Basics
12560 map.addStackMetrics()
12561 map.addImageSaver()
12562 map.addTextSaver()
12563 map.addForwardToChatter()
12564 map.addMenuDisplayer()
12565 map.addMapCenterer()
12566 map.addStackExpander()
12567 map.addPieceMover()
12568 map.addKeyBufferer()
12569 map.addSelectionHighlighters()
12570 map.addHighlightLastMoved()
12571 map.addZoomer()
12572
12573 map.addMassKey(name='Restore',
12574 buttonHotkey = self._restoreKey,
12575 hotkey = self._restoreKey,
12576 icon = self.getIcon('restore-icon',
12577 '/images/Undo16.gif'),
12578 tooltip = 'Restore selected units')
12579
12580 picker = map.addBoardPicker()
12581 picker.addSetup(maxColumns=len(self._sides),mapName=name,
12582 boardNames=[s+' pool' for s in self._sides])
12583
12584 for i, s in enumerate(self._sides):
12585 v(f'Adding {s} pool')
12586 color = [0,0,0,64]
12587 color[i % 3] = 255
12588 w = 400
12589 h = 400
12590 c = rgba(*color)
12591 img = ''
12592 dimg = self._categories.get('pool',{}).get('all',{})\
12593 .get(s,None)
12594
12595 if dimg:
12596 bb = self.getBB(dimg['img'])
12597 w = bb[2] - bb[0]
12598 h = bb[3] - bb[1]
12599 c = ''
12600 img = dimg['filename']
12601 v(f'Using image provided by user {img}')
12602
12603 board = picker.addBoard(name = f'{s} pool',
12604 image = img,
12605 width = w,
12606 height = h,
12607 color = c)
12608
12609 if dimg is None or not 'zones' in dimg:
12610 continue
12611
12612 zoned = board.addZonedGrid()
12613 zoned.addHighlighter()
12614 w = abs(w)
12615 h = abs(h)
12616 self.addZones(zoned,board['name'],dimg['zones'],w,h)
12617
12618
12619 # --------------------------------------------------------------------
12620 def getPictureInfo(self,picture,name,width,height):
12621 '''
12622 Returns
12623 -------
12624 hex_width, hex_height : float, float
12625 Scale hex width
12626 scx, scy : float, float, float, float
12627 Scale to image and picture (x,y)
12628 rot90 : bool
12629 True if rotated +/-90 degrees
12630 tran : callable
12631 Translation function
12632 '''
12633 if picture is None:
12634 print(f'WARNING: No Tikz picture information.'
12635 f"Are you sure you used the `[zoned]' option for the "
12636 f"tikzpicture environment of {name}?")
12637 f = lambda x,y: (x,y)
12638 return HEX_WIDTH,HEX_HEIGHT,1,1,False,f
12639
12640 # Get picture bounding box
12641 tll = picture['lower left']
12642 tur = picture['upper right']
12643 # Get picture transformation
12644 pa = picture['xx']
12645 pb = picture['xy']
12646 pc = picture['yx']
12647 pd = picture['yy']
12648 # Get picture offset (always 0,0?)
12649 pdx = picture['dx']
12650 pdy = picture['dy']
12651 # Define picture global transformation
12652 pr = lambda x,y: (pa * x + pc * y, pb * x + pd * y)
12653 # Globally transform (rotate) picture bounding box
12654 pll = pr(*tll)
12655 pur = pr(*tur)
12656 # Calculate widht, height, and scaling factors
12657 pw = pur[0] - pll[0]
12658 ph = pur[1] - pll[1]
12659 scw = width / pw
12660 sch = height / ph
12661 # Extract picture scales and rotation
12662 # Courtesy of
12663 # https://math.stackexchange.com/questions/13150/extracting-rotation-scale-values-from-2d-transformation-matrix
12664 from math import sqrt, atan2, degrees, isclose
12665 psx = sqrt(pa**2 + pb**2) # * (-1 if pa < 0 else 1)
12666 psy = sqrt(pc**2 + pd**2) # * (-1 if pd < 0 else 1)
12667 prt = degrees(atan2(pc,pd))
12668 if not any([isclose(abs(prt),a) for a in [0,90,180,270]]):
12669 raise RuntimeException('Rotations of Tikz pictures other than '
12670 '0 or +/-90,+/- 180, or +/-270 not supported. '
12671 'found {prt}')
12672 rot90 = int(prt // 90)
12673 if rot90 == 2: rot90 = -2
12674 # Now supported
12675 # if any([isclose(prt,a) for a in [90,270,180,-180]]):
12676 # print(f'WARNING: rotations by {prt} not fully supported')
12677
12678 from math import sqrt
12679 hex_width = psx * scw * 2 # HEX_WIDTH
12680 hex_height = psy * sch * sqrt(3) # HEX_HEIGHT
12681 with VerboseGuard('Picture') as v:
12682 v(f'Transformations: {pa},{pb},{pc},{pd}')
12683 v(f'Scale (x,y): {psx},{psy}')
12684 v(f'Rotation (degrees): {prt} ({rot90})')
12685 v(f'Scale to pixels (x,y): {scw},{sch}')
12686
12687 # When translating the Tikz coordinates, it is important to note
12688 # that the Tikz y-axis point upwards, while the picture y-axis
12689 # point downwards. This means that the upper right corner is at
12690 # (width,0) and the lower left corner is at (0,height).
12691 def tranx(x,off=-pll[0]):
12692 # print(f'x: {x} + {off} -> {x+off} -> {int(scw*(x+off))}')
12693 return int(scw * (x + off)+.5)
12694 def trany(y,off=-pur[1]):
12695 # print(f'y: {y} + {off} -> {y+off} -> {-int(sch*(y+off))}')
12696 return -int(sch * (y + off)+.5)
12697 tran = lambda x,y : (tranx(x), trany(y))
12698
12699 return hex_width, hex_height, scw * psx, sch * psy, rot90, tran
12700
12701 # --------------------------------------------------------------------
12702 def getHexParams(self,
12703 llx,
12704 lly,
12705 urx,
12706 ury,
12707 mx,
12708 my,
12709 hex_width,
12710 hex_height,
12711 rot90,
12712 labels,
12713 coords,
12714 targs,
12715 nargs):
12716 '''rot90 = 0 No rotation
12717 = 1 Rotated -90 (clock-wise)
12718 = -1 Rotated 90 (counter clock-wise)
12719 = -2 Rotated 180
12720 '''
12721 with VerboseGuard('Hex parameters') as v:
12722 from math import sqrt
12723 isodd = lambda x : (x % 2 == 1)
12724 iseven = lambda x : (x % 2 == 0)
12725 isfalse = lambda x : False
12726 shorts = {'isodd': isodd, 'iseven': iseven, 'isfalse': isfalse }
12727
12728 # Funny scaling needed by VASSAL. Seems like they only
12729 # really about the absolute value of 'dy' and then the
12730 # aspect ratio between dx and dy.
12731 pxfac = sqrt(3)/2
12732 hex_pw = hex_height * pxfac
12733 hex_ph = hex_width * pxfac
12734 stagger = False
12735 #
12736 # Get parameters from coordinates. These should always be set
12737 #
12738 rows = coords .get('row', {})
12739 columns = coords .get('column',{})
12740 top_short = columns .get('top short', 'isfalse')
12741 bot_short = columns .get('bottom short','isfalse')
12742 inv_col = columns .get('factor',1)
12743 inv_row = rows .get('factor',1)
12744 voff = -rows .get('offset',0) # 0: from 0 -> -1
12745 hoff = -columns.get('offset',0) # -1: from 1 -> -2
12746 vdesc = inv_row == 1
12747 hdesc = inv_col == -1
12748 #
12749 # Calculate total dimensions, and number of columns and rows
12750 #
12751 w = abs((urx-llx) - 2 * mx)
12752 h = abs((ury-lly) - 2 * my)
12753 if abs(rot90) == 1: h, w = w, h
12754 nc = int(w // (hex_width * 3 / 4))
12755 nr = int(h // (hex_height))
12756 namrot = {0: 'none - 0',
12757 -1: '-90 - CCW',
12758 1: '90 CW',
12759 -2: '180 - half-turn'}
12760
12761 v(f'Width: {w}')
12762 v(f'Height: {h}')
12763 v(f'Margins: x={mx} y={my}')
12764 v(f'Rotation: {rot90} ({namrot[rot90]})')
12765 v(f'Labels: {labels}')
12766 v(f'Columns:')
12767 v(f' size: {nc}')
12768 v(f' start: {hoff}')
12769 v(f' direction: {inv_col}')
12770 v(f' top short: {top_short}')
12771 v(f' bottom short: {bot_short}')
12772 v(f'Rows:')
12773 v(f' size: {nr}')
12774 v(f' start: {voff}')
12775 v(f' direction: {inv_row}')
12776 v(f'Image:')
12777 v(f' BB: ({llx},{lly}) x ({urx},{ury})')
12778 #
12779 # X0 and Y0 are in the local (rotated) frame of the hex grid.
12780 # Thus X is always along hex breadth, and Y along the
12781 # height. Thus the base offset (rotated into the hex frame) differs.
12782 x0 = ury if abs(rot90) == 1 else llx
12783 y0 = llx if abs(rot90) == 1 else ury
12784 # Calculate column,row of corners
12785 llc = hoff
12786 ulc = hoff
12787 lrc = hoff+nc-1
12788 urc = hoff+nc-1
12789 #
12790 # Swap in directions
12791 if hdesc: llc, lrc, ulc, urc = lrc, llc, urc, ulc
12792 #
12793 is_short_top = shorts[columns.get('top short', 'isfalse')]
12794 is_short_bot = shorts[columns.get('bottom short','isfalse')]
12795 if is_short_top is isfalse:
12796 # Assume fully populated columns
12797 is_short_top = isodd if iseven(hoff) else iseven
12798 if is_short_bot is isfalse:
12799 is_short_bot = isodd if isodd(hoff) else iseven
12800
12801 #
12802 # Now we have the hex coordinates of the corners. We can
12803 # now check how things are offset. Before rotation, we
12804 # will have that the first column is offset by hex_pw / 2.
12805 x0 += hex_width / 2
12806 #
12807 # If the first column is _not_ short on top, then off set
12808 # is simply hex_ph / 2. Otherwise, the offset is hex_ph
12809 y0 += hex_ph / 2
12810 voff -= 1
12811 voff -= inv_row
12812 v(f' Initial offset of image {x0},{y0}')
12813
12814 # Treat each kind of rotation separately. Note that -90 and
12815 # 180 uses the `is_short_bot' while 0 and 90 uses
12816 # `is_short_top'. There might be a way to unify these, if
12817 # offsets and so on may warrent it, but it may be complete
12818 # overkill.
12819 is_off = False
12820 col_map = {0 : (ulc, is_short_top, is_short_bot),
12821 -1 : (urc, is_short_top, is_short_bot),
12822 1 : (ulc, is_short_bot, is_short_top),
12823 -2 : (urc, is_short_bot, is_short_top) }
12824 col_chk, is_s1, is_s2 = col_map[rot90]
12825
12826 is_off = is_s1(col_chk)
12827 if is_off:
12828 y0 += hex_ph /2
12829
12830 v(f'Is first column off: {is_off}')
12831
12832 # For full columns, noting more is needed
12833 #
12834 # Below is if some columns are short both top and bottom.
12835 # VASSAL seems to start numbering from a given place, and
12836 # then use that for the rest numbering, and forgets to
12837 # take into account various offsets and the like. hence,
12838 # we need to hack it hard.
12839 if iseven(nc):
12840 v(f'Even number of columns, perhaps hacks')
12841 if rot90 == 0:
12842 # Hacks
12843 #
12844 # If the last column is short in both top and bottom,
12845 # and we have inverse columns, but not inverse rows,
12846 # then add to offset
12847 if inv_col == -1 and inv_row == 1 and \
12848 is_s1(urc) and is_s2(urc):
12849 voff += 1
12850 # If the column we check for short is short both top
12851 # and bottom, and we have inverse rows, but not
12852 # inverse columns, then add offset
12853 if inv_row == -1 and inv_col == 1 and \
12854 is_s2(col_chk) and is_off:
12855 voff += 1
12856
12857 if rot90 == -1:
12858 # If the last column is short in both top and bottom,
12859 # and we have inverse columns, then add to offset
12860 if is_s1(urc) and inv_col == -1 and is_s2(urc):
12861 voff -= inv_row
12862
12863 if rot90 == 1:
12864 voff += inv_row + (inv_row == 1)
12865 # If the first column is short in both top and bottom,
12866 # and we have inverse columns, then add to offset
12867 if is_s1(ulc) and is_s2(ulc) and inv_col == -1:
12868 voff += inv_row
12869
12870 if rot90 == -2:
12871 voff += inv_row * 2
12872 # Hacks If the column we check for short is short both
12873 # top and bottom, and we have either inverse rows and
12874 # inverse columns, or rows and columns are normal,
12875 # then add offset
12876 if inv_col == inv_row and is_s1(col_chk) and is_s2(col_chk):
12877 voff += 1
12878 # If the first column is short in both top and bottom,
12879 # and we have inverse columns and rows, then add to
12880 # offset
12881 if inv_col == inv_row and inv_col == -1 and \
12882 is_s1(ulc) and is_s2(ulc):
12883 voff += 1
12884 else:
12885 v(f'Odd number of columns')
12886 voff -= inv_row
12887 if rot90 == 1:
12888 # If we offset in the column direction, add the
12889 # inverse row direction, and if we have inverse rows,
12890 # substract one, otherwise add 2.
12891 voff += (inv_row * hoff + (-1 if inv_row == -1 else 2))
12892 # If we have a short column, and that column is even,
12893 # then add, otherwise subtract, the inverse row
12894 # direction, if the checked column is even.
12895 voff += ((1 if is_off else -1) *
12896 inv_row if is_short_bot(2) else 0)
12897 if rot90 == 2:
12898 voff += inv_row * (2 + is_off) # OK for odd
12899
12900
12901 if rot90 == 0:
12902 if inv_col == -1 and iseven(nc): # OK
12903 stagger = not stagger
12904 hoff -= (inv_col == -1) # OK
12905
12906 if rot90 == -1: # CCW
12907 if inv_col == 1 and iseven(nc): # OK
12908 stagger = not stagger
12909 vdesc, hdesc = hdesc, vdesc
12910 vdesc = not vdesc
12911 voff += (inv_row == 1)
12912 hoff -= (inv_col == 1) # OK
12913
12914 if rot90 == 1: # CW
12915 if (inv_col == 1 and iseven(nc)) or isodd(nc): # OK
12916 stagger = not stagger
12917 vdesc, hdesc = hdesc, vdesc
12918 hdesc = not hdesc
12919 hoff -= (inv_col == -1) # OK
12920
12921 if rot90 == -2:
12922 if (inv_col == -1 and iseven(nc)) or isodd(nc): # OK
12923 stagger = not stagger
12924 vdesc, hdesc = not vdesc, not hdesc
12925 hoff -= (inv_col == 1) # OK
12926
12927 # Labels
12928 if labels is not None:
12929 labmap = {
12930 'auto': {
12931 'hLeading': 1,'vLeading': 1,'hType': 'N','vType': 'N' },
12932 'auto=numbers' : {
12933 'hLeading': 1,'vLeading': 1,'hType': 'N','vType': 'N' },
12934 'auto=alpha column': {
12935 'hLeading': 0,'vLeading': 0,'hType': 'A','vType': 'N' },
12936 'auto=alpha 2 column': {# Not supported
12937 'hLeading': 1,'vLeading': 1,'hType': 'A','vType': 'N' },
12938 'auto=inv y x plus 1': {
12939 'hLeading': 1,'vLeading': 1,'hType': 'N','vType': 'N' },
12940 'auto=x and y plus 1': {
12941 'hLeading': 1,'vLeading': 1,'hType': 'N','vType': 'N' }
12942 }
12943 for l in labels.split(','):
12944 nargs.update(labmap.get(l,{}))
12945 if 'alpha column' in l or 'alpha 2 column' in l:
12946 hoff -= 1 # VASSAL 0->A, wargame 1->A
12947 if l == 'auto=inv y x plus 1':
12948 hoff += 1
12949 #inv_row = not inv_row
12950 if l == 'auto=x and y plus 1':
12951 hoff -= 1
12952 voff -= 1
12953
12954 # Add margins
12955 x0 += int(mx)
12956 y0 += int(my)
12957
12958 targs['dx'] = hex_pw
12959 targs['dy'] = hex_ph
12960 nargs['vOff'] = voff
12961 nargs['hOff'] = hoff
12962 nargs['vDescend'] = vdesc
12963 nargs['hDescend'] = hdesc
12964 targs['edgesLegal'] = True
12965 targs['sideways'] = abs(rot90) == 1
12966 nargs['stagger'] = stagger
12967 targs['x0'] = int(x0+.5)
12968 targs['y0'] = int(y0+.5)
12969
12970 # --------------------------------------------------------------------
12971 def getRectParams(self,i,llx,ury,width,height,targs,nargs):
12972 targs['dx'] = width
12973 targs['dy'] = height
12974 targs['x0'] = int(llx - width/2)
12975 targs['y0'] = int(ury + height/2)
12976 targs['color'] = rgb(0,255,0)
12977 nargs['color'] = rgb(0,255,0)
12978 nargs['vDescend'] = True
12979 nargs['vOff'] = -3
12980 nargs.update({'sep':',','vLeading':0,'hLeading':0})
12981
12982 # ----------------------------------------------------------------
12983 def addZones(self,
12984 zoned,
12985 name,
12986 info,
12987 width,
12988 height,
12989 labels=None,
12990 coords=None,
12991 picinfo=None):
12992 '''Add zones to the Zoned element.
12993
12994 Parameters
12995 ----------
12996 zoned : Zoned
12997 Parent element
12998 name : str
12999 Name of Zoned
13000 info : dict
13001 Dictionary of zones informatio
13002 width : int
13003 Width of parent
13004 height : int
13005 Height of parent
13006 labels : list
13007 On recursive call, list of labels
13008 coords : list
13009 On recursive call, coordinates
13010 picinfo : dict
13011 On recursive call, picture information
13012 '''
13013 grids = []
13014 picture = None
13015
13016 with VerboseGuard(f'Adding zones to {name}') as v:
13017 for k, val in info.items():
13018 if k == 'labels': labels = val;
13019 if k == 'coords': coords = val
13020 if k == 'zoned': picture = val
13021 if 'zone' not in k or k == 'zoned':
13022 continue
13023
13024 grids = [[k,val]] + grids # Reverse order!
13025 # grids.append([k,v])
13026
13027 if len(grids) < 1:
13028 return
13029
13030 if picinfo is None:
13031 picinfo = self.getPictureInfo(picture,name,width,height)
13032
13033 hex_width, hex_height, scx, scy, rot90, tran = picinfo
13034
13035 for g in grids:
13036 n, i = g
13037 v(f'Adding zone {n}')
13038
13039 if 'scope' in n:
13040 llx,lly = tran(*i['global lower left'])
13041 urx,ury = tran(*i['global upper right'])
13042 path = [[llx,ury],[urx,ury],[urx,lly],[llx,lly]]
13043 nm = n.replace('zone scope ','')
13044 elif 'path' in n:
13045 path = [tran(*p) for p in i['path']]
13046 llx = min([px for px,py in path])
13047 ury = max([py for px,py in path])
13048 nm = n.replace('zone path ','')
13049
13050 # Checkf if we have "point" type elements in this object and
13051 # add them to dict.
13052 points = [ val for k,val in i.items()
13053 if (k.startswith('point') and
13054 isinstance(val,dict) and \
13055 val.get('type','') == 'point')]
13056
13057 pathstr = ';'.join([f'{s[0]},{s[1]}' for s in path])
13058 v(f'Zone path ({llx},{ury}): {pathstr} ({len(points)})')
13059
13060 ispool = 'pool' in n.lower() and len(points) <= 0
13061 zone = zoned.addZone(name = nm,
13062 locationFormat = ("$name$"
13063 if ispool else
13064 "$gridLocation$"),
13065 useParentGrid = False,
13066 path = pathstr)
13067
13068 # Do not add grids to pools
13069 if ispool:
13070 v(f'Board {n} is pool with no points')
13071 continue
13072
13073 targs = {'color':rgb(255,0,0),'visible':self._visible}
13074 nargs = {'color':rgb(255,0,0),'visible':self._visible}
13075 # print(targs,nargs)
13076 if 'turn' in n.lower(): nargs['sep'] = 'T'
13077 if 'oob' in n.lower(): nargs['sep'] = 'O'
13078
13079 if len(points) > 0:
13080 with VerboseGuard('Using region grid') as vv:
13081 grid = zone.addRegionGrid(snapto = True,
13082 visible = self._visible)
13083 for j,p in enumerate(points):
13084 pn = p["name"].strip()
13085 pp = p.get('parent','').strip()
13086 pc = p["coords"]
13087 if j == 0: vv(f'',end='')
13088 vv(f'[{pn}] ',end='',flush=True,noindent=True)
13089
13090 if pn.endswith(' flipped'):
13091 pn = pn[:-len(' flipped')]
13092
13093 x, y = tran(*pc)
13094 r = grid.addRegion(name = pn,
13095 originx = x,
13096 originy = y,
13097 alsoPiece = True,
13098 prefix = pp)
13099 v('')
13100
13101 elif 'hex' in n.lower():
13102 margin = i.get('board frame',{}).get('margin',0)
13103 mx = scx * margin
13104 my = scy * margin
13105 # self.message(f'{margin} -> {scx},{scy} -> {mx},{my}')
13106 w = abs(urx - llx)-2*mx
13107 h = abs(ury - lly)-2*my
13108 self.getHexParams(llx = llx,
13109 lly = lly,
13110 urx = urx,
13111 ury = ury,
13112 mx = mx,
13113 my = my,
13114 hex_width = hex_width,
13115 hex_height = hex_height,
13116 rot90 = rot90,
13117 labels = labels,
13118 coords = coords,
13119 targs = targs,
13120 nargs = nargs)
13121
13122 v(f'Adding hex grid')
13123
13124 grid = zone.addHexGrid(**targs)
13125 grid.addNumbering(**nargs)
13126
13127 else:
13128 width = hex_width / HEX_WIDTH * RECT_WIDTH
13129 height = hex_height / HEX_HEIGHT * RECT_HEIGHT
13130 self.getRectParams(i,llx,ury,width,height,targs,nargs)
13131
13132 v(f'Adding rectangular grid')
13133
13134 grid = zone.addSquareGrid(**targs)
13135 grid.addNumbering(**nargs)
13136
13137
13138 # Once we've dealt with this grid, we should see if we have
13139 # any embedded zones we should deal with.
13140 self.addZones(zoned,name,i,width,height,
13141 labels=labels,
13142 coords=coords,
13143 picinfo=picinfo)
13144
13145
13146 # ----------------------------------------------------------------
13147 def addBoards(self):
13148 '''Add Boards to the module
13149 '''
13150 with VerboseGuard('Adding boards') as v:
13151 hasFlipped = False
13152 for cn,cd in self._categories.get('counter',{}).items():
13153 for sn in cd:
13154 if ' flipped' in sn:
13155 hasFlipped = True
13156 break
13157
13158 v(f'Has flipped? {hasFlipped}')
13159 for bn, b in self._categories.get('board',{}).get('all',{}).items():
13160 self.addBoard(bn, b,hasFlipped=hasFlipped)
13161
13162
13163 # ----------------------------------------------------------------
13164 def getIcon(self,name,otherwise):
13165 with VerboseGuard(f'Get Icon {name}') as v:
13166 icon = self._categories\
13167 .get('icon',{})\
13168 .get('all',{})\
13169 .get(name,{
13170 'filename':otherwise})['filename']
13171 v(f'Using "{icon}"')
13172 return icon
13173
13174 # ----------------------------------------------------------------
13175 def addOOBs(self):
13176 '''Add OOBs to the game'''
13177 oobc = self._categories.get('oob',{}).get('all',{}).items()
13178 if len(oobc) < 1:
13179 return
13180
13181 with VerboseGuard(f'Adding OOBs') as v:
13182 icon = self.getIcon('oob-icon','/images/inventory.gif')
13183 v(f'Using icon "{icon}" for OOB')
13184 charts = \
13185 self._game.addChartWindow(name='OOBs',
13186 hotkey = self._oobKey,
13187 description = 'OOBs',
13188 text = '',
13189 icon = icon,
13190 tooltip = 'Show/hide OOBs')
13191 tabs = charts.addTabs(entryName='OOBs')
13192
13193 for on, o in oobc:
13194 widget = tabs.addMapWidget(entryName=on)
13195 self.addOOB(widget, on, o)
13196
13197
13198 # ----------------------------------------------------------------
13199 def addOOB(self,widget,name,info):
13200 '''Add a OOB elements to the game
13201
13202 Parameters
13203 ----------
13204 widget : Widget
13205 Widget to add to
13206 name : str
13207 Name
13208 info : dict
13209 Information on the OOB image
13210 '''
13211 map = widget.addWidgetMap(mapName = name,
13212 markMoved = 'Never',
13213 hotkey = '')
13214 map.addCounterDetailViewer()
13215 map.addStackMetrics()
13216 map.addImageSaver()
13217 map.addTextSaver()
13218 map.addForwardToChatter()
13219 map.addMenuDisplayer()
13220 map.addMapCenterer()
13221 map.addStackExpander()
13222 map.addPieceMover()
13223 map.addKeyBufferer()
13224 map.addSelectionHighlighters()
13225 map.addHighlightLastMoved()
13226 map.addZoomer()
13227
13228 picker = map.addPicker()
13229 ulx,uly,lrx,lry = self.getBB(info['img'])
13230 board = picker.addBoard(name = name,
13231 image = info['filename'])
13232 zoned = board.addZonedGrid()
13233 zoned.addHighlighter()
13234
13235 if not 'zones' in info:
13236 zone = zoned.addZone(name = 'full',
13237 useParentGrid = False,
13238 path=(f'{ulx},{uly};' +
13239 f'{lrx},{uly};' +
13240 f'{lrx},{lry};' +
13241 f'{ulx},{lry}'))
13242 grid = zone.addSquareGrid()
13243 grid.addNumbering()
13244
13245 return
13246
13247 # If we get here, we have board info!
13248 w = abs(ulx-lrx)
13249 h = abs(uly-lry)
13250 self.addZones(zoned,name,info['zones'],w,h)
13251
13252 # ----------------------------------------------------------------
13253 def addCharts(self):
13254 '''Add Charts elements to game
13255 '''
13256 chartc = self._categories.get('chart',{}).get('all',{}).items()
13257 if len(chartc) < 1:
13258 return
13259
13260 with VerboseGuard('Adding charts') as v:
13261 charts = self._game.addChartWindow(name = 'Charts',
13262 hotkey = self._chartsKey,
13263 description = '',
13264 text = '',
13265 tooltip = 'Show/hide charts',
13266 icon = self.getIcon('chart-icon',
13267 '/images/chart.gif'))
13268 tabs = charts.addTabs(entryName='Charts')
13269 for i, (cn, c) in enumerate(chartc):
13270 if i == 0: v('',end='')
13271 v(f'[{cn}] ',end='',flush=True,noindent=True)
13272
13273 tabs.addChart(chartName = cn,
13274 description = cn,
13275 fileName = c['filename'])
13276
13277 v('')
13278
13279 # ----------------------------------------------------------------
13280 def addDie(self):
13281 '''Add a `Die` element to the module
13282 '''
13283 if self._dice is not None and len(self._dice) > 0:
13284 return
13285 self._game.addDiceButton(name = '1d6',
13286 hotkey = self._diceKey)
13287
13288 # ====================================================================
13289 def patchVmod(vmod_filename,patch_name,verbose):
13290
13291 with VMod(vmod_filename,'r') as vmod:
13292 buildFile = BuildFile(vmod.getBuildFile())
13293 moduleData = ModuleData(vmod.getModuleData())
13294
13295 from importlib.util import spec_from_file_location, module_from_spec
13296 from pathlib import Path
13297 from sys import modules
13298
13299 p = Path(patch_name)
13300
13301 spec = spec_from_file_location(p.stem, p.absolute())
13302 module = module_from_spec(spec)
13303 spec.loader.exec_module(module)
13304
13305 modules[p.stem] = module
13306
13307 with VMod(vmod_filename,'a') as vmod:
13308 module.patch(buildFile,
13309 moduleData,
13310 vmod,
13311 verbose)
13312
13313 vmod.replaceFiles(**{VMod.BUILD_FILE :
13314 buildFile.encode(),
13315 VMod.MODULE_DATA :
13316 moduleData.encode()})
13317
13318
13319 #
13320 # EOF
13321 #
13322 # ====================================================================
13323 # From main.py
13324
13325 from argparse import ArgumentParser
13326
13327 class DefaultSubcommandArgParse(ArgumentParser):
13328 _default_subparser = None
13329
13330 def set_default_subparser(self, name):
13331 self._default_subparser = name
13332
13333 def _parse_known_args(self, arg_strings, *args, **kwargs):
13334 from argparse import _SubParsersAction
13335 in_args = set(arg_strings)
13336 d_sp = self._default_subparser
13337 if d_sp is not None and not {'-h', '--help'}.intersection(in_args):
13338 for x in self._subparsers._actions:
13339 subparser_found = (
13340 isinstance(x, _SubParsersAction) and
13341 in_args.intersection(x._name_parser_map.keys())
13342 )
13343 if subparser_found:
13344 break
13345 else:
13346 # insert default in first position, this implies no
13347 # global options without a sub_parsers specified
13348 arg_strings = [d_sp] + arg_strings
13349 return super(DefaultSubcommandArgParse, self)._parse_known_args(
13350 arg_strings, *args, **kwargs
13351 )
13352 # ====================================================================
13353 def patchIt(args):
13354 vmodname = args.output.name
13355 patchname = args.patch.name
13356 args.output.close()
13357 args.patch .close()
13358
13359 patchVmod(vmodname, patchname, args.verbose)
13360
13361 # ====================================================================
13362 def exportIt(args):
13363
13364 vmodname = args.output.name
13365 patchname = args.patch.name if args.patch is not None else None
13366
13367 args.output.close()
13368 if args.patch is not None:
13369 args.patch.close()
13370
13371 Verbose().setVerbose(args.verbose)
13372
13373 try:
13374 if args.version.lower() == 'draft':
13375 args.visible_grids = True
13376
13377 rulesname = args.rules.name if args.rules is not None else None
13378 tutname = args.tutorial.name if args.tutorial is not None else None
13379
13380 exporter = LaTeXExporter(vmodname = vmodname,
13381 pdfname = args.pdffile.name,
13382 infoname = args.infofile.name,
13383 title = args.title,
13384 version = args.version,
13385 description = args.description,
13386 rules = rulesname,
13387 tutorial = tutname,
13388 patch = patchname,
13389 visible = args.visible_grids,
13390 vassalVersion = args.vassal_version,
13391 nonato = args.no_nato_prototypes,
13392 nochit = args.no_chit_information,
13393 resolution = args.resolution,
13394 counterScale = args.counter_scale,
13395 imageFormat = args.image_format)
13396 exporter.run()
13397 except Exception as e:
13398 from sys import stderr
13399 print(f'Failed to build {vmodname}: {e}',file=stderr)
13400 from os import unlink
13401 try:
13402 unlink(vmodname)
13403 except:
13404 pass
13405
13406 raise e
13407
13408
13409 # ====================================================================
13410 if __name__ == '__main__':
13411 from argparse import ArgumentParser, FileType
13412
13413 ap = DefaultSubcommandArgParse(description='Create draft VASSAL module')
13414 ap.set_default_subparser('export')
13415 sp = ap.add_subparsers(dest='mode')
13416
13417 pp = sp.add_parser('patch',help='Patch VMod')
13418 pp.add_argument('output',
13419 help='Module to patch',
13420 type=FileType('r'),
13421 default='Draft.vmod')
13422 pp.add_argument('patch',
13423 help='A python script to patch generated module',
13424 type=FileType('r'),
13425 default='patch.py')
13426 pp.add_argument('-V','--verbose',
13427 help='Be verbose',
13428 action='store_true')
13429
13430
13431 ep = sp.add_parser('export',help='Export from PDF and JSON to VMod')
13432 ep.add_argument('pdffile',
13433 help='The PDF file to read images from',
13434 type=FileType('r'),
13435 default='export.pdf',
13436 nargs='?')
13437 ep.add_argument('infofile',
13438 help='The JSON file to read image information from',
13439 type=FileType('r'),
13440 default='export.json',
13441 nargs='?')
13442 ep.add_argument('-o','--output',
13443 help='Output file to write module to',
13444 type=FileType('w'),
13445 default='Draft.vmod')
13446 ep.add_argument('-p','--patch',
13447 help='A python script to patch generated module',
13448 type=FileType('r'))
13449 ep.add_argument('-V','--verbose',
13450 help='Be verbose',
13451 action='store_true')
13452 ep.add_argument('-t','--title',
13453 help='Module title', default='Draft',
13454 type=str)
13455 ep.add_argument('-v','--version',
13456 help='Module version',
13457 type=str,
13458 default='draft')
13459 ep.add_argument('-r','--rules',
13460 help='Rules PDF file',
13461 type=FileType('r'))
13462 ep.add_argument('-T','--tutorial',
13463 help='Tutorial (v)log file',
13464 type=FileType('r'))
13465 ep.add_argument('-d','--description',
13466 help='Short description of module',
13467 type=str,
13468 default='draft of module')
13469 ep.add_argument('-W','--vassal-version',
13470 help='Vassal version number',
13471 type=str,
13472 default='3.6.7')
13473 ep.add_argument('-G','--visible-grids',
13474 action='store_true',
13475 help='Make grids visible in the module')
13476 ep.add_argument('-N','--no-nato-prototypes',
13477 action='store_true',
13478 help='Do not make prototypes for types,echelons,commands')
13479 ep.add_argument('-C','--no-chit-information',
13480 action='store_true',
13481 help='Do not make properties from chit information')
13482 ep.add_argument('-S','--counter-scale',
13483 type=float, default=1,
13484 help='Scale counters by factor')
13485 ep.add_argument('-R','--resolution',
13486 type=int, default=150,
13487 help='Resolution of images')
13488 ep.add_argument('-I','--image-format',
13489 choices = ['png','svg'], default='png',
13490 help='Image format to use')
13491
13492 args = ap.parse_args()
13493
13494 if args.mode == 'patch':
13495 patchIt(args)
13496 else:
13497 exportIt(args)
13498
13499 #
13500 # EOF
13501 #
13502 ##
13503 # End of generated script
13504 ##