This repository was archived by the owner on Jan 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutil.js
More file actions
98 lines (78 loc) · 2.62 KB
/
util.js
File metadata and controls
98 lines (78 loc) · 2.62 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
/* jslint node: true */
'use strict';
var cfg = require('./config.json');
exports.validNick = function(nickname) {
var regex = /^\w*$/;
return regex.exec(nickname) !== null;
};
// determine mass from radius of circle
exports.massToRadius = function (mass) {
return 4 + Math.sqrt(mass) * 6;
};
// overwrite Math.log function
exports.log = (function () {
var log = Math.log;
return function (n, base) {
return log(n) / (base ? log(base) : 1);
};
})();
// get the Euclidean distance between the edges of two shapes
exports.getDistance = function (p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)) - p1.radius - p2.radius;
};
exports.randomInRange = function (from, to) {
return Math.floor(Math.random() * (to - from)) + from;
};
// generate a random position within the field of play
exports.randomPosition = function (radius) {
return {
x: exports.randomInRange(radius, cfg.gameWidth - radius),
y: exports.randomInRange(radius, cfg.gameHeight - radius)
};
};
exports.uniformPosition = function(points, radius) {
var bestCandidate, maxDistance = 0;
var numberOfCandidates = 10;
if (points.length === 0) {
return exports.randomPosition(radius);
}
// Generate the cadidates
for (var ci = 0; ci < numberOfCandidates; ci++) {
var minDistance = Infinity;
var candidate = exports.randomPosition(radius);
candidate.radius = radius;
for (var pi = 0; pi < points.length; pi++) {
var distance = exports.getDistance(candidate, points[pi]);
if (distance < minDistance) {
minDistance = distance;
}
}
if (minDistance > maxDistance) {
bestCandidate = candidate;
maxDistance = minDistance;
} else {
return exports.randomPosition(radius);
}
}
return bestCandidate;
};
exports.findIndex = function(arr, id) {
var len = arr.length;
while (len--) {
if (arr[len].id === id) {
return len;
}
}
return -1;
};
exports.randomColor = function() {
var color = '#' + ('00000' + (Math.random() * (1 << 24) | 0).toString(16)).slice(-6);
var c = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color);
var r = (parseInt(c[1], 16) - 32) > 0 ? (parseInt(c[1], 16) - 32) : 0;
var g = (parseInt(c[2], 16) - 32) > 0 ? (parseInt(c[2], 16) - 32) : 0;
var b = (parseInt(c[3], 16) - 32) > 0 ? (parseInt(c[3], 16) - 32) : 0;
return {
fill: color,
border: '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
};
};