-
Notifications
You must be signed in to change notification settings - Fork 2
/
besogo.all.js
4012 lines (3537 loc) · 143 KB
/
besogo.all.js
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
/*
MIT License
Copyright (c) 2015-2018 Ye Wang
https://yewang.github.io/besogo/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
(function() { // Main components
'use strict';
var besogo = window.besogo = window.besogo || {}; // Establish our namespace
besogo.VERSION = '0.0.2-alpha';
besogo.create = function(container, options) {
var editor, // Core editor object
resizer, // Auto-resizing function
boardDiv, // Board display container
panelsDiv, // Parent container of panel divs
makers = { // Map to panel creators
control: besogo.makeControlPanel,
names: besogo.makeNamesPanel,
hint: besogo.makeHintPanel,
comment: besogo.makeCommentPanel,
tool: besogo.makeToolPanel,
tree: besogo.makeTreePanel,
file: besogo.makeFilePanel
},
insideText = container.textContent || container.innerText || '',
i, panelName; // Scratch iteration variables
container.className += ' besogo-container'; // Marks this div as initialized
// Process options and set defaults
options = options || {}; // Makes option checking simpler
options.size = besogo.parseSize(options.size || 19);
options.coord = options.coord || 'none';
options.tool = options.tool || 'auto';
if (options.panels === '') {
options.panels = [];
}
options.panels = options.panels || 'control+names+comment+tool+tree+file';
if (typeof options.panels === 'string') {
options.panels = options.panels.split('+');
}
options.path = options.path || '';
if (options.shadows === undefined) {
options.shadows = 'auto';
} else if (options.shadows === 'off') {
options.shadows = false;
}
// Make the core editor object
editor = besogo.makeEditor(options.size.x, options.size.y);
container.editor = editor;
editor.setTool(options.tool);
editor.setCoordStyle(options.coord);
if (options.realstones) { // Using realistic stones
editor.REAL_STONES = true;
editor.SHADOWS = options.shadows;
} else { // SVG stones
editor.SHADOWS = (options.shadows && options.shadows !== 'auto');
}
if (options.zoom) { // Set initial zoom value if given
editor.setZoom(+options.zoom)
}
if (!options.nokeys) { // Add keypress handler unless nokeys option is truthy
addKeypressHandler(container, editor);
}
if (options.sgf) { // Load SGF file from URL
try {
fetchParseLoad(options.sgf, editor, options.path);
} catch(e) {
// Silently fail on network error
}
} else if (insideText.match(/\s*\(\s*;/)) { // Text content looks like an SGF file
parseAndLoad(insideText, editor);
navigatePath(editor, options.path); // Navigate editor along path
}
if (typeof options.variants === 'number' || typeof options.variants === 'string') {
editor.setVariantStyle(+options.variants); // Converts to number
}
while (container.firstChild) { // Remove all children of container
container.removeChild(container.firstChild);
}
boardDiv = makeDiv('besogo-board'); // Create div for board display
besogo.makeBoardDisplay(boardDiv, editor); // Create board display
if (!options.nowheel) { // Add mousewheel handler unless nowheel option is truthy
addWheelHandler(boardDiv, editor);
}
if (options.panels.length > 0) { // Only create if there are panels to add
panelsDiv = makeDiv('besogo-panels');
for (i = 0; i < options.panels.length; i++) {
panelName = options.panels[i];
if (makers[panelName]) { // Only add if creator function exists
makers[panelName](makeDiv('besogo-' + panelName, panelsDiv), editor);
}
}
if (!panelsDiv.firstChild) { // If no panels were added
container.removeChild(panelsDiv); // Remove the panels div
panelsDiv = false; // Flags panels div as removed
}
}
if (options.resize === 'fixed') {
setDimensions(container.clientWidth, container.clientHeight);
} else { // Add auto-resizing unless resize option is "fixed"
resizer = function() {
var // height = window.innerHeight, // Viewport height
height = parseFloat(getComputedStyle(container.parentElement).height),
// Calculated width of parent element
width = parseFloat(getComputedStyle(container.parentElement).width),
minPanelsWidth = +(options.minpanelswidth || 350),
minPanelsHeight = +(options.minpanelsheight || 350),
// Calculated dimensions for the panels div
panelsWidth,
panelsHeight;
if (width >= height) { // Landscape mode
container.style['flex-direction'] = 'row';
panelsWidth = (width - height >= minPanelsWidth) ? (width - height) : minPanelsWidth;
panelsDiv.style.height = height + 'px';
panelsDiv.style.width = panelsWidth + 'px';
boardDiv.style.height = height + 'px';
boardDiv.style.width = (width - panelsWidth) + 'px';
} else { // Portrait mode
container.style['flex-direction'] = 'column';
panelsHeight = (height - width >= minPanelsHeight) ? (height - width) : minPanelsHeight;
panelsDiv.style.height = panelsHeight + 'px';
panelsDiv.style.width = width + 'px';
boardDiv.style.height = (height - panelsHeight) + 'px';
boardDiv.style.width = width + 'px';
}
};
window.addEventListener("resize", resizer);
resizer(); // Initial div sizing
}
// Sets dimensions with optional height param
function setDimensions(width, height) {
if (height && width > height) { // Landscape mode
container.style['flex-direction'] = 'row';
boardDiv.style.height = height + 'px';
boardDiv.style.width = height + 'px';
if (panelsDiv) {
panelsDiv.style.height = height + 'px';
panelsDiv.style.width = (width - height) + 'px';
}
} else { // Portrait mode (implied if height is missing)
container.style['flex-direction'] = 'column';
boardDiv.style.height = width + 'px';
boardDiv.style.width = width + 'px';
if (panelsDiv) {
if (height) { // Only set height if param present
panelsDiv.style.height = (height - width) + 'px';
}
panelsDiv.style.width = width + 'px';
}
}
}
// Creates and adds divs to specified parent or container
function makeDiv(className, parent) {
var div = document.createElement("div");
if (className) {
div.className = className;
}
parent = parent || container;
parent.appendChild(div);
return div;
}
}; // END function besogo.create
// Parses size parameter from SGF format
besogo.parseSize = function(input) {
var matches,
sizeX,
sizeY;
input = (input + '').replace(/\s/g, ''); // Convert to string and remove whitespace
matches = input.match(/^(\d+):(\d+)$/); // Check for #:# pattern
if (matches) { // Composed value pattern found
sizeX = +matches[1]; // Convert to numbers
sizeY = +matches[2];
} else if (input.match(/^\d+$/)) { // Check for # pattern
sizeX = +input; // Convert to numbers
sizeY = +input; // Implied square
} else { // Invalid input format
sizeX = sizeY = 19; // Default size value
}
if (sizeX > 52 || sizeX < 1 || sizeY > 52 || sizeY < 1) {
sizeX = sizeY = 19; // Out of range, set to default
}
return { x: sizeX, y: sizeY };
};
// Automatically converts document elements into besogo instances
besogo.autoInit = function() {
var allDivs = document.getElementsByTagName('div'), // Live collection of divs
targetDivs = [], // List of divs to auto-initialize
options, // Structure to hold options
i, j, attrs; // Scratch iteration variables
for (i = 0; i < allDivs.length; i++) { // Iterate over all divs
if ( (hasClass(allDivs[i], 'besogo-editor') || // Has an auto-init class
hasClass(allDivs[i], 'besogo-viewer') ||
hasClass(allDivs[i], 'besogo-diagram')) &&
!hasClass(allDivs[i], 'besogo-container') ) { // Not already initialized
targetDivs.push(allDivs[i]);
}
}
for (i = 0; i < targetDivs.length; i++) { // Iterate over target divs
options = {}; // Clear the options struct
if (hasClass(targetDivs[i], 'besogo-editor')) {
options.panels = ['control', 'names', 'comment', 'tool', 'tree', 'file'];
options.tool = 'auto';
} else if (hasClass(targetDivs[i], 'besogo-viewer')) {
options.panels = ['control', 'names', 'comment'];
options.tool = 'navOnly';
} else if (hasClass(targetDivs[i], 'besogo-diagram')) {
options.panels = [];
options.tool = 'navOnly';
}
attrs = targetDivs[i].attributes;
for (j = 0; j < attrs.length; j++) { // Load attributes as options
options[attrs[j].name] = attrs[j].value;
}
besogo.create(targetDivs[i], options);
}
function hasClass(element, str) {
return (element.className.split(' ').indexOf(str) !== -1);
}
};
// Sets up keypress handling
function addKeypressHandler(container, editor) {
if (!container.getAttribute('tabindex')) {
container.setAttribute('tabindex', '0'); // Set tabindex to allow div focusing
}
container.addEventListener('keydown', function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 33: // page up
editor.prevNode(10);
break;
case 34: // page down
editor.nextNode(10);
break;
case 35: // end
editor.nextNode(-1);
break;
case 36: // home
editor.prevNode(-1);
break;
case 37: // left
if ( evt.shiftKey ) {
editor.prevBranchPoint();
} else {
editor.prevNode(1);
}
break;
case 38: // up
editor.nextSibling(-1);
break;
case 39: // right
editor.nextNode(1);
break;
case 40: // down
editor.nextSibling(1);
break;
case 46: // delete
editor.cutCurrent();
break;
} // END switch (evt.keyCode)
if (evt.keyCode >= 33 && evt.keyCode <= 40) {
evt.preventDefault(); // Suppress page nav controls
}
}); // END func() and addEventListener
} // END function addKeypressHandler
// Sets up mousewheel handling
function addWheelHandler(boardDiv, editor) {
boardDiv.addEventListener('wheel', function(evt) {
evt = evt || window.event;
if (evt.deltaY > 0) {
editor.nextNode(1);
evt.preventDefault();
} else if (evt.deltaY < 0) {
editor.prevNode(1);
evt.preventDefault();
}
});
}
// Parses SGF string and loads into editor
function parseAndLoad(text, editor) {
var sgf;
try {
sgf = besogo.parseSgf(text);
} catch (error) {
return; // Silently fail on parse error
}
besogo.loadSgf(sgf, editor);
}
// Fetches text file at url from same domain
function fetchParseLoad(url, editor, path) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) { // Successful fetch
parseAndLoad(http.responseText, editor);
navigatePath(editor, path);
}
};
http.overrideMimeType('text/plain'); // Prevents XML parsing and warnings
http.open("GET", url, true); // Asynchronous load
http.send();
}
function navigatePath(editor, path) {
var subPaths,
i, j; // Scratch iteration variables
path = path.split(/[Nn]+/); // Split into parts that start in next mode
for (i = 0; i < path.length; i++) {
subPaths = path[i].split(/[Bb]+/); // Split on switches into branch mode
executeMoves(subPaths[0], false); // Next mode moves
for (j = 1; j < subPaths.length; j++) { // Intentionally starting at 1
executeMoves(subPaths[j], true); // Branch mode moves
}
}
function executeMoves(part, branch) {
var i;
part = part.split(/\D+/); // Split on non-digits
for (i = 0; i < part.length; i++) {
if (part[i]) { // Skip empty strings
if (branch) { // Branch mode
if (editor.getCurrent().children.length) {
editor.nextNode(1);
editor.nextSibling(part[i] - 1);
}
} else { // Next mode
editor.nextNode(+part[i]); // Converts to number
}
}
}
}
}
})(); // END closure
besogo.makeBoardDisplay = function(container, editor) {
'use strict';
var CELL_SIZE = 88, // Including line width
COORD_MARGIN = 75, // Margin for coordinate labels
EXTRA_MARGIN = 6, // Extra margin on the edge of board
BOARD_MARGIN, // Total board margin
// Board size parameters
sizeX = editor.getCurrent().getSize().x,
sizeY = editor.getCurrent().getSize().y,
svg, // Holds the overall board display SVG element
stoneGroup, // Group for stones
markupGroup, // Group for markup
hoverGroup, // Group for hover layer
markupLayer, // Array of markup layer elements
hoverLayer, // Array of hover layer elements
randIndex, // Random index for stone images
TOUCH_FLAG = false, // Flag for touch interfaces
xDown = null, // Touch event start flags
yDown = null;
initializeBoard(editor.getCoordStyle(), editor.getZoom()); // Initialize SVG element and draw the board
container.appendChild(svg); // Add the SVG element to the document
editor.addListener(update); // Register listener to handle editor/game state updates
redrawAll(editor.getCurrent()); // Draw stones, markup and hover layer
// Set listener to detect touch interfaces
container.addEventListener('touchstart', setTouchFlag);
// Function for setting the flag for touch interfaces
function setTouchFlag () {
TOUCH_FLAG = true; // Set flag to prevent needless function calls
hoverLayer = []; // Drop hover layer references, kills events
svg.removeChild(hoverGroup); // Remove hover group from SVG
// Remove self when done
container.removeEventListener('touchstart', setTouchFlag);
}
container.addEventListener('touchstart', handleTouchStart, false);
container.addEventListener('touchmove', handleTouchMove, false);
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
}
function handleTouchMove(evt) {
var xUp = evt.touches[0].clientX,
yUp = evt.touches[0].clientY,
xDiff, yDiff;
if ( ! xDown || ! yDown ) {
return;
}
xDiff = xDown - xUp;
yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {
if ( xDiff > 0 ) {
editor.nextNode(1);
} else {
editor.prevNode(1);
}
} else {
if ( yDiff > 0 ) {
editor.nextSibling(1);
} else {
editor.nextSibling(-1);
}
}
xDown = null;
yDown = null;
}
// Initializes the SVG and draws the board
function initializeBoard(coord, zoom) {
drawBoard(coord, zoom); // Initialize the SVG element and draw the board
stoneGroup = besogo.svgEl("g");
markupGroup = besogo.svgEl("g");
svg.appendChild(stoneGroup); // Add placeholder group for stone layer
svg.appendChild(markupGroup); // Add placeholder group for markup layer
if (!TOUCH_FLAG) {
hoverGroup = besogo.svgEl("g");
svg.appendChild(hoverGroup);
}
addEventTargets(); // Add mouse event listener layer
if (editor.REAL_STONES) { // Generate index for realistic stone images
randomizeIndex();
}
}
// Callback for board display redraws
function update(msg) {
var current = editor.getCurrent(),
currentSize = current.getSize(),
reinit = false, // Board redraw flag
oldSvg = svg;
// Check if board size has changed
if (currentSize.x !== sizeX || currentSize.y !== sizeY || msg.coord || msg.zoom) {
sizeX = currentSize.x;
sizeY = currentSize.y;
initializeBoard(msg.coord || editor.getCoordStyle(), msg.zoom || editor.getZoom());
container.replaceChild(svg, oldSvg);
reinit = true; // Flag board redrawn
}
// Redraw stones only if needed
if (reinit || msg.navChange || msg.stoneChange) {
redrawStones(current);
redrawMarkup(current);
redrawHover(current);
} else if (msg.markupChange || msg.treeChange) {
redrawMarkup(current);
redrawHover(current);
} else if (msg.tool || msg.label) {
redrawHover(current);
}
}
function redrawAll(current) {
redrawStones(current);
redrawMarkup(current);
redrawHover(current);
}
// Initializes the SVG element and draws the board
function drawBoard(coord, zoom) {
var boardWidth,
boardHeight,
string = "", // Path string for inner board lines
i; // Scratch iteration variable
BOARD_MARGIN = (coord === 'none' ? 0 : COORD_MARGIN) + EXTRA_MARGIN;
boardWidth = 2*BOARD_MARGIN + sizeX*CELL_SIZE;
boardHeight = 2*BOARD_MARGIN + sizeY*CELL_SIZE;
var viewBoxWidth = boardWidth / zoom;
var viewBoxHeight = boardHeight / zoom;
var viewBoxMinX = boardWidth - viewBoxWidth;
var viewBoxMinY = 0;
svg = besogo.svgEl("svg", { // Initialize the SVG element
width: "100%",
height: "100%",
viewBox: `${viewBoxMinX} ${viewBoxMinY} ${viewBoxWidth} ${viewBoxHeight}`
});
svg.appendChild(besogo.svgEl("rect", { // Fill background color
width: boardWidth,
height: boardHeight,
'class': 'besogo-svg-board'
}) );
svg.appendChild(besogo.svgEl("rect", { // Draw outer square of board
width: CELL_SIZE*(sizeX - 1),
height: CELL_SIZE*(sizeY - 1),
x: svgPos(1),
y: svgPos(1),
'class': 'besogo-svg-lines'
}) );
for (i = 2; i <= (sizeY - 1); i++) { // Horizontal inner lines
string += "M" + svgPos(1) + "," + svgPos(i) + "h" + CELL_SIZE*(sizeX - 1);
}
for (i = 2; i <= (sizeX - 1); i++) { // Vertical inner lines
string += "M" + svgPos(i) + "," + svgPos(1) + "v" + CELL_SIZE*(sizeY - 1);
}
svg.appendChild( besogo.svgEl("path", { // Draw inner lines of board
d: string,
'class': 'besogo-svg-lines'
}) );
drawHoshi(); // Draw the hoshi points
if (coord !== 'none') {
drawCoords(coord); // Draw the coordinate labels
}
}
// Draws coordinate labels on the board
function drawCoords(coord) {
var labels = besogo.coord[coord](sizeX, sizeY),
labelXa = labels.x, // Top edge labels
labelXb = labels.xb || labels.x, // Bottom edge
labelYa = labels.y, // Left edge
labelYb = labels.yb || labels.y, // Right edge
shift = COORD_MARGIN + 10,
i, x, y; // Scratch iteration variable
for (i = 1; i <= sizeX; i++) { // Draw column coordinate labels
x = svgPos(i);
drawCoordLabel(x, svgPos(1) - shift, labelXa[i]);
drawCoordLabel(x, svgPos(sizeY) + shift, labelXb[i]);
}
for (i = 1; i <= sizeY; i++) { // Draw row coordinate labels
y = svgPos(i);
drawCoordLabel(svgPos(1) - shift, y, labelYa[i]);
drawCoordLabel(svgPos(sizeX) + shift, y, labelYb[i]);
}
function drawCoordLabel(x, y, label) {
var element = besogo.svgEl("text", {
x: x,
y: y,
dy: ".65ex", // Seems to work for vertically centering these fonts
"font-size": 32,
"text-anchor": "middle", // Horizontal centering
"font-family": "Helvetica, Arial, sans-serif",
fill: 'black'
});
element.appendChild( document.createTextNode(label) );
svg.appendChild(element);
}
}
// Draws hoshi onto the board at procedurally generated locations
function drawHoshi() {
var cx, cy, // Center point calculation
pathStr = ""; // Path string for drawing star points
if (sizeX % 2 && sizeY % 2) { // Draw center hoshi if both dimensions are odd
cx = (sizeX - 1)/2 + 1; // Calculate the center of the board
cy = (sizeY - 1)/2 + 1;
drawStar(cx, cy);
if (sizeX >= 17 && sizeY >= 17) { // Draw side hoshi if at least 17x17 and odd
drawStar(4, cy);
drawStar(sizeX - 3, cy);
drawStar(cx, 4);
drawStar(cx, sizeY - 3);
}
}
if (sizeX >= 11 && sizeY >= 11) { // Corner hoshi at (4, 4) for larger sizes
drawStar(4, 4);
drawStar(4, sizeY - 3);
drawStar(sizeX - 3, 4);
drawStar(sizeX - 3, sizeY - 3);
} else if (sizeX >= 8 && sizeY >= 8) { // Corner hoshi at (3, 3) for medium sizes
drawStar(3, 3);
drawStar(3, sizeY - 2);
drawStar(sizeX - 2, 3);
drawStar(sizeX - 2, sizeY - 2);
} // No corner hoshi for smaller sizes
if (pathStr) { // Only need to add if hoshi drawn
svg.appendChild( besogo.svgEl('path', { // Drawing circles via path points
d: pathStr, // Hack to allow radius adjustment via stroke-width
'stroke-linecap': 'round', // Makes the points round
'class': 'besogo-svg-hoshi'
}) );
}
function drawStar(i, j) { // Extend path string to draw star point
pathStr += "M" + svgPos(i) + ',' + svgPos(j) + 'l0,0'; // Draws a point
}
}
// Remakes the randomized index for stone images
function randomizeIndex() {
var maxIndex = besogo.BLACK_STONES * besogo.WHITE_STONES,
i, j;
randIndex = [];
for (i = 1; i <= sizeX; i++) {
for (j = 1; j <= sizeY; j++) {
randIndex[fromXY(i, j)] = Math.floor(Math.random() * maxIndex);
}
}
}
// Adds a grid of squares to register mouse events
function addEventTargets() {
var element,
i, j;
for (i = 1; i <= sizeX; i++) {
for (j = 1; j <= sizeY; j++) {
element = besogo.svgEl("rect", { // Make a transparent event target
x: svgPos(i) - CELL_SIZE/2,
y: svgPos(j) - CELL_SIZE/2,
width: CELL_SIZE,
height: CELL_SIZE,
opacity: 0
});
// Add event listeners, using closures to decouple (i, j)
element.addEventListener("click", handleClick(i, j));
if (!TOUCH_FLAG) { // Skip hover listeners for touch interfaces
element.addEventListener("mouseover", handleOver(i, j));
element.addEventListener("mouseout", handleOut(i, j));
}
svg.appendChild(element);
}
}
}
function handleClick(i, j) { // Returns function for click handling
return function(event) {
// Call click handler in editor
editor.click(i, j, event.ctrlKey, event.shiftKey);
if(!TOUCH_FLAG) {
(handleOver(i, j))(); // Ensures that any updated tool is visible
}
};
}
function handleOver(i, j) { // Returns function for mouse over
return function() {
var element = hoverLayer[ fromXY(i, j) ];
if (element) { // Make tool action visible on hover over
element.setAttribute('visibility', 'visible');
}
};
}
function handleOut(i, j) { // Returns function for mouse off
return function() {
var element = hoverLayer[ fromXY(i, j) ];
if (element) { // Make tool action invisible on hover off
element.setAttribute('visibility', 'hidden');
}
};
}
// Redraws the stones
function redrawStones(current) {
var group = besogo.svgEl("g"), // New stone layer group
shadowGroup, // Group for shadow layer
i, j, x, y, color; // Scratch iteration variables
if (editor.SHADOWS) { // Add group for shawdows
shadowGroup = besogo.svgShadowGroup();
group.appendChild(shadowGroup);
}
for (i = 1; i <= sizeX; i++) {
for (j = 1; j <= sizeY; j++) {
color = current.getStone(i, j);
if (color) {
x = svgPos(i);
y = svgPos(j);
if (editor.REAL_STONES) { // Realistic stone
group.appendChild(besogo.realStone(x, y, color, randIndex[fromXY(i, j)]));
} else { // SVG stone
group.appendChild(besogo.svgStone(x, y, color));
}
if (editor.SHADOWS) { // Draw shadows
shadowGroup.appendChild(besogo.svgShadow(x - 2, y - 4));
shadowGroup.appendChild(besogo.svgShadow(x + 2, y + 4));
}
}
}
}
svg.replaceChild(group, stoneGroup); // Replace the stone group
stoneGroup = group;
}
// Redraws the markup
function redrawMarkup(current) {
var element, i, j, x, y, // Scratch iteration variables
group = besogo.svgEl("g"), // Group holding markup layer elements
lastMove = current.move,
variants = editor.getVariants(),
mark, // Scratch mark state {0, 1, 2, 3, 4, 5}
stone, // Scratch stone state {0, -1, 1}
color; // Scratch color string
markupLayer = []; // Clear the references to the old layer
// Mark all variants first, which allows them to be overwritten with hints later
markRemainingVariants(variants, current, group);
for (i = 1; i <= sizeX; i++) {
for (j = 1; j <= sizeY; j++) {
mark = current.getMarkup(i, j);
if (mark) {
x = svgPos(i);
y = svgPos(j);
stone = current.getStone(i, j);
color = stone; // Stone color int, may be overwriten with class str
if (lastMove && lastMove.x === i && lastMove.y === j) {
color = 'last';
}
else if (checkVariants(variants, current, i, j)) {
color = 'variant';
}
if (typeof mark === 'number') { // Markup is a basic shape
switch(mark) {
case 1: // Green (unnumbered and not used anymore)
element = besogo.svgCircle(x, y, color);
break;
case 2: // Yellow (actually purple)
element = besogo.svgSquare(x, y, color);
if (!stone) { // Check for exclusion if empty
if (current.checkExcluded(i, j, current.moveNumber + 1)) {
group.appendChild(element); // Cache the purple ring
element = besogo.svgBlock(x, y, color);
}
}
break;
case 3: // Missing
element = besogo.svgTriangle(x, y, color);
break;
}
if (mark < 0) { // Negative markup is green hint with number
if (!stone) { // If placing label on empty spot
element = makeBacker(x, y);
group.appendChild(element);
}
element = besogo.svgLabel(x, y, color, -mark + '');
markupLayer[ fromXY(i, j) ] = element;
group.appendChild(element);
element = besogo.svgCircle(x, y, color);
}
} else { // Markup is a label (unused for josekle)
if (!stone) { // If placing label on empty spot
element = makeBacker(x, y);
group.appendChild(element);
}
element = besogo.svgLabel(x, y, color, mark);
markupLayer[ fromXY(i, j) ] = element;
}
group.appendChild(element);
} // END if (mark)
} // END for j
} // END for i
// Mark last move with plus if not already marked
if (lastMove && lastMove.x !== 0 && lastMove.y !== 0) {
i = lastMove.x;
j = lastMove.y;
if (!markupLayer[ fromXY(i, j) ]) { // Last move not marked
element = besogo.svgPlus(svgPos(i), svgPos(j));
group.appendChild(element);
markupLayer[ fromXY(i, j) ] = element;
}
}
svg.replaceChild(group, markupGroup); // Replace the markup group
markupGroup = group;
} // END function redrawMarkup
function makeBacker(x, y) { // Makes a label markup backer at (x, y)
return besogo.svgEl("rect", {
x: x - CELL_SIZE/2,
y: y - CELL_SIZE/2,
height: CELL_SIZE,
width: CELL_SIZE,
opacity: 0.85,
stroke: "none",
'class': 'besogo-svg-board besogo-svg-backer'
});
}
// Checks if (x, y) is in variants
function checkVariants(variants, current, x, y) {
var i, move;
for (i = 0; i < variants.length; i++) {
if (variants[i] !== current) { // Skip current (within siblings)
move = variants[i].move;
if (move && move.x === x && move.y === y) {
return true;
}
}
}
return false;
}
// Marks variants that have not already been marked
function markRemainingVariants(variants, current, group) {
var element,
move, // Variant move
label, // Variant label
stone, // Stone state
i, x, y; // Scratch iteration variables
for (i = 0; i < variants.length; i++) {
if (variants[i] !== current) { // Skip current (within siblings)
move = variants[i].move;
// Check if move, not a pass, and no mark yet
if (move && move.x !== 0 && current.getMarkup(move.x, move.y) >= 0) {
stone = current.getStone(move.x, move.y);
x = svgPos(move.x); // Get SVG positions
y = svgPos(move.y);
if (!stone) { // If placing label on empty spot
element = makeBacker(x, y);
group.appendChild(element);
}
// Label variants with letters A-Z cyclically
label = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
element = besogo.svgLabel(x, y, 'variant', label);
group.appendChild(element);
markupLayer[ fromXY(move.x, move.y) ] = element;
}
}
}
} // END function markRemainingVariants
// Redraws the hover layer
function redrawHover(current) {
if (TOUCH_FLAG) {
return; // Do nothing for touch interfaces
}
var element, i, j, x, y, // Scratch iteration variables
group = besogo.svgEl("g"), // Group holding hover layer elements
tool = editor.getTool(),
children,
stone, // Scratch stone state {0, -1, 1} or move
color; // Scratch color string
hoverLayer = []; // Clear the references to the old layer
group.setAttribute('opacity', '0.35');
if (tool === 'navOnly') { // Render navOnly hover by iterating over children
children = current.children;
for (i = 0; i < children.length; i++) {
stone = children[i].move;
if (stone && stone.x !== 0) { // Child node is move and not a pass
x = svgPos(stone.x);
y = svgPos(stone.y);
element = besogo.svgStone(x, y, stone.color);
element.setAttribute('visibility', 'hidden');
group.appendChild(element);
hoverLayer[ fromXY(stone.x, stone.y) ] = element;
}
}
} else { // Render hover for other tools by iterating over grid
for (i = 1; i <= sizeX; i++) {
for (j = 1; j <= sizeY; j++) {
element = null;
x = svgPos(i);
y = svgPos(j);
stone = current.getStone(i, j);
color = (stone === -1) ? "white" : "black"; // White on black
switch(tool) {
case 'auto':
element = besogo.svgStone(x, y, current.nextMove());
break;
case 'playB':
element = besogo.svgStone(x, y, -1);
break;
case 'playW':
element = besogo.svgStone(x, y, 1);
break;
case 'addB':
if (stone === -1) {
element = besogo.svgCross(x, y, besogo.RED);
} else {
element = besogo.svgEl('g');
element.appendChild(besogo.svgStone(x, y, -1));
element.appendChild(besogo.svgPlus(x, y, besogo.RED));
}
break;
case 'addW':
if (stone === 1) {
element = besogo.svgCross(x, y, besogo.RED);
} else {
element = besogo.svgEl('g');
element.appendChild(besogo.svgStone(x, y, 1));
element.appendChild(besogo.svgPlus(x, y, besogo.RED));
}
break;
case 'addE':
if (stone) {
element = besogo.svgCross(x, y, besogo.RED);
}
break;
case 'clrMark':
break; // Nothing
case 'circle':
element = besogo.svgCircle(x, y, color);
break;
case 'square':
element = besogo.svgSquare(x, y, color);
break;
case 'triangle':
element = besogo.svgTriangle(x, y, color);
break;
case 'cross':
element = besogo.svgCross(x, y, color);
break;
case 'block':
element = besogo.svgBlock(x, y, color);
break;
case 'label':
element = besogo.svgLabel(x, y, stone, editor.getLabel());
break;
} // END switch (tool)
if (element) {
element.setAttribute('visibility', 'hidden');
group.appendChild(element);
hoverLayer[ fromXY(i, j) ] = element;
}
} // END for j
} // END for i
} // END else
svg.replaceChild(group, hoverGroup); // Replace the hover layer group
hoverGroup = group;
} // END function redrawHover
function svgPos(x) { // Converts (x, y) coordinates to SVG position