-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslingshotchess.js
713 lines (622 loc) · 31.9 KB
/
slingshotchess.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
const DEBUG_DRAW_COLLISION_CIRCLES = false;
const TOUCH_EVENT_DEBUG = false;
const TIMESTEPS_PER_SECOND = 30;
const MILLIS_BETWEEN_TIMESTEPS = 1000/TIMESTEPS_PER_SECOND;
const MAX_RENDER_SKIPS = 5;
const DT = MILLIS_BETWEEN_TIMESTEPS/1000.0;
const MAX_WORLD_SIZE_PIXELS = 600;
const SQUARE_WIDTH = 100;
const PIECE_WIDTH = 90;
const BOARD_SQUARES = 8;
const BOUNDARY_WIDTH = 100
const BOARD_WIDTH = BOARD_SQUARES*SQUARE_WIDTH;
const BOUNDARY_AND_BOARD_WIDTH = 2*BOUNDARY_WIDTH + BOARD_WIDTH;
const BOARD_OFFSET = BOUNDARY_WIDTH;
const WORLD_WIDTH = BOUNDARY_AND_BOARD_WIDTH
const BACKGROUND_COLOUR = "#ADD8E6";
const WHITE_COLOUR = "#F0D9B5";
const BLACK_COLOUR = "#B58863";
const FRICTION_COEFFICIENT = 0.2;
// The so-called coefficient of restitution, between 0 and 1.
// When it's 1, it's an elastic collision (all energy conserved). When
// it's 0, it's a perfectly inelastic collision.
// See: https://en.wikipedia.org/wiki/Inelastic_collision
const COLLISION_COEFFICIENT = 0.5;
const VELOCITY_FLOOR = 15;
const COLLISION_CIRCLE_NONTARGET_COLOUR = "#7e00007e";
const COLLISION_CIRCLE_TARGET_COLOUR = "#00e0007e";
const COLLISION_CIRCLE_DEBUG_COLOUR = "#FF0000";
const MAX_DRAG_DISTANCE = 200;
const MIN_DRAG_DISTANCE = 20;
const DRAG_CIRCLE_RADIUS = 15;
const DRAG_CIRCLE_COLOUR = "#7e7e7eAA";
const NUM_DRAG_CIRCLES = 3;
const TURN_INDICATOR_WIDTH = 275;
const TURN_INDICATOR_HEIGHT = 40;
const TURN_INDICATOR_TEXT_OFFSET = 10;
const TURN_INDICATOR_FONT_SIZE = 25;
// Lichess cburnett pieces encoded in base64.
// Available under the GNU Affero General Public License.
const pieceTypeToSrc = {
"wN": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0NSIgaGVpZ2h0PSI0NSI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiBzdHJva2U9IiMwMDAiIHN0cm9rZS13aWR0aD0iMS41IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxwYXRoIGQ9Ik0yMiAxMGMxMC41IDEgMTYuNSA4IDE2IDI5SDE1YzAtOSAxMC02LjUgOC0yMSIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0yNCAxOGMuMzggMi45MS01LjU1IDcuMzctOCA5LTMgMi0yLjgyIDQuMzQtNSA0LTEuMDQyLS45NCAxLjQxLTMuMDQgMC0zLTEgMCAuMTkgMS4yMy0xIDItMSAwLTQuMDAzIDEtNC00IDAtMiA2LTEyIDYtMTJzMS44OS0xLjkgMi0zLjVjLS43My0uOTk0LS41LTItLjUtMyAxLTEgMyAyLjUgMyAyLjVoMnMuNzgtMS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gMi41LTNjMSAwIDEgMyAxIDMiIGZpbGw9IiMwMDAiLz48cGF0aCBkPSJNOS41IDI1LjVhLjUuNSAwIDEgMS0xIDAgLjUuNSAwIDEgMSAxIDB6bTUuNDMzLTkuNzVhLjUgMS41IDMwIDEgMS0uODY2LS41LjUgMS41IDMwIDEgMSAuODY2LjV6IiBmaWxsPSIjZWNlY2VjIiBzdHJva2U9IiNlY2VjZWMiLz48cGF0aCBkPSJNMjQuNTUgMTAuNGwtLjQ1IDEuNDUuNS4xNWMzLjE1IDEgNS42NSAyLjQ5IDcuOSA2Ljc1UzM1Ljc1IDI5LjA2IDM1LjI1IDM5bC0uMDUuNWgyLjI1bC4wNS0uNWMuNS0xMC4wNi0uODgtMTYuODUtMy4yNS0yMS4zNC0yLjM3LTQuNDktNS43OS02LjY0LTkuMTktNy4xNmwtLjUxLS4xeiIgZmlsbD0iI2VjZWNlYyIgc3Ryb2tlPSJub25lIi8+PC9nPjwvc3ZnPg==",
}
const pieceTypeToImage = {};
// Initialise the image for each type of piece.
Object.entries(pieceTypeToSrc).forEach(([key, value]) => {
var img = new Image();
img.src = value;
pieceTypeToImage[key] = img;
});
async function waitForImage(img) {
await getPromise(img);
}
function getPromise(img) {
return new Promise(resolve => {
const listener = () => {
img.removeEventListener("load", listener);
resolve();
}
img.addEventListener("load", listener);
});
}
// Wait for the images to load so that we don't
// try to render them before they're ready.
Object.values(pieceTypeToImage).forEach(waitForImage);
const PieceColour = {Black: "b", White: "w"};
const PieceType = {Pawn: "P", Rook: "R", Bishop: "B", Knight: "N", King: "K", Queen: "Q"};
const PIECE_COLLISION_RADII = {};
PIECE_COLLISION_RADII[PieceType.Pawn] = 25;
PIECE_COLLISION_RADII[PieceType.Rook] = 25;
PIECE_COLLISION_RADII[PieceType.Bishop] = 25;
PIECE_COLLISION_RADII[PieceType.Knight] = 25;
PIECE_COLLISION_RADII[PieceType.King] = 25;
PIECE_COLLISION_RADII[PieceType.Queen] = 25;
const PIECE_MASS = {};
PIECE_MASS[PieceType.Pawn] = 2;
PIECE_MASS[PieceType.Rook] = 2.7;
PIECE_MASS[PieceType.Bishop] = 2.3;
PIECE_MASS[PieceType.Knight] = 2.3;
PIECE_MASS[PieceType.King] = 2.1;
PIECE_MASS[PieceType.Queen] = 3;
const PIECE_MAX_LAUNCH_VELOCITY = {};
PIECE_MAX_LAUNCH_VELOCITY[PieceType.Pawn] = 180;
PIECE_MAX_LAUNCH_VELOCITY[PieceType.Rook] = 300;
PIECE_MAX_LAUNCH_VELOCITY[PieceType.Bishop] = 300;
PIECE_MAX_LAUNCH_VELOCITY[PieceType.Knight] = 250;
PIECE_MAX_LAUNCH_VELOCITY[PieceType.King] = 180;
PIECE_MAX_LAUNCH_VELOCITY[PieceType.Queen] = 300;
var teamToMove = PieceColour.White;
var winningTeam = null;
var gameOver = false;
var turnInProgress = false;
var kingDead = {};
kingDead[PieceColour.White] = false;
kingDead[PieceColour.Black] = false;
class PieceInfo {
constructor(colour, type) {
this.colour = colour;
this.type = type;
}
}
class Piece {
constructor(x, y, info) {
this.coords = vec2d(x, y);
this.velocity = vec2d(0.0, 0.0);
this.info = info;
}
getImage() {
return pieceTypeToImage[this.info.colour + this.info.type];
}
radius() {
return PIECE_COLLISION_RADII[this.info.type];
}
mass() {
return PIECE_MASS[this.info.type];
}
maxVelocity() {
return PIECE_MAX_LAUNCH_VELOCITY[this.info.type];
}
}
function piecesIntersect(b1, b2) {
return euclideanDistance(b1.coords, b2.coords) < b1.radius() + b2.radius();
}
function pieceContains(piece, coords) {
return euclideanDistance(piece.coords, coords) < piece.radius();
}
function pushPiecesAlongRow(pieces, yIndex, colour) {
pieces.push(new Piece(boardIndexToCoord(0), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Rook)));
pieces.push(new Piece(boardIndexToCoord(1), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Knight)));
pieces.push(new Piece(boardIndexToCoord(2), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Bishop)));
pieces.push(new Piece(boardIndexToCoord(3), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Queen)));
pieces.push(new Piece(boardIndexToCoord(4), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.King)));
pieces.push(new Piece(boardIndexToCoord(5), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Bishop)));
pieces.push(new Piece(boardIndexToCoord(6), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Knight)));
pieces.push(new Piece(boardIndexToCoord(7), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Rook)));
}
function pushPawnsAlongRow(pieces, yIndex, colour) {
for (var xIndex = 0; xIndex < 8; xIndex += 1) {
pieces.push(
new Piece(boardIndexToCoord(xIndex), boardIndexToCoord(yIndex),
new PieceInfo(colour, PieceType.Pawn)));
}
}
// Create pieces in their starting positions!
var pieces = [];
pushPiecesAlongRow(pieces, 7, PieceColour.Black);
pushPawnsAlongRow(pieces, 6, PieceColour.Black);
pushPawnsAlongRow(pieces, 1, PieceColour.White);
pushPiecesAlongRow(pieces, 0, PieceColour.White);
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
const debugTouchSpan = document.createElement("span");
var pixelsPerUnitLength = 0;
var unitLengthsPerPixel = 0;
var clickPosition = null;
var targetPiece = null;
var currentMousePosition = null;
function eventDebugPrint(e) {
let c = Math.ceil;
let cmp = currentMousePosition == null ? {x:0, y:0} : currentMousePosition;
debugTouchSpan.innerText = `${e.type == undefined ? 'unknown' : e.type} @ x,y (${c(e.clientX)},${c(e.clientY)}) cms (${c(cmp.x)},${c(cmp.y)}) chpc: ${canvas.hasPointerCapture(e.pointerId)}`;
}
function init() {
if (TOUCH_EVENT_DEBUG) {
debugTouchSpan.style.display="block";
debugTouchSpan.style.textAlign="center";
let canvas = document.getElementsByTagName("canvas")[0];
canvas.parentNode.insertBefore(debugTouchSpan, canvas.nextSibling);
}
let resolvePointEvent = function(f) {
return function(e) {
f(e);
if (TOUCH_EVENT_DEBUG) {
eventDebugPrint(e);
}
}
}
window.addEventListener('pointerdown', resolvePointEvent(storeClickPosition));
window.addEventListener('pointerup', resolvePointEvent(releaseClick));
window.addEventListener('pointermove', resolvePointEvent(storeCurrentMousePosition));
window.addEventListener('pointercancel', resolvePointEvent(cancelClick));
}
/* simple ticker class */
let Ticker = class {
constructor(intervalms) {
this.ticks = -1;
this.waiter = null;
this.ticker = -1;
this.interval = intervalms;
}
isRunning() {
return this.ticker != -1;
}
start() {
if (!this.isRunning()) {
this.ticker = window.setInterval(this.tick.bind(this),this.interval);
}
this.tick();
}
stop() {
if (this.isRunning()) {
pause();
reset();
}
}
pause() {
if (this.isRunning()) {
window.clearInterval(this.ticker);
this.ticker = -1;
}
}
reset() {
this.ticks = 0;
}
tick() {
this.ticks++;
this.lastTick = Date.now();
if (this.waiter !== null) {
this.waiter();
this.waiter = null;
}
}
async waitForNextTick(currentTick) {
let p = new Promise( resolve => {
if (currentTick < this.ticks) {
resolve();
} else {
this.waiter = resolve;
}
});
return p;
}
}
async function runMainLoop() {
// Main game loop!
// https://dewitters.com/dewitters-gameloop/
let ticker = new Ticker(MILLIS_BETWEEN_TIMESTEPS);
let gametick = 0;
ticker.start();
while (true) {
await ticker.waitForNextTick(gametick);
var loops = 0;
while (ticker.ticks > gametick && loops < MAX_RENDER_SKIPS) {
updateGameState();
++gametick;
++loops;
}
render();
window.requestAnimationFrame(time => {});
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getClickPosition(evt) {
var rect = canvas.getBoundingClientRect(),
scaleX = canvas.width / rect.width,
scaleY = canvas.height / rect.height;
return vec2d(
toUnitLengths((evt.clientX - rect.left) * scaleX),
yToUnitLengths((evt.clientY - rect.top) * scaleY)
);
}
function storeClickPosition(event) {
if (launchAllowed()) {
var potentialClickPosition = getClickPosition(event);
for (piece of pieces) {
if (piece.info.colour == teamToMove && pieceContains(piece, potentialClickPosition)) {
targetPiece = piece;
clickPosition = potentialClickPosition;
break;
}
}
}
}
function launchAllowed() {
return !gameOver && !turnInProgress;
}
function storeCurrentMousePosition(event) {
currentMousePosition = getClickPosition(event);
}
function releaseClick(event) {
if (targetPiece !== null && clickPosition !== null && launchAllowed()) {
// touch end events do not have coordinates
// so use last saved position from movement
var drag = getDragVec(currentMousePosition);
var dragLength = vecLength(drag);
if (dragLength > MIN_DRAG_DISTANCE) {
// Direction.
var d = toUnitVec(drag);
var dragDistance = Math.min(MAX_DRAG_DISTANCE, dragLength);
var speed = (dragDistance / MAX_DRAG_DISTANCE) * piece.maxVelocity();
var velocityChange = scaleVec(speed, d);
targetPiece.velocity = addVec(targetPiece.velocity, velocityChange);
changeTeamToMove();
turnInProgress = true;
}
}
cancelClick(event);
}
function cancelClick(event) {
targetPiece = null;
clickPosition = null;
currentMousePosition = null;
}
function changeTeamToMove() {
if (teamToMove == PieceColour.White) {
teamToMove = PieceColour.Black;
} else {
teamToMove = PieceColour.White;
}
}
function getDragVec(newPosition) {
return subVec(clickPosition, newPosition);
}
function updateGameState() {
var stationaryPieces = 0;
var newCoords = [];
pieces.forEach(piece => {
if (isZeroVec(piece.velocity)) {
newCoords.push(piece.coords);
stationaryPieces += 1;
} else {
newCoords.push(
addVec(
piece.coords,
scaleVec(DT, piece.velocity)));
piece.velocity = applyFriction(piece.velocity, piece.mass());
}
});
if (stationaryPieces === pieces.length) {
turnInProgress = false;
}
// Check for collisions between the pieces at their
// new positions. If a piece is in a collision, freeze
// it in its current position.
// Warning: doesn't handle multi-piece collisions.
var shouldFreeze = Array(newCoords.length).fill(false);
for (var i = 0; i < newCoords.length; i += 1) {
for (var j = i+1; j < newCoords.length; j += 1) {
// Pieces collide! Freeze 'em. And update their
// velocities.
if (euclideanDistance(newCoords[i], newCoords[j]) < pieces[i].radius() + pieces[j].radius()) {
shouldFreeze[i] = true;
shouldFreeze[j] = true;
// The component of piece i's velocity in the direction
// of piece j is transferred to j. And vice versa.
exchangeVelocity(pieces[i], pieces[j]);
}
}
}
for (var i = 0; i < newCoords.length; i += 1) {
if (!shouldFreeze[i]) {
pieces[i].coords = newCoords[i];
}
}
var i = 0;
while (i < pieces.length) {
if (outsideBoardArea(pieces[i])) {
if (pieces[i].info.type === PieceType.King) {
kingDead[pieces[i].info.colour] = true;
gameOver = true;
}
pieces.splice(i, 1);
} else {
i += 1;
}
}
if (gameOver) {
if (kingDead[PieceColour.White]) {
winningTeam = PieceColour.Black;
} else {
winningTeam = PieceColour.White;
}
}
}
function applyFriction(velocity, mass) {
// Not incorporating mass just yet.
var newVelocity = subVec(velocity, scaleVec(DT*(1-FRICTION_COEFFICIENT), velocity));
// Just so pieces aren't stuck at a very very small velocity that
// will never go to zero.
if (vecLength(newVelocity) < VELOCITY_FLOOR) {
return vec2d(0, 0);
}
return newVelocity;
}
function exchangeVelocity(piece, otherPiece) {
var c1 = piece.coords;
var c2 = otherPiece.coords;
var m1 = piece.mass();
var m2 = otherPiece.mass();
// Velocity along the line from piece to otherPiece.
var d = direction(c1, c2);
// Projections onto the direction vector.
var p1 = projectOnto(piece.velocity, d);
var p2 = projectOnto(otherPiece.velocity, d);
// Finally, the velocity along that direction vector. Positive direction
// is wherever the direction vector is pointing.
var u1 = Math.sign(dotProduct(p1, d)) * vecLength(p1);
var u2 = Math.sign(dotProduct(p2, d)) * vecLength(p2);
// New velocities along the direction vector!
var output = computeOutputVelocities(u1, u2, m1, m2);
// First remove the old velocity along the direction vector, then
// add the new velocity along that direction.
piece.velocity = addVec(subVec(piece.velocity, p1), scaleVec(output.v1, d));
otherPiece.velocity = addVec(subVec(otherPiece.velocity, p2), scaleVec(output.v2, d));
}
function computeOutputVelocities(u1, u2, m1, m2) {
// See: https://en.wikipedia.org/wiki/Elastic_collision
// https://en.wikipedia.org/wiki/Inelastic_collision
const C = COLLISION_COEFFICIENT;
return {v1: (C*m2*(u2-u1) + m1*u1 + m2*u2)/(m1+m2),
v2: (C*m1*(u1-u2) + m1*u1 + m2*u2)/(m1+m2)};
}
function outsideBoardArea(piece) {
return piece.coords.x < BOARD_OFFSET
|| piece.coords.x > BOARD_OFFSET + BOARD_WIDTH
|| piece.coords.y < BOARD_OFFSET
|| piece.coords.y > BOARD_OFFSET + BOARD_WIDTH;
}
function render() {
const ratio = Math.ceil(window.devicePixelRatio);
const sideSize = Math.min(MAX_WORLD_SIZE_PIXELS, window.innerHeight, window.innerWidth);
// This can change as the user resizes the window.
canvas.width = sideSize * ratio;
canvas.height = sideSize * ratio;
canvas.style.width = `${sideSize}px`;
canvas.style.height = `${sideSize}px`;
pixelsPerUnitLength = canvas.width/WORLD_WIDTH;
unitLengthsPerPixel = WORLD_WIDTH/canvas.width;
drawBackground();
drawBoard();
pieces.forEach(drawPiece);
drawAimingCircles();
drawOverlay();
if (TOUCH_EVENT_DEBUG) {
drawCurrentMousePosition();
}
}
function drawOverlay() {
var bgColour, textColour, text;
if (gameOver) {
if (winningTeam === PieceColour.White) {
bgColour = "#FFFFFF";
textColour = "#000000";
text = "white wins!";
} else {
bgColour = "#000000";
textColour = "#FFFFFF";
text = "black wins!";
}
} else if (turnInProgress) {
bgColour = "#999999";
textColour = "#FFFFFF";
text = "turn in progress";
} else if (teamToMove === PieceColour.White) {
bgColour = "#FFFFFF";
textColour = "#000000";
text = "white to play";
} else {
bgColour = "#000000";
textColour = "#FFFFFF";
text = "black to play";
}
drawRectangle(WORLD_WIDTH-TURN_INDICATOR_WIDTH,
TURN_INDICATOR_HEIGHT,
TURN_INDICATOR_WIDTH,
TURN_INDICATOR_HEIGHT,
bgColour);
drawText(text,
WORLD_WIDTH-TURN_INDICATOR_WIDTH+TURN_INDICATOR_TEXT_OFFSET,
TURN_INDICATOR_TEXT_OFFSET,
TURN_INDICATOR_FONT_SIZE,
textColour);
}
function drawText(text, x, y, fontSize, colour) {
ctx.fillStyle = colour;
ctx.font = toPixels(fontSize) + "px monospace";
ctx.fillText(text, toPixels(x), yToPixels(y));
}
function toPixels(length) {
return Math.ceil(length * pixelsPerUnitLength);
}
function yToPixels(y) {
/* There needs to be a separate function for converting a y coordinate
to the matching pixel coordinate, since the positive y direction of
the canvas points down, while the "world" y axis points up. */
return canvas.height - 1 - toPixels(y)
}
function toUnitLengths(pixels) {
return unitLengthsPerPixel * pixels;
}
function yToUnitLengths(y) {
return toUnitLengths(canvas.height-1-y);
}
function drawBackground() {
ctx.fillStyle = BACKGROUND_COLOUR;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawBoard() {
fillSquares(WHITE_COLOUR, 1);
fillSquares(BLACK_COLOUR, 0);
}
function drawPiece(piece) {
const xPixels = toPixels(piece.coords.x);
const yPixels = yToPixels(piece.coords.y)
const topLeftCornerX = toPixels(piece.coords.x - PIECE_WIDTH/2);
const topLeftCornerY = yToPixels(piece.coords.y + PIECE_WIDTH/2);
ctx.drawImage(piece.getImage(), topLeftCornerX, topLeftCornerY,
toPixels(PIECE_WIDTH), toPixels(PIECE_WIDTH));
if (DEBUG_DRAW_COLLISION_CIRCLES) {
drawCircle(piece.coords.x, piece.coords.y, piece.radius(), COLLISION_CIRCLE_DEBUG_COLOUR, false);
} else if (targetPiece !== null) {
var colour;
if (targetPiece === piece) {
colour = COLLISION_CIRCLE_TARGET_COLOUR;
} else {
colour = COLLISION_CIRCLE_NONTARGET_COLOUR;
}
drawCircle(piece.coords.x, piece.coords.y, piece.radius(), colour, false);
}
}
function drawCircle(x, y, radius, colour, fill) {
ctx.beginPath();
ctx.arc(toPixels(x), yToPixels(y), toPixels(radius), 0, 2*Math.PI, false);
if (fill) {
ctx.fillStyle = colour;
ctx.fill();
} else {
ctx.lineWidth = 2;
ctx.strokeStyle = colour;
ctx.stroke();
}
}
function drawCross(x, y, radius, colour) {
ctx.beginPath();
ctx.moveTo(toPixels(x-radius), yToPixels(y-radius));
ctx.lineTo(toPixels(x+radius), yToPixels(y+radius));
ctx.moveTo(toPixels(x+radius), yToPixels(y-radius));
ctx.lineTo(toPixels(x-radius), yToPixels(y+radius));
ctx.lineWidth = 5;
ctx.strokeStyle = colour;
ctx.stroke();
}
function fillSquares(colour, initialX) {
// Considering bottom left square to have board coordinates (0, 0).
// Need to convert this to "world" coordinates.
var xIndex = initialX;
var yIndex = 0;
while (yIndex < BOARD_SQUARES) {
drawRectangle(boardIndexToCoord(xIndex) - SQUARE_WIDTH/2,
boardIndexToCoord(yIndex+1) - SQUARE_WIDTH/2,
SQUARE_WIDTH,
SQUARE_WIDTH,
colour);
xIndex += 2;
if (xIndex >= BOARD_SQUARES) {
if (xIndex == BOARD_SQUARES) {
xIndex = 1;
}
else {
xIndex = 0;
}
yIndex += 1;
}
}
}
function boardIndexToCoord(i) {
return BOARD_OFFSET + i*SQUARE_WIDTH + SQUARE_WIDTH/2;
}
function drawRectangle(x, y, width, height, colour) {
ctx.fillStyle = colour;
ctx.fillRect(toPixels(x), yToPixels(y), toPixels(width), toPixels(height));
}
function drawAimingCircles() {
if (targetPiece !== null && clickPosition !== null && currentMousePosition !== null) {
var drag = getDragVec(currentMousePosition);
var dragLength = vecLength(drag);
if (dragLength > MIN_DRAG_DISTANCE) {
var dragDir = toUnitVec(drag);
for (var i = 0; i < NUM_DRAG_CIRCLES; i += 1) {
var circleCoords = addVec(
targetPiece.coords,
scaleVec((i/(NUM_DRAG_CIRCLES-1))
* Math.min(MAX_DRAG_DISTANCE, dragLength),
dragDir));
drawCircle(circleCoords.x, circleCoords.y,
DRAG_CIRCLE_RADIUS, DRAG_CIRCLE_COLOUR, true);
}
} else if (dragLength > 0) {
var colour = COLLISION_CIRCLE_TARGET_COLOUR;
if (DEBUG_DRAW_COLLISION_CIRCLES) {
colour = COLLISION_CIRCLE_DEBUG_COLOUR;
}
drawCross(targetPiece.coords.x, targetPiece.coords.y, DRAG_CIRCLE_RADIUS, COLLISION_CIRCLE_TARGET_COLOUR);
}
}
}
function drawCurrentMousePosition() {
if (currentMousePosition !== null) {
drawCircle(currentMousePosition.x, currentMousePosition.y,
DRAG_CIRCLE_RADIUS, DRAG_CIRCLE_COLOUR, true);
}
}