-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjgoboard-3.4.2.js
More file actions
2246 lines (1884 loc) · 64.5 KB
/
jgoboard-3.4.2.js
File metadata and controls
2246 lines (1884 loc) · 64.5 KB
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
/* jgoboard by Joonas Pihlajamaa, slightly modified by Christopher Clark */
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
//var request = require('superagent');
var C = require('./constants');
/**
* Automatic div module.
* @module autodiv
*/
function parseMarkup(str) {
var lines = str.split('\n'), data = [];
// Handle div contents as diagram contents
for(var i = 0, len = lines.length; i < len; ++i) {
var elems = [], line = lines[i];
for(var j = 0, len2 = line.length; j < len2; ++j) {
switch(line[j]) {
case '.':
elems.push({type: C.CLEAR}); break;
case 'o':
elems.push({type: C.WHITE}); break;
case 'x':
elems.push({type: C.BLACK}); break;
case ' ':
break; // ignore whitespace
default: // assume marker
if(!elems.length) break; // no intersection yet
// Append to mark so x123 etc. are possible
if(elems[elems.length - 1].mark)
elems[elems.length - 1].mark += line[j];
else
elems[elems.length - 1].mark = line[j];
}
}
if(elems.length) data.push(elems);
}
return data;
}
// Array of loaded boards
//var boards = [];
// Available attributes:
// data-jgostyle: Evaluated and used as board style
// data-jgosize: Used as board size unless data-jgosgf is defined
// data-jgoview: Used to define viewport
function process(JGO, div) {
// Handle special jgo-* attributes
var style, width, height, TL, BR; // last two are viewport
if(div.getAttribute('data-jgostyle')) {
/*jshint evil:true */
style = eval(div.getAttribute('data-jgostyle'));
} else style = JGO.BOARD.medium;
if(div.getAttribute('data-jgosize')) {
var size = div.getAttribute('data-jgosize');
if(size.indexOf('x') != -1) {
width = parseInt(size.substring(0, size.indexOf('x')));
height = parseInt(size.substr(size.indexOf('x')+1));
} else width = height = parseInt(size);
}
//if(div.getAttribute('data-jgosgf'))
var data = parseMarkup(div.innerHTML);
div.innerHTML = '';
if(!width) { // Size still missing
if(!data.length) return; // no size or data, no board
height = data.length;
width = data[0].length;
}
var jboard = new JGO.Board(width, height);
var jsetup = new JGO.Setup(jboard, style);
if(div.getAttribute('data-jgoview')) {
var tup = div.getAttribute('data-jgoview').split('-');
TL = jboard.getCoordinate(tup[0]);
BR = jboard.getCoordinate(tup[1]);
} else {
TL = new JGO.Coordinate(0,0);
BR = new JGO.Coordinate(width-1, height-1);
}
jsetup.view(TL.i, TL.j, width-TL.i, height-TL.j);
var c = new JGO.Coordinate();
for(c.j = TL.j; c.j <= BR.j; ++c.j) {
for(c.i = TL.i; c.i <= BR.i; ++c.i) {
var elem = data[c.j - TL.j][c.i - TL.i];
jboard.setType(c, elem.type);
if(elem.mark) jboard.setMark(c, elem.mark);
}
}
jsetup.create(div);
}
/**
* Find all div elements with class 'jgoboard' and initialize them.
*/
exports.init = function(document, JGO) {
var matches = document.querySelectorAll('div.jgoboard');
for(var i = 0, len = matches.length; i < len; ++i)
process(JGO, matches[i]);
};
},{"./constants":4}],2:[function(require,module,exports){
'use strict';
var Coordinate = require('./coordinate');
var C = require('./constants');
var util = require('./util');
/**
* Go board class for storing intersection states. Also has listeners that
* are notified on any changes to the board via setType() and setMark().
*
* @param {int} width The width of the board
* @param {int} [height] The height of the board
* @constructor
*/
var Board = function(width, height) {
this.width = width;
if(height !== undefined)
this.height = height;
else { //noinspection JSSuspiciousNameCombination
this.height = this.width;
}
this.listeners = [];
this.shading = [];
this.stones = [];
this.marks = [];
this.shades = false;
// Initialize stones and marks
for(var i=0; i<this.width; ++i) {
var stoneArr = [], markArr = [];
for(var j=0; j<this.height; ++j) {
stoneArr.push(C.CLEAR);
markArr.push(C.MARK.NONE);
}
this.stones.push(stoneArr);
this.marks.push(markArr);
}
};
/**
* Add listener to the board. Listeners are passed an event object with
* event type ('type' or 'mark'), coordinate and board members, and new
* and old values as newVal and oldVal. Event object should be
* considered read only.
*
* @param {function} func A listener callback.
*/
Board.prototype.addListener = function(func) {
this.listeners.push(func);
};
/**
* Remove listener from the board.
*
* @param {function} func A listener callback.
*/
Board.prototype.removeListener = function(func) {
var index = this.listeners.indexOf(func);
if(index != -1) this.listeners.splice(index, 1);
};
/**
* Create coordinate from "J18" type of notation that depend from board size.
*
* @param {string} s The coordinate string.
*/
Board.prototype.getCoordinate = function(s) {
return new Coordinate(C.COORDINATES.indexOf(s.toUpperCase().substr(0,1)),
this.height - parseInt(s.substr(1)));
};
/**
* Make a human readable "J18" type string representation of the coordinate.
*
* @param {Coordinate} c Coordinate.
* @returns {string} representation.
*/
Board.prototype.toString = function(c) {
return C.COORDINATES[c.i] + (this.height-c.j);
};
/**
* Simple iteration over all coordinates.
*
* @param {func} func The iterator method, which is called with the
* coordinate, type and mark parameters.
* @param {int} [i1] Column start.
* @param {int} [j1] Row start.
* @param {int} [i2] Colunm end.
* @param {int} [j2] Row end.
*/
Board.prototype.each = function(func, i1, j1, i2, j2) {
var c = new Coordinate();
if(i1 === undefined) i1 = 0;
if(j1 === undefined) j1 = 0;
if(i2 === undefined) i2 = this.width-1;
if(j2 === undefined) j2 = this.height-1;
for(c.j=j1; c.j<=j2; c.j++)
for(c.i=i1; c.i<=i2; c.i++)
func(c.copy(), this.stones[c.i][c.j], this.marks[c.i][c.j]);
};
/**
* Clear board.
*/
Board.prototype.clear = function() {
this.each(function(c) {
this.setType(c, C.CLEAR);
this.setMark(c, C.MARK.NONE);
}.bind(this));
};
/**
* Set the intersection type at given coordinate(s).
*
* @param {Object} c A Coordinate or Array of them.
* @param {Object} t New type, e.g. CLEAR, BLACK, ...
*/
Board.prototype.setType = function(c, t) {
if(c instanceof Coordinate) {
var old = this.stones[c.i][c.j];
if(old == t) return; // no change
this.stones[c.i][c.j] = t;
var ev = { type: 'type', coordinate: c, board: this,
oldVal: old, newVal: t };
this.listeners.forEach(function(l) { l(ev); });
} else if(c instanceof Array) {
for(var i=0, len=c.length; i<len; ++i)
this.setType(c[i], t); // use ourself to avoid duplicate code
}
};
/**
* Set the intersection mark at given coordinate(s).
*
* @param {Object} c A Coordinate or Array of them.
* @param {Object} m New mark, e.g. MARK.NONE, MARK.TRIANGLE, ...
*/
Board.prototype.setMark = function(c, m) {
if(c instanceof Coordinate) {
var old = this.marks[c.i][c.j];
if(old == m) return; // no change
this.marks[c.i][c.j] = m;
var ev = { type: 'mark', coordinate: c, board: this,
oldVal: old, newVal: m };
this.listeners.forEach(function(l) { l(ev); });
} else if(c instanceof Array) {
for(var i=0, len=c.length; i<len; ++i)
this.setMark(c[i], m); // use ourself to avoid duplicate code
}
};
/**
* Get the intersection type(s) at given coordinate(s).
*
* @param {Object} c A Coordinate or an Array of them.
* @returns {Object} Type or array of types.
*/
Board.prototype.getType = function(c) {
var ret;
if(c instanceof Coordinate) {
ret = this.stones[c.i][c.j];
} else if(c instanceof Array) {
ret = [];
for(var i=0, len=c.length; i<len; ++i)
ret.push(this.stones[c[i].i][c[i].j]);
}
return ret;
};
/**
* Get the intersection mark(s) at given coordinate(s).
*
* @param {Object} c A Coordinate or an Array of them.
* @returns {Object} Mark or array of marks.
*/
Board.prototype.getMark = function(c) {
var ret;
if(c instanceof Coordinate) {
ret = this.marks[c.i][c.j];
} else if(c instanceof Array) {
ret = [];
for(var i=0, len=c.length; i<len; ++i)
ret.push(this.marks[c[i].i][c[i].j]);
}
return ret;
};
/**
* Get neighboring coordinates on board.
*
* @param {Coordinate} c The coordinate
* @returns {Array} The array of adjacent coordinates of given type (may be an empty array)
*/
Board.prototype.getAdjacent = function(c) {
var coordinates = [], i = c.i, j = c.j;
if(i>0)
coordinates.push(new Coordinate(i-1, j));
if(i+1<this.width)
coordinates.push(new Coordinate(i+1, j));
if(j>0)
coordinates.push(new Coordinate(i, j-1));
if(j+1<this.height)
coordinates.push(new Coordinate(i, j+1));
return coordinates;
};
/**
* Filter coordinates based on intersection type.
*
* @param {Object} c An array of Coordinates.
* @param {Object} t A type filter (return only matching type).
* @returns {Object} Object with attributes 'type' and 'mark', array or false.
*/
Board.prototype.filter = function(c, t) {
var ret = [];
for(var i=0, len=c.length; i<len; ++i)
if(this.stones[c[i].i][c[i].j] == t)
ret.push(c);
return ret;
};
/**
* Check if coordinates contain given type.
*
* @param {Object} c An array of Coordinates.
* @param {Object} t A type filter (return only matching type).
* @returns {bool} True or false.
*/
Board.prototype.hasType = function(c, t) {
for(var i=0, len=c.length; i<len; ++i)
if(this.stones[c[i].i][c[i].j] == t)
return true;
return false;
};
/**
* Search all intersections of similar type, return group and edge coordinates.
*
* @param {Coordinate} coord The coordinate from which to start search.
* @param {int} [overrideType] Treat current coordinate as this type.
* @returns {Object} Two arrays of coordinates in members 'group' and 'neighbors'.
*/
Board.prototype.getGroup = function(coord, overrideType) {
var type = overrideType || this.getType(coord), seen = {},
group = [coord.copy()], neighbors = [],
queue = this.getAdjacent(coord);
seen[coord.toString()] = true;
while(queue.length) {
var c = queue.shift();
if(c.toString() in seen)
continue; // seen already
else
seen[c.toString()] = true; // seen now
if(this.getType(c) == type) { // check if type is correct
group.push(c);
queue = queue.concat(this.getAdjacent(c)); // add prospects
} else
neighbors.push(c);
}
return {group: group, neighbors: neighbors};
};
/**
* Get a raw copy of board contents. Will not include any listeners!
*
* @returns {Object} Board contents.
*/
Board.prototype.getRaw = function() {
return {
width: this.width,
height: this.height,
stones: util.extend({}, this.stones),
marks: util.extend({}, this.marks)
};
};
/**
* Set a raw copy of board contents. Will not change or call any listeners!
*
* @param {Object} raw Board contents.
*/
Board.prototype.setRaw = function(raw) {
this.width = raw.width;
this.height = raw.height;
this.stones = raw.stones;
this.marks = raw.marks;
};
/**
* Calculate impact of a move on board. Returns a data structure outlining
* validness of move (success & errorMsg) and possible captures and ko
* coordinate.
*
* @param {Board} jboard Board to play the move on (stays unchanged).
* @param {Coordinate} coord Coordinate to play or null for pass.
* @param {int} stone Stone to play - BLACK or WHITE.
* @param {Coordinate} [ko] Coordinate of previous ko.
* @returns {Object} Move result data structure.
*/
Board.prototype.playMove = function(coord, stone, ko) {
var oppType = (stone == C.BLACK ? C.WHITE : C.BLACK),
captures = [], adjacent;
if(!coord) // pass
return { success: true, captures: [], ko: false };
if(this.getType(coord) != C.CLEAR)
return { success: false,
errorMsg: 'Cannot play on existing stone!' };
if(ko && coord.equals(ko))
return { success: false,
errorMsg: 'Cannot retake ko immediately!' };
adjacent = this.getAdjacent(coord); // find adjacent coordinates
for(var i=0; i<adjacent.length; i++) {
var c = adjacent[i];
if(this.getType(c) == oppType) { // potential capture
var g = this.getGroup(c);
if(this.filter(g.neighbors, C.CLEAR).length == 1)
captures = captures.concat(g.group);
}
}
// Suicide not allowed
if(captures.length === 0 &&
!this.hasType(this.getGroup(coord, stone).neighbors, C.CLEAR))
return { success: false,
errorMsg: 'Suicide is not allowed!' };
// Check for ko. Note that captures were not removed so there should
// be zero liberties around this stone in case of a ko.
if(captures.length == 1 && this.filter(adjacent, C.CLEAR).length === 0)
return { success: true, captures: captures, ko: captures[0].copy() };
return { success: true, captures: captures, ko: false };
};
module.exports = Board;
},{"./constants":4,"./coordinate":5,"./util":13}],3:[function(require,module,exports){
'use strict';
var C = require('./constants');
var Coordinate = require('./coordinate');
var Stones = require('./stones');
var util = require('./util');
/**
* Create a jGoBoard canvas object.
*
* @param {Object} elem Container HTML element or its id.
* @param {Object} opt Options object.
* @param {Object} images Set of images (or false values) for drawing.
* @constructor
*/
var Canvas = function(elem, opt, images) {
/* global document */
if(typeof elem === 'string')
elem = document.getElementById(elem);
var canvas = document.createElement('canvas'), i, j;
var padLeft = opt.edge.left ? opt.padding.normal : opt.padding.clipped,
padRight = opt.edge.right ? opt.padding.normal : opt.padding.clipped,
padTop = opt.edge.top ? opt.padding.normal : opt.padding.clipped,
padBottom = opt.edge.bottom ? opt.padding.normal : opt.padding.clipped;
this.marginLeft = opt.edge.left ? opt.margin.normal : opt.margin.clipped;
this.marginRight = opt.edge.right ? opt.margin.normal : opt.margin.clipped;
this.marginTop = opt.edge.top ? opt.margin.normal : opt.margin.clipped;
this.marginBottom = opt.edge.bottom ? opt.margin.normal : opt.margin.clipped;
this.boardWidth = padLeft + padRight +
opt.grid.x * opt.view.width;
this.boardHeight = padTop + padBottom +
opt.grid.y * opt.view.height;
this.width = canvas.width =
this.marginLeft + this.marginRight + this.boardWidth;
this.height = canvas.height =
this.marginTop + this.marginBottom + this.boardHeight;
this.listeners = {'click': [], 'mousemove': [], 'mouseout': []};
/**
* Get board coordinate based on screen coordinates.
* @param {number} x Coordinate.
* @param {number} y Coordinate.
* @returns {Coordinate} Board coordinate.
*/
this.getCoordinate = function(pageX, pageY) {
var bounds = canvas.getBoundingClientRect(),
scaledX = (pageX - bounds.left) * canvas.width / (bounds.right - bounds.left),
scaledY = (pageY - bounds.top) * canvas.height / (bounds.bottom - bounds.top);
return new Coordinate(
Math.floor((scaledX-this.marginLeft-padLeft)/opt.grid.x) + opt.view.xOffset,
Math.floor((scaledY-this.marginTop-padTop)/opt.grid.y) + opt.view.yOffset);
}.bind(this);
// Click handler will call all listeners passing the coordinate of click
// and the click event
canvas.onclick = function(ev) {
var c = this.getCoordinate(ev.clientX, ev.clientY),
listeners = this.listeners.click;
for(var l=0; l<listeners.length; l++)
listeners[l].call(this, c.copy(), ev);
}.bind(this);
// Move handler will call all listeners passing the coordinate of move
// whenever mouse moves over a new intersection
canvas.onmousemove = function(ev) {
if(!this.listeners.mousemove.length) return;
var c = this.getCoordinate(ev.clientX, ev.clientY),
listeners = this.listeners.mousemove;
var lastMove = new Coordinate(-1, -1);
if(c.i < this.opt.view.xOffset ||
c.i >= this.opt.view.xOffset + this.opt.view.width)
c.i = -1;
if(c.j < this.opt.view.yOffset ||
c.j >= this.opt.view.yOffset + this.opt.view.height)
c.j = -1;
if(lastMove.equals(c))
return; // no change
else
lastMove = c.copy();
for(var l=0; l<listeners.length; l++)
listeners[l].call(this, c.copy(), ev);
}.bind(this);
// Mouseout handler will again call all listeners of that event, no
// coordinates will be passed of course, only the event
canvas.onmouseout = function(ev) {
var listeners = this.listeners.mouseout;
for(var l=0; l<listeners.length; l++)
listeners[l].call(this, ev);
}.bind(this);
elem.appendChild(canvas);
this.ctx = canvas.getContext('2d');
this.opt = util.extend({}, opt); // make a copy just in case
this.stones = new Stones(opt, images);
this.images = images;
// Fill margin with correct color
this.ctx.fillStyle = opt.margin.color;
this.ctx.fillRect(0, 0, canvas.width, canvas.height);
if(this.images.board) {
// Prepare to draw board with shadow
this.ctx.save();
this.ctx.shadowColor = opt.boardShadow.color;
this.ctx.shadowBlur = opt.boardShadow.blur;
this.ctx.shadowOffsetX = opt.boardShadow.offX;
this.ctx.shadowOffsetX = opt.boardShadow.offY;
var clipTop = opt.edge.top ? 0 : this.marginTop,
clipLeft = opt.edge.left ? 0 : this.marginLeft,
clipBottom = opt.edge.bottom ? 0 : this.marginBottom,
clipRight = opt.edge.right ? 0 : this.marginRight;
// Set clipping to throw shadow only on actual edges
this.ctx.beginPath();
this.ctx.rect(clipLeft, clipTop,
canvas.width - clipLeft - clipRight,
canvas.height - clipTop - clipBottom);
this.ctx.clip();
this.ctx.drawImage(this.images.board, 0, 0,
this.boardWidth, this.boardHeight,
this.marginLeft, this.marginTop,
this.boardWidth, this.boardHeight);
// Draw lighter border around the board to make it more photography
this.ctx.strokeStyle = opt.border.color;
this.ctx.lineWidth = opt.border.lineWidth;
this.ctx.beginPath();
this.ctx.rect(this.marginLeft, this.marginTop,
this.boardWidth, this.boardHeight);
this.ctx.stroke();
this.ctx.restore(); // forget shadow and clipping
}
// Top left center of grid (not edge, center!)
this.gridTop = this.marginTop + padTop + opt.grid.y / 2;
this.gridLeft = this.marginLeft + padLeft + opt.grid.x / 2;
this.ctx.strokeStyle = opt.grid.color;
var smt = this.opt.grid.smooth; // with 0.5 there will be full antialias
// Draw vertical gridlines
for(i=0; i<opt.view.width; i++) {
if((i === 0 && opt.edge.left) || (i+1 == opt.view.width && opt.edge.right))
this.ctx.lineWidth = opt.grid.borderWidth;
else
this.ctx.lineWidth = opt.grid.lineWidth;
this.ctx.beginPath();
this.ctx.moveTo(smt + this.gridLeft + opt.grid.x * i,
smt + this.gridTop - (opt.edge.top ? 0 : opt.grid.y / 2 + padTop/2));
this.ctx.lineTo(smt + this.gridLeft + opt.grid.x * i,
smt + this.gridTop + opt.grid.y * (opt.view.height - 1) +
(opt.edge.bottom ? 0 : opt.grid.y / 2 + padBottom/2));
this.ctx.stroke();
}
// Draw horizontal gridlines
for(i=0; i<opt.view.height; i++) {
if((i === 0 && opt.edge.top) || (i+1 == opt.view.height && opt.edge.bottom))
this.ctx.lineWidth = opt.grid.borderWidth;
else
this.ctx.lineWidth = opt.grid.lineWidth;
this.ctx.beginPath();
this.ctx.moveTo(smt + this.gridLeft - (opt.edge.left ? 0 : opt.grid.x / 2 + padLeft/2),
smt + this.gridTop + opt.grid.y * i);
this.ctx.lineTo(smt + this.gridLeft + opt.grid.x * (opt.view.width - 1) +
(opt.edge.right ? 0 : opt.grid.x / 2 + padRight/2),
smt + this.gridTop + opt.grid.y * i);
this.ctx.stroke();
}
if(opt.stars.points) { // If star points
var step = (opt.board.width - 1) / 2 - opt.stars.offset;
// 1, 4, 5, 8 and 9 points are supported, rest will result in randomness
for(j=0; j<3; j++) {
for(i=0; i<3; i++) {
if(j == 1 && i == 1) { // center
if(opt.stars.points % 2 === 0)
continue; // skip center
} else if(i == 1 || j == 1) { // non-corners
if(opt.stars.points < 8)
continue; // skip non-corners
} else { // corners
if(opt.stars.points < 4)
continue; // skip corners
}
var x = (opt.stars.offset + i * step) - opt.view.xOffset,
y = (opt.stars.offset + j * step) - opt.view.yOffset;
if(x < 0 || y < 0 || x >= opt.view.width || y >= opt.view.height)
continue; // invisible
this.ctx.beginPath();
this.ctx.arc(smt + this.gridLeft + x * opt.grid.x,
smt + this.gridTop + y * opt.grid.y,
opt.stars.radius, 2*Math.PI, false);
this.ctx.fillStyle = opt.grid.color;
this.ctx.fill();
}
}
}
this.ctx.font = opt.coordinates.font;
this.ctx.fillStyle = opt.coordinates.color;
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
// Draw horizontal coordinates
for(i=0; i<opt.view.width; i++) {
if(opt.coordinates && opt.coordinates.top)
this.ctx.fillText(C.COORDINATES[i + opt.view.xOffset],
this.gridLeft + opt.grid.x * i,
this.marginTop / 2);
if(opt.coordinates && opt.coordinates.bottom)
this.ctx.fillText(C.COORDINATES[i + opt.view.xOffset],
this.gridLeft + opt.grid.x * i,
canvas.height - this.marginBottom / 2);
}
// Draw vertical coordinates
for(i=0; i<opt.view.height; i++) {
if(opt.coordinates && opt.coordinates.left)
this.ctx.fillText(''+(opt.board.height-opt.view.yOffset-i),
this.marginLeft / 2,
this.gridTop + opt.grid.y * i);
if(opt.coordinates && opt.coordinates.right)
this.ctx.fillText(''+(opt.board.height-opt.view.yOffset-i),
canvas.width - this.marginRight / 2,
this.gridTop + opt.grid.y * i);
}
// Store rendered board in another canvas for fast redraw
this.backup = document.createElement('canvas');
this.backup.width = canvas.width;
this.backup.height = canvas.height;
this.backup.getContext('2d').drawImage(canvas,
0, 0, canvas.width, canvas.height,
0, 0, canvas.width, canvas.height);
// Clip further drawing to board only
this.ctx.beginPath();
this.ctx.rect(this.marginLeft, this.marginTop, this.boardWidth, this.boardHeight);
this.ctx.clip();
// Fix Chromium bug with image glitches unless they are drawn once
// https://code.google.com/p/chromium/issues/detail?id=469906
if(this.images.black) this.ctx.drawImage(this.images.black, 10, 10);
if(this.images.white) this.ctx.drawImage(this.images.white, 10, 10);
if(this.images.shadow) this.ctx.drawImage(this.images.shadow, 10, 10);
// Sucks but works
this.restore(this.marginLeft, this.marginTop, this.boardWidth, this.boardHeight);
};
/**
* Restore portion of canvas.
*/
Canvas.prototype.restore = function(x, y, w, h) {
x = Math.floor(x);
y = Math.floor(y);
this.ctx.drawImage(this.backup, x, y, w, h, x, y, w, h);
};
/**
* Get X coordinate based on column.
* @returns {number} Coordinate.
*/
Canvas.prototype.getX = function(i) {
return this.gridLeft + this.opt.grid.x * i;
};
/**
* Get Y coordinate based on row.
* @returns {number} Coordinate.
*/
Canvas.prototype.getY = function(j) {
return this.gridTop + this.opt.grid.y * j;
};
/**
* Redraw canvas portion using a board.
*
* @param {Board} jboard Board object.
* @param {number} i1 Starting column to be redrawn.
* @param {number} j1 Starting row to be redrawn.
* @param {number} i2 Ending column to be redrawn (inclusive).
* @param {number} j2 Ending row to be redrawn (inclusive).
*/
Canvas.prototype.draw = function(jboard, i1, j1, i2, j2) {
i1 = Math.max(i1, this.opt.view.xOffset);
j1 = Math.max(j1, this.opt.view.yOffset);
i2 = Math.min(i2, this.opt.view.xOffset + this.opt.view.width - 1);
j2 = Math.min(j2, this.opt.view.yOffset + this.opt.view.height - 1);
if(i2 < i1 || j2 < j1)
return; // nothing to do here
var x = this.getX(i1 - this.opt.view.xOffset) - this.opt.grid.x,
y = this.getY(j1 - this.opt.view.yOffset) - this.opt.grid.y,
w = this.opt.grid.x * (i2 - i1 + 2),
h = this.opt.grid.y * (j2 - j1 + 2);
this.ctx.save();
this.ctx.beginPath();
this.ctx.rect(x, y, w, h);
this.ctx.clip(); // only apply redraw to relevant area
this.restore(x, y, w, h); // restore background
// Expand redrawn intersections while keeping within viewport
i1 = Math.max(i1-1, this.opt.view.xOffset);
j1 = Math.max(j1-1, this.opt.view.yOffset);
i2 = Math.min(i2+1, this.opt.view.xOffset + this.opt.view.width - 1);
j2 = Math.min(j2+1, this.opt.view.yOffset + this.opt.view.height - 1);
var isLabel = /^[a-zA-Z1-9]/;
// Stone radius derived marker size parameters
var stoneR = this.opt.stone.radius,
clearW = stoneR * 1.5, clearH = stoneR * 1.2, clearFunc;
// Clear grid for labels on clear intersections before casting shadows
if(this.images.board) { // there is a board texture
clearFunc = function(ox, oy) {
this.ctx.drawImage(this.images.board,
ox - this.marginLeft - clearW / 2, oy - this.marginTop - clearH / 2, clearW, clearH,
ox - clearW / 2, oy - clearH / 2, clearW, clearH);
}.bind(this);
} else { // no board texture
this.ctx.fillStyle = this.opt.margin.color;
clearFunc = function(ox, oy) {
this.ctx.fillRect(ox - clearW / 2, oy - clearH / 2, clearW, clearH);
}.bind(this);
}
// Clear board grid under markers when needed
jboard.each(function(c, type, mark) {
// Note: Use of smt has been disabled here for clear results
var ox = this.getX(c.i - this.opt.view.xOffset);
var oy = this.getY(c.j - this.opt.view.yOffset);
if(type == C.CLEAR && mark && isLabel.test(mark))
clearFunc(ox, oy);
}.bind(this), i1, j1, i2, j2); // provide iteration limits
// After the board has been cleared, but before shadows and stones have been drawn,
// draw in the shading if any exists, Chris Clark
var shadeSize = 8.5;
this.ctx.lineWidth = this.opt.grid.borderWidth;
if (jboard.shades) {
jboard.each(function(c, type) {
var i = c.i + c.j * 19;
var strength = jboard.shades[i];
var color = "rgba(255," + Math.floor((1.0-strength)*255) + ",0,0.7)";
this.ctx.fillStyle = color;
var ox = this.getX(c.i - this.opt.view.xOffset);
var oy = this.getY(c.j - this.opt.view.yOffset);
// We need to redraw the lines to avoid some weird coloring affect that occur because
// (I think?) cause by the clear function removing them
this.ctx.beginPath();
this.ctx.moveTo(ox, oy - shadeSize);
this.ctx.lineTo(ox, oy + shadeSize);
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo(ox- shadeSize, oy);
this.ctx.lineTo(ox + shadeSize, oy);
this.ctx.stroke();
this.ctx.fillRect(ox - shadeSize, oy - shadeSize,shadeSize * 2, shadeSize * 2);
}.bind(this), i1, j1, i2, j2)
}
// Shadows
jboard.each(function(c, type) {
var ox = this.getX(c.i - this.opt.view.xOffset);
var oy = this.getY(c.j - this.opt.view.yOffset);
if(type == C.BLACK || type == C.WHITE) {
this.stones.drawShadow(this.ctx,
this.opt.shadow.xOff + ox,
this.opt.shadow.yOff + oy);
}
}.bind(this), i1, j1, i2, j2); // provide iteration limits
// Stones and marks
jboard.each(function(c, type, mark) {
var ox = (this.getX(c.i - this.opt.view.xOffset));
var oy = (this.getY(c.j - this.opt.view.yOffset));
var markColor;
switch(type) {
case C.BLACK:
case C.DIM_BLACK:
this.ctx.globalAlpha = type == C.BLACK ? 1 : this.opt.stone.dimAlpha;
this.stones.drawStone(this.ctx, type, ox, oy);
markColor = this.opt.mark.blackColor; // if we have marks, this is the color
break;
case C.WHITE:
case C.DIM_WHITE:
this.ctx.globalAlpha = type == C.WHITE ? 1 : this.opt.stone.dimAlpha;
this.stones.drawStone(this.ctx, type, ox, oy);
markColor = this.opt.mark.whiteColor; // if we have marks, this is the color
break;
default:
this.ctx.globalAlpha=1;
markColor = this.opt.mark.clearColor; // if we have marks, this is the color
}
// Common settings to all markers
this.ctx.lineWidth = this.opt.mark.lineWidth;
this.ctx.strokeStyle = markColor;
this.ctx.font = this.opt.mark.font;
this.ctx.fillStyle = markColor;
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
if(mark) this.stones.drawMark(this.ctx, mark, ox, oy);
}.bind(this), i1, j1, i2, j2); // provide iteration limits
this.ctx.restore(); // also restores globalAlpha
};
/**
* Add an event listener to canvas (click) events. The callback will be
* called with 'this' referring to Canvas object, with coordinate and
* event as parameters. Supported event types are 'click', 'mousemove',
* and 'mouseout'. With 'mouseout', there is no coordinate parameter for
* callback.
*
* @param {String} event The event to listen to, e.g. 'click'.
* @param {function} callback The callback.
*/
Canvas.prototype.addListener = function(event, callback) {
this.listeners[event].push(callback);
};
module.exports = Canvas;
},{"./constants":4,"./coordinate":5,"./stones":12,"./util":13}],4:[function(require,module,exports){
'use strict';
var util = require('./util');
/**
* Enum for intersection types. Aliased in JGO namespace, e.g. JGO.BLACK.
* @enum
* @readonly
*/
exports.INTERSECTION = {
CLEAR: 0,
/** Black stone */
BLACK: 1,
/** White stone */
WHITE: 2,
/** Semi-transparent black stone */
DIM_BLACK: 3,
/** Semi-transparent white stone */
DIM_WHITE: 4
};
// Alias all objects into globals
util.extend(exports, exports.INTERSECTION);
/**
* Enum for marker types.
* @readonly
* @enum
*/
exports.MARK = {
/** No marker ('') */
NONE: '',
/** Selected intersection */
SELECTED: '^',
/** Square */
SQUARE: '#',
/** Triangle */
TRIANGLE: '/',
/** Circle */
CIRCLE: '0',
/** Cross */
CROSS: '*',
/** Black territory */
BLACK_TERRITORY: '-',
/** White territory */
WHITE_TERRITORY: '+'
};