forked from inclement/noGo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
boardview.py
2040 lines (1804 loc) · 78.8 KB
/
boardview.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2013 Alexander Taylor
# This file is part of noGo.
# noGo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
# noGo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with noGo. If not, see http://www.gnu.org/licenses/gpl-3.0.txt
from kivy.app import App
from kivy.core.window import Window
from kivy.graphics import Color, Rectangle, Ellipse
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.carousel import Carousel
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.stencilview import StencilView
from kivy.uix.dropdown import DropDown
from kivy.uix.scatter import Scatter
from kivy.uix.spinner import Spinner, SpinnerOption
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.popup import Popup
from kivy.uix.slider import Slider
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.screenmanager import *
from kivy.adapters.listadapter import ListAdapter
from kivy.uix.listview import ListView, ListItemButton
from kivy.utils import platform
from kivy.animation import Animation
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty, ListProperty, AliasProperty, StringProperty, DictProperty, BooleanProperty, StringProperty, OptionProperty, BoundedNumericProperty
from kivy.vector import Vector
from kivy.clock import Clock
Clock.max_iteration = 60
from kivy.input.postproc import doubletap
from sgfmodels import Sgf, CollectionSgf, Collection
#from db import KombiloInterface
from helpers import embolden
import sgfmodels
from random import random as r
from random import choice
from math import sin
from functools import partial
from glob import glob
from os.path import abspath
from os import mkdir
from json import dump as jsondump, load as jsonload, dump as jsondump
import json
from time import asctime, time, strftime
from shutil import copyfile
from gomill import sgf, boards
from abstractboard import *
from sgfcollections import CollectionChooserButton
from widgetcache import WidgetCache
from boardwidgets import Stone, TextMarker, TriangleMarker, SquareMarker, CircleMarker, CrossMarker, VarStone, WhiteStoneSimple, BlackStoneSimple
import sys
navigate_text = '[b]Navigation mode[/b] selected. Tap on the right side of the board to advance the game, or the left to move back.'
edit_text = '[b]Edit mode[/b] selected. Use the edit tools below the board to add/remove SGF markers and stones.'
score_text = '[b]Score mode[/b] selected. Tap on groups to toggle them as dead/alive.'
play_text = '[b]Play mode[/b] selected. Press, move and release on the board to play stones. Pressing back and replaying a move will give the option of whether to replace the next move or to create a new variation. Edit tools can be accessed with the arrows by the comment box, or via the separate Edit mode..'
guess_text = '[b]Guess mode[/b] selected. Try to play stones that match the existing game. A marker indicates how good the guess was, and if correct the game advances.'
zoom_text = '[b]Zoom mode[/b] selected. Experimental.'
blacknames = ['black','b','B','Black']
whitenames = ['white','w','W','White']
handicap_positions = {19: {2: [(3,3),(15,15)],
3: [(3,3),(15,15),(3,15)],
4: [(3,3),(3,15),(15,15),(15,3)],
5: [(3,3),(3,15),(15,15),(15,3),(9,9)],
6: [(3,3),(3,15),(15,15),(15,3),(9,3),(9,15)],
7: [(3,3),(3,15),(15,15),(15,3),(9,3),(9,15),(9,9)],
8: [(3,3),(3,15),(15,15),(15,3),(9,3),(9,15),(3,9),(15,9)],
9: [(3,3),(3,15),(15,15),(15,3),(9,3),(9,15),(3,9),(15,9),(9,9)]
},
13: {2: [(3,3),(9,9)],
3: [(3,3),(9,9),(3,9)],
4: [(3,3),(3,9),(9,9),(9,3)],
5: [(3,3),(3,9),(9,9),(9,3),(6,6)],
6: [(3,3),(3,9),(9,9),(9,3),(9,3),(9,9)],
7: [(3,3),(3,9),(9,9),(9,3),(9,3),(9,9),(6,6)],
8: [(3,3),(3,9),(9,9),(9,3),(9,3),(9,9),(3,9),(9,9)],
9: [(3,3),(3,9),(9,9),(9,3),(9,3),(9,9),(3,9),(9,9),(6,6)]
},
9: {2: [(2,2),(6,6)],
3: [(2,2),(6,6),(2,6)],
4: [(2,2),(2,6),(6,6),(6,2)],
5: [(2,2),(2,6),(6,6),(6,2),(4,4)],
6: [(2,2),(2,6),(6,6),(6,2),(2,4),(6,4)],
7: [(2,2),(2,6),(6,6),(6,2),(2,4),(6,4),(4,4)],
8: [(2,2),(2,6),(6,6),(6,2),(2,4),(6,4),(4,2),(4,6)],
9: [(2,2),(2,6),(6,6),(6,2),(2,4),(6,4),(4,2),(4,6),(4,4)],
}
}
def format_score(score):
if score == 0:
return '[color=#ff0000]j[/color][color=#00ff00]i[/color][color=#ff0000]g[/color][color=#00ff00]o[/color]'
elif score > 0:
return 'B+%.1f' % score
else:
return 'W+%.1f' % abs(score)
def alternate_colour(colour):
if colour == 'b':
return 'w'
elif colour == 'w':
return 'b'
else:
return 'b'
def colourname_to_colour(colourname):
if colourname in blacknames:
return 'black'
elif colourname in whitenames:
return 'white'
else:
return None
def get_move_marker_colour(col):
if col == 'w':
return [1,1,1,0.5]
elif col == 'b':
return [0,0,0,0.5]
else:
return [0.5,0.5,0.5,0.5]
class AreaMarker(Widget):
start_coord = ListProperty([0,0])
end_coord = ListProperty([0,0])
bottom_left = ListProperty([0,0])
top_right = ListProperty([0,0])
dx = NumericProperty(0)
dy = NumericProperty(0)
board = ObjectProperty()
corners = ListProperty([0,0,0,0,0,0,0,0])
def on_board(self, *args):
board = self.board
board.bind(size=self.set_corners)
board.bind(pos=self.set_corners)
def set_corners(self, *args):
to_pos = self.board.coord_to_pos
start = self.start_coord
end = self.end_coord
dx = end[0] - start[0]
dy = end[1] - start[1]
self.dx = dx
self.dy = dy
if dx >= 0 and dy >= 0:
bottom_left = to_pos(start)
top_right = to_pos((end[0]+1, end[1]+1))
bottom_left_coord = start
top_right_coord = end
elif dx >= 0 and dy < 0:
bottom_left = to_pos((start[0], end[1]))
top_right = to_pos((end[0]+1, start[1]+1))
bottom_left_coord = (start[0], end[1])
top_right_coord = (end[0], start[1])
elif dx < 0 and dy >= 0:
bottom_left = to_pos((end[0], start[1]))
top_right = to_pos((start[0]+1, end[1]+1))
bottom_left_coord = (end[0], start[1])
top_right_coord = (start[0], end[1])
elif dx < 0 and dy < 0:
bottom_left = to_pos((end[0], end[1]))
top_right = to_pos((start[0]+1, start[1]+1))
bottom_left_coord = end
top_right_coord = start
self.bottom_left = bottom_left_coord
self.top_right = top_right_coord
corners = [bottom_left[0], bottom_left[1],
bottom_left[0], top_right[1],
top_right[0], top_right[1],
top_right[0], bottom_left[1]]
self.corners = corners
def on_start_coord(self, *args):
self.set_corners()
def on_end_coord(self, *args):
self.set_corners()
class ReversibleSpinner(BoxLayout):
spinner = ObjectProperty()
button = ObjectProperty()
text = StringProperty('')
values = ListProperty([])
option_cls = ObjectProperty()
cur_text = StringProperty('')
prev_text = StringProperty('')
def __init__(self, *args, **kwargs):
super(ReversibleSpinner, self).__init__(*args, **kwargs)
self.cur_text = self.text
if self.prev_text == '':
self.prev_text = self.text
def on_text(self, *args):
self.spinner.text = self.text
self.prev_text = self.cur_text
self.cur_text = self.text
if self.prev_text == '':
self.prev_text = self.cur_text
def revert_spinner(self):
self.text = self.prev_text
class VarPopup(Popup):
pass
class BoardCarousel(Carousel):
board = ObjectProperty()
board_navmode = StringProperty('')
def on_board_navmode(self,*args):
navmode = self.board_navmode
if navmode == 'Edit':
self.index = 2
elif navmode in ['Navigate','Play']:
self.index = 0
class GameTree(ScrollView):
board = ObjectProperty(None, allownone=True)
abstractboard = ObjectProperty(None, allownone=True)
nodes = DictProperty({})
positions = DictProperty({})
widgets = DictProperty({})
def build(self):
sgf = abstractboard.game
rootnode = sgf.get_root()
mainseq = sgf.get_main_sequence()
nodes = {}
positions = {}
widgets = {}
class GameTreeLayout(FloatLayout):
pass
class GameTreeWhite(AnchorLayout):
pass
class GameTreeBlack(AnchorLayout):
pass
class GameTreeEmpty(AnchorLayout):
pass
class LDMarker(Widget):
pass
class VarBranchButton(Button):
pass
class GameInfo(BoxLayout):
popup = ObjectProperty(None,allownone=True)
board = ObjectProperty(None,allownone=True)
bname = StringProperty('')
wname = StringProperty('')
brank = StringProperty('')
wrank = StringProperty('')
komi = StringProperty('')
result = StringProperty('')
event = StringProperty('')
gname = StringProperty('')
ruleset = StringProperty('')
source = StringProperty('')
entries_layout = ObjectProperty(None)
def release_keyboard(self):
print 'RELEASING KEYBOARDS'
print 'child widgets are',self.entries_layout.children
for widget in self.entries_layout.children:
widget.focus = False
def populate_from_gameinfo(self,gi):
if 'bname' in gi:
self.bname = gi['bname']
if 'wname' in gi:
self.wname = gi['wname']
if 'brank' in gi:
self.brank = gi['brank']
if 'wrank' in gi:
self.wrank = gi['wrank']
if 'komi' in gi:
self.komi = str(gi['komi'])
if 'result' in gi:
self.result = gi['result']
if 'event' in gi:
self.event = gi['event']
if 'gname' in gi:
self.gname = gi['gname']
if 'rules' in gi:
self.ruleset = gi['rules']
if 'source' in gi:
self.source = gi['source']
class GuessPopup(Widget):
alpha = NumericProperty(1)
colour = ListProperty([1,0,0])
pass
class TabletPlayerDetails(BoxLayout):
wstone = ObjectProperty(None)
bstone = ObjectProperty(None)
board = ObjectProperty(None)
wtext = StringProperty('W player')
wrank = StringProperty('')
btext = StringProperty('B player')
brank = StringProperty('')
next_to_play = StringProperty('')
wtoplaycolour = ListProperty([0,1,0,1])
btoplaycolour = ListProperty([0,1,0,1])
def set_to_play(self,player):
#print 'set_to_play called!',player
if player == 'w':
self.wtoplaycolour = [0,0.8,0,1]
self.btoplaycolour = [0,0.8,0,0]
elif player == 'b':
self.btoplaycolour = [0,0.8,0,1]
self.wtoplaycolour = [0,0.8,0,0]
else:
self.wtoplaycolour = [0,0.8,0,0]
self.btoplaycolour = [0,0.8,0,0]
def on_touch_down(self,touch):
if self.wstone.collide_point(*touch.pos):
self.board.next_to_play = 'w'
elif self.bstone.collide_point(*touch.pos):
self.board.next_to_play = 'b'
class PlayerDetails(BoxLayout):
wstone = ObjectProperty(None)
bstone = ObjectProperty(None)
board = ObjectProperty(None)
wtext = StringProperty('W player')
wrank = StringProperty('')
btext = StringProperty('B player')
brank = StringProperty('')
next_to_play = StringProperty('')
wtoplaycolour = ListProperty([0,1,0,1])
btoplaycolour = ListProperty([0,1,0,1])
def set_to_play(self,player):
#print 'set_to_play called!',player
if player == 'w':
self.wtoplaycolour = [0,0.8,0,1]
self.btoplaycolour = [0,0.8,0,0]
elif player == 'b':
self.btoplaycolour = [0,0.8,0,1]
self.wtoplaycolour = [0,0.8,0,0]
else:
self.wtoplaycolour = [0,0.8,0,0]
self.btoplaycolour = [0,0.8,0,0]
def on_touch_down(self,touch):
if self.wstone.collide_point(*touch.pos):
self.board.next_to_play = 'w'
elif self.bstone.collide_point(*touch.pos):
self.board.next_to_play = 'b'
class GameSlider(Slider):
def on_value(self, *args):
#print 'gameslider value changed to',self.value
pass
class CommentBox(ScrollView):
pre_text = StringProperty('')
text = StringProperty('')
board = ObjectProperty(None,allownone=True)
padding = ListProperty([0,0])
def on_size(self,*args):
print 'comment box size changed',self.size
def on_pos(self,*args):
print 'comment box pos changed',self.pos
def on_touch_down(self,touch):
super(CommentBox,self).on_touch_down(touch)
if self.collide_point(*touch.pos):
if self.board is not None:
callback = self.board.get_new_comment
Clock.schedule_once(callback,1.1)
touch.ud['event'] = callback
board = self.board
if board.autoplaying:
if touch.x > self.x + 0.5*self.width:
board.inc_autoplay()
else:
board.dec_autoplay()
elif board.navmode == 'Navigate' and self.text == '[color=444444]Long press to add comment.[/color]':
print 'selftext'
print self.pre_text
print self.text
if touch.x > self.x + 0.5*self.width:
board.advance_one_move()
else:
board.retreat_one_move()
def on_touch_move(self,touch):
super(CommentBox,self).on_touch_move(touch)
if (touch.x - touch.ox)**2 + (touch.y - touch.oy)**2 > 25:
try:
Clock.unschedule(touch.ud['event'])
except KeyError:
pass
def on_touch_up(self,touch):
super(CommentBox,self).on_touch_up(touch)
try:
Clock.unschedule(touch.ud['event'])
except KeyError:
pass
class TabletBoardView(BoxLayout):
managedby = ObjectProperty(None,allownone=True)
screenname = StringProperty('')
boardcontainer = ObjectProperty(None,allownone=True)
board = ObjectProperty(None,allownone=True)
spinner = ObjectProperty(None,allownone=True)
sgf_model = ObjectProperty(None,allownone=True)
def rottest(self,num):
Window.rotation = num
class PhoneBoardView(BoxLayout):
managedby = ObjectProperty(None,allownone=True)
screenname = StringProperty('')
boardcontainer = ObjectProperty(None,allownone=True)
board = ObjectProperty(None,allownone=True)
spinner = ObjectProperty(None,allownone=True)
sgf_model = ObjectProperty(None,allownone=True)
def rottest(self,num):
Window.rotation = num
# def on_touch_move(self, touch):
# super(PhoneBoardView, self).on_touch_down(touch)
# with self.canvas:
# Ellipse(pos=(touch.pos[0]-5,touch.pos[1]-5),size=(10,10))
class StarPoint(Widget):
pass
class PlayMarker(Widget):
markercolour = ListProperty([0,0,0])
coord = ListProperty([])
pass
starposs = {19:[(3,3),(3,9),(3,15),(9,3),(9,9),(9,15),(15,3),(15,9),(15,15)],
13:[(3,3),(3,9),(9,3),(9,9),(6,6)],
9:[(2,2),(6,2),(2,6),(6,6),(4,4)]}
class EditMarker(Widget):
coord = ListProperty((0,0))
board = ObjectProperty(None)
colour = ListProperty((1,1,1,0.5))
def set_position_from_coord(self,coord):
if self.board is not None:
if not (0<=coord[0]<self.board.gridsize and 0<=coord[1]<self.board.gridsize):
self.colour[3] = 0.0
else:
self.colour[3] = 0.75
newpos = self.board.coord_to_pos(self.coord)
return newpos
else:
return (0,0)
class MakeMoveMarker(EditMarker):
def set_position_from_coord(self,coord):
if self.board is not None:
if not (0<=coord[0]<self.board.gridsize and 0<=coord[1]<self.board.gridsize):
self.colour[3] = 0.0
else:
self.colour[3] = 0.75
newpos = self.board.coord_to_pos(self.coord)
return newpos
else:
return (0,0)
class MakeTriangleMarker(EditMarker):
pass
class MakeSquareMarker(EditMarker):
pass
class MakeCircleMarker(EditMarker):
pass
class MakeCrossMarker(EditMarker):
pass
class MakeEmptyMarker(EditMarker):
pass
class PickNewVarType(FloatLayout):
board = ObjectProperty(None)
popup = ObjectProperty(None)
coord = ListProperty((0,0))
class GuiBoard(Widget):
gridsize = NumericProperty(19) # Board size
navmode = StringProperty('Navigate') # How to scale the board
abstractboard = ObjectProperty(None,allownone=True) # Object to query for where to play moves
uielements = DictProperty({})
makemovemarker = ObjectProperty(None,allownone=True)
touchoffset = ListProperty([0,0])
guesses = ListProperty([0,0])
gameinfo = DictProperty({})
sgf_model = ObjectProperty(None,allownone=True)
#kinterface = ObjectProperty(None)
#areamarker = ObjectProperty(None, allownone=True)
input_mode = OptionProperty('play',options=['play',
'mark_tri',
'mark_squ',
'mark_cir',
'mark_cro',
'bstone',
'wstone',
'estone',
'mark_area'])
autoplaying = BooleanProperty(False)
autoplay_dts = [0.2, 0.3, 0.4, 0.5, 0.75, 1.0, 2, 4, 6, 10]
autoplay_index = BoundedNumericProperty(2,min=0,max=9)
board_path = StringProperty('./media/boards/none.png')
# def on_board_path(self,*args,**kwargs):
# print 'board path changed',args,kwargs
# import os
# print 'exists?', os.path.exists(self.board_path)
cache = ObjectProperty(WidgetCache())
# Game tree index
current_node_index = NumericProperty(0)
current_branch_length = NumericProperty(0)
# Save state
user_saved = BooleanProperty(False)
temporary_filepath = StringProperty('')
permanent_filepath = StringProperty('')
has_unsaved_data = BooleanProperty(False)
# Score mode
ld_markers = DictProperty({})
scoreboard = ObjectProperty(None,allownone=True)
variations_exist = BooleanProperty(False)
showcoords = BooleanProperty(False)
wname = StringProperty('')
wrank = StringProperty('')
bname = StringProperty('')
brank = StringProperty('')
next_to_play = StringProperty('e')
permanent_text = StringProperty('')
comment_pre_text = StringProperty('')
comment_text = StringProperty('')
# def on_comment_pre_text(self,*args):
# print 'on_comment_pre_text',args
# def on_comment_text(self,*args):
# print 'on_comment_text',args
# Board flipping
flip_horiz = BooleanProperty(False)
flip_vert = BooleanProperty(False)
flip_forwardslash = BooleanProperty(True)
flip_backslash = BooleanProperty(False)
# Transient widgets
playmarker = ObjectProperty(None,allownone=True) # Circle marking last played move
boardmarkers = DictProperty({})
guesspopup = ObjectProperty(None,allownone=True)
varstones = DictProperty({})
# Coordinates widget
coordinate_letter = 'abcdefghjklmnopqrstuv'
coordinate_number = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19']
coordinates = BooleanProperty(False)
coordinate_labels = ListProperty([])
def on_coordinates(self,obj,val):
print 'on_coordinates',obj,val
if val:
print 'adding coordinates'
self.add_coordinates()
else:
print 'removing coordinates'
self.remove_coordinates()
display_markers = BooleanProperty(True)
def on_display_markers(self,obj,val):
if val:
print 'adding markers'
self.retreat_one_move()
self.advance_one_move()
else:
self.clear_markers()
def get_reconstruction(self):
return self.abstractboard.get_reconstruction()
def reconstruct_from(self, reconstruction):
instructions = self.abstractboard.reconstruct_from(reconstruction)
self.follow_instructions(instructions)
# def add_widget(self,*args,**kwargs):
# print 'board add_widget called with...',args
# super(GuiBoard,self).add_widget(*args)
stones = DictProperty({})
starpoints = DictProperty()
starpoint_positions = DictProperty(starposs)
gobansize = ListProperty((100,100))
numcells = NumericProperty(10)
boardindent = ListProperty((100,100))
stonesize = ListProperty((100,100))
gridspacing = NumericProperty(10)
gridlines = ListProperty([])
gobanpos = ListProperty((100,100))
def __init__(self,*args,**kwargs):
super(GuiBoard,self).__init__(*args,**kwargs)
print 'GuiBoard init, making abstractboard with gridsize', self.gridsize
self.abstractboard = AbstractBoard(gridsize=self.gridsize)
self.reset_abstractboard()
def add_handicap_stones(self,num):
#print 'asked to add handicap stones',num
if handicap_positions.has_key(self.gridsize):
stone_positions = handicap_positions[self.gridsize]
if stone_positions.has_key(num):
stone_coords = stone_positions[num]
print 'handicap positions are',stone_coords
for coord in stone_coords:
self.toggle_background_stone(coord,'b')
if num > 0:
self.next_to_play = 'w'
else:
self.next_to_play = 'b'
def start_autoplay(self,*args,**kwargs ):
print 'starting_autoplay'
self.advance_one_move()
if 'message' in kwargs:
message = kwargs['message']
else:
message = True
interval = self.autoplay_dts[self.autoplay_index]
Clock.schedule_interval(self.advance_one_move, interval)
if message:
self.permanent_text = '[b]Autoplay[/b] activated. Tap either side of this box to speed up or slow down autoplay, or any navigation button to stop. Current speed = [b]{}[/b] seconds between stones\n'.format(interval)
else:
self.permanent_text = '[color=dddddd]Autoplaying with [b]{}[/b] seconds between stones[/color]\n'.format(interval)
print 'started autoplay, permanent text is'
print self.permanent_text
self.autoplaying = True
def toggle_autoplay(self,*args,**kwargs):
if self.autoplaying:
self.stop_autoplay()
else:
self.start_autoplay()
def inc_autoplay(self,*args):
if self.autoplay_index < 9:
self.autoplay_index += 1
def dec_autoplay(self,*args):
if self.autoplay_index > 0:
self.autoplay_index -= 1
def on_autoplay_index(self,*args,**kwargs):
print 'on_autoplay_index',self.autoplay_index
self.stop_autoplay()
self.start_autoplay(message=False)
def stop_autoplay(self,*args,**kwargs):
print 'stopping autoplay'
self.permanent_text = ''
try:
Clock.unschedule(self.advance_one_move)
self.autoplaying = False
except:
pass
def set_game_date(self):
isodate = strftime("%Y-%m-%d")
gi = self.gameinfo
gi['date'] = isodate
self.set_game_info(gi)
def set_game_info(self,info):
#print 'asked to set with info',info
self.abstractboard.set_gameinfo(info)
self.get_game_info()
#App.get_running_app().manager.refresh_open_games()
def get_game_info(self):
gi = self.abstractboard.get_gameinfo()
self.gameinfo = gi
self.get_player_details()
try:
self.collectionsgf.set_gameinfo(gi)
self.collectionsgf.save()
except AttributeError:
print 'Tried to set collectionsgf info when it doesn\'t exist yet.'
try:
print 'Trying to remind'
print App.get_running_app().manager
print App.get_running_app().manager.collections_to_refresh
App.get_running_app().manager.add_collection_refresh_reminder(self.collectionsgf.collection)
print 'Added collection refresh reminder'
App.get_running_app().manager.homescreen_to_refresh = True
print 'Set homescreen refresh reminder'
except AttributeError:
print 'Tried to refresh collectionsgf before it was created?'
# try:
# App.get_running_app().manager.refresh_collection(self.collectionsgf.collection)
# App.get_running_app().manager.refresh_open_games()
# except AttributeError:
# print 'Tried to refresh collectionsgf before it was created'
def email_sgf(self):
if platform() == 'android':
import android
self.save_sgf()
filen = self.collectionsgf.filen
copyfile(filen,'/sdcard/noGo/email_sgf.sgf')
filen = '/sdcard/noGo/email_sgf.sgf'
android.action_send('application/x-go-sgf', filename=filen)
else:
print 'Asked to email sgf'
print '...request ignored. Only supported on android'
def view_game_info(self):
gi = GameInfo(board=self)
gi.populate_from_gameinfo(self.gameinfo)
popup = Popup(content=gi,title='Game info.',size_hint=(0.95,0.5),pos_hint={'top':1})
popup.content.popup = popup
popup.open()
def save_sgf_in(self, selection):
sgf = self.sgf_model
if len(selection) == 0:
return False
else:
collection = selection[0].collection
collectionsgfs = list(CollectionSgf.select().where(CollectionSgf.sgf == sgf) )
if len(collectionsgfs) == 0:
collectionsgf = CollectionSgf(collection=collection,
sgf = sgf)
collectionsgf.save()
else:
collectionsgf = collectionsgfs[0]
collectionsgf.collection = collection
collectionsgf.save()
self.sgf_model.auto_filename()
self.save_sgf()
App.get_running_app().manager.refresh_collections_index()
def save_sgf(self,mode='quiet'):
#saveas=False,autosave=False,refresh=True):
filen = self.sgf_model.filename
if filen == '':
filen = self.sgf_model.auto_filename()
print 'filen from collectionsgf is',filen
if mode == 'quiet':
self.abstractboard.save_sgf(filen)
elif mode == 'saveas':
self.ask_where_to_save()
self.sgf_model.populate_from_gameinfo(self.gameinfo)
self.sgf_model.save()
#App.get_running_app().collections.save()
def ask_where_to_save(self,force=True):
sq = SaveQuery(board=self,sgf_model=self.sgf_model)
popup = Popup(content=sq,title='Where to save?',size_hint=(0.85,0.85))
popup.content.popup = popup
collections_list = sgfmodels.get_collections()
collections_args_converter = sgfmodels.collections_args_converter
list_adapter = ListAdapter(data=collections_list,
args_converter = collections_args_converter,
selection_mode = 'single',
allow_empty_selection=True,
cls=CollectionChooserButton,
)
sq.collections_list.adapter = list_adapter
popup.open()
def build_savefile_name(self,dirn):
filen = ''.join((dirn,'/',asctime().replace(' ','_')))
if 'wname' in self.gameinfo:
filen += '_' + self.gameinfo['wname']
else:
filen += '_' + 'wunknown'
if 'bname' in self.gameinfo:
filen += '_' + self.gameinfo['bname']
else:
filen += '_' + 'bunknown'
if 'event' in self.gameinfo:
filen += '_' + self.gameinfo['event']
else:
filen += '_' + 'eunknown'
filen += '.sgf'
return filen
def back_to_varbranch(self):
instructions = self.abstractboard.jump_to_varbranch()
self.follow_instructions(instructions)
def jump_to_node_by_number(self,number):
#print 'asked to jump to node',number,'from',self.current_node_index
if int(number) != self.current_node_index:
instructions = self.abstractboard.jump_to_leaf_number(number)
self.follow_instructions(instructions)
else:
pass
#print '...but already at that node!'
def take_stone_input(self,coords):
coords = tuple(coords)
if self.navmode in ['Play','Edit']:
#print 'TAKING STONE INPUT',coords,self.navmode
if self.input_mode == 'play':
if tuple(coords) not in self.stones:
existingvars = map(lambda j: j.get_move(),self.abstractboard.curnode)
alreadyexists = False
for entry in existingvars:
if entry[0] == self.next_to_play and entry[1][0] == coords[0] and entry[1][1] == coords[1]:
instructions = self.abstractboard.jump_to_node(self.abstractboard.curnode[existingvars.index(entry)])
print 'entry already exists!'
self.follow_instructions(instructions)
return True
children_exist = self.abstractboard.do_children_exist()
if not children_exist:
self.add_new_stone(coords)
else:
popup = VarPopup(content=PickNewVarType(board=self,coord=coords),title='Do you want to...')
popup.content.popup = popup
popup.open()
elif self.input_mode == 'mark_tri':
self.toggle_marker('triangle',coords)
elif self.input_mode == 'mark_squ':
self.toggle_marker('square',coords)
elif self.input_mode == 'mark_cir':
self.toggle_marker('circle',coords)
elif self.input_mode == 'mark_cro':
self.toggle_marker('cross',coords)
elif self.input_mode == 'bstone':
self.toggle_background_stone(coords,'b')
elif self.input_mode == 'wstone':
self.toggle_background_stone(coords,'w')
elif self.input_mode == 'estone':
self.toggle_background_stone(coords,'e')
elif self.navmode == 'Guess':
if tuple(coords) not in self.stones:
self.guesses[1] += 1
nextcoords = self.abstractboard.get_next_coords()
if nextcoords[0] is not None and nextcoords[1] is not None:
correct = False
if coords[0] == nextcoords[0] and coords[1] == nextcoords[1]:
self.guesses[0] += 1
correct = True
instructions = self.abstractboard.advance_position()
self.follow_instructions(instructions)
pre_text = '%.1f%% correct' % (100*float(self.guesses[0])/self.guesses[1])
if not correct:
off_by_x = abs(coords[0]-nextcoords[0])
off_by_y = abs(coords[1]-nextcoords[1])
self.set_guess_popup(coords,max(off_by_x,off_by_y))
pre_text = '[color=ff0000]Wrong[/color] - ' + pre_text
else:
pre_text = '[color=00ff00]Correct![/color] - ' + pre_text
pre_text += '\n-----\n'
self.comment_pre_text = pre_text
def set_guess_popup(self,centre, size):
if self.guesspopup is not None:
self.remove_widget(self.guesspopup)
self.guesspopup = None
centrecoords = self.coord_to_pos(centre)
cx,cy = centrecoords
lr = (cx - (size+0.25)*self.stonesize[0], cy - (size+0.25)*self.stonesize[1])
tr = (cx + (size+1.25)*self.stonesize[0], cy + (size+1.25)*self.stonesize[1])
markerpos = lr
markersize = (tr[0]-lr[0],tr[1]-lr[1])
markercolour = [0. + size/(0.5*self.gridsize), 1. - size/(0.5*self.gridsize), 0.]
gp = GuessPopup(pos=markerpos, size=markersize, colour=markercolour,alpha=0.1)
self.guesspopup = gp
ani = Animation(alpha=1.0,t='in_out_quad',duration=0.2) + Animation(alpha=(0.15),t='in_out_quad', duration=0.5)
#ani.bind(on_complete=self.remove_guess_popup)
ani.start(gp)
self.add_widget(gp)
def remove_guess_popup(self,*args,**kwargs):
if self.guesspopup is not None:
self.remove_widget(self.guesspopup)
self.guesspopup = None
# def toggle_background_stone(self,coords,colour='b',force='toggle'):
# instructions = self.abstractboard.toggle_background_stone(coords,colour,force)
# print 'toggle background got instructions',instructions
# self.follow_instructions(instructions)
def toggle_marker(self, mtype, coords):
self.abstractboard.clear_markers_at(coords)
if self.boardmarkers.has_key(coords):
self.remove_marker(coords)
else:
self.abstractboard.add_marker_at(mtype,coords)
self.add_marker(coords, mtype)
def add_new_stone(self,coords,newtype='newvar'):
#print 'Called add_new_stone', coords, newtype
colour = self.next_to_play
if newtype == 'newvar':
instructions = self.abstractboard.add_new_node(coords,self.next_to_play)
self.follow_instructions(instructions)
App.get_running_app().play_stone_sound()
if newtype == 'newmain':
instructions = self.abstractboard.add_new_node(coords,self.next_to_play,newmainline=True)
self.follow_instructions(instructions)
App.get_running_app().play_stone_sound()
if newtype == 'replacenext':
instructions = self.abstractboard.replace_next_node(coords,self.next_to_play)
self.follow_instructions(instructions)
App.get_running_app().play_stone_sound()
if newtype == 'insert':
instructions = self.abstractboard.insert_before_next_node(coords,self.next_to_play)
self.follow_instructions(instructions)
App.get_running_app().play_stone_sound()
#print 'add_new_stone received instructions:',instructions
def open_sgf_dialog(self,*args,**kwargs):
popup = Popup(content=OpenSgfDialog(board=self),title='Open SGF',size_hint=(0.85,0.85))
popup.content.popup = popup
popup.open()
def load_sgf_from_file(self,path,filen):
#print 'asked to load from',path,filen
self.abstractboard.load_sgf_from_file(filen[0])
#print 'loaded abstractboard from file'
self.permanent_filepath = self.abstractboard.filepath
#print 'set permanent filepath'
self.reset_abstractboard()
#print 'reset abstractboard'
def get_new_comment(self,*args,**kwargs):
print 'get new comment called'
self.retreat_one_move()
if self.comment_text == '[color=444444]Long press to add comment.[/color]':
popup = Popup(content=CommentInput(board=self,comment=''),title='Edit comment:',size_hint=(0.95,0.45),pos_hint={'top':0.95})
else:
popup = Popup(content=CommentInput(board=self,comment=self.comment_text),title='Edit comment:',size_hint=(0.85,0.55),pos=(0.075*Window.width, 0.95*Window.height))
popup.content.popup = popup
if platform() == 'android':
import android
android.vibrate(0.1)
popup.open()
def set_new_comment(self,comment):
self.comment_text = comment
self.abstractboard.curnode.set('C',comment)
def clear_ld_markers(self):
for coords in self.ld_markers:
marker = self.ld_markers[coords]
self.remove_widget(marker)
self.ld_markers = {}
print 'new self.ld_markers', self.ld_markers
# def make_areamarker_at(self, touch):
# if self.areamarker is not None:
# marker = self.areamarker
# else:
# marker = AreaMarker(board=self)
# self.add_widget(marker)
# coord = self.pos_to_coord(touch.pos)
# marker.start_coord = coord
# marker.end_coord = coord
# self.areamarker = marker
# def clear_areamarker(self, *args):
# if self.areamarker is not None:
# marker = self.areamarker
# self.remove_widget(marker)