-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
74 lines (63 loc) · 2.05 KB
/
main.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
const defaultAttributeScores = [15, 14, 13, 12, 10, 8];
class Player {
constructor(characterName = 'Naruto'){
this.name = characterName;
this.attributes = {
strength: 0,
dexterity: 0,
constitution: 0,
intelligence: 0,
wisdom: 0,
charisma: 0
};
let shuffledResult = shuffleArray(defaultAttributeScores);
for (const [key, value] of Object.entries(this.attributes)) {
let attributeValue = shuffledResult.pop();
this.attributes[key] = attributeValue;
}
}
rollAttributes() {
for (const key in this.attributes) {
let results = diceRoller(4, 6);
results.sort(function(a, b){return a - b}); //numeric sort with compare function
results.shift(); //remove lowest die roll
let sum = sumArrayElements(results); //sum the rolls
this.attributes[key] = sum;
}
}
printPlayer() {
console.log(`NAME: ${this.name}`);
for (const [key, value] of Object.entries(this.attributes)) {
console.log(`${key.slice(0, 3).toUpperCase()}: ${value}`);
}
}
}
const player01 = new Player();
player01.printPlayer();
const player02 = new Player('Son Goku');
player02.rollAttributes();
player02.printPlayer();
function shuffleArray(targetArray) {
let shuffled = Array.from(targetArray); // Array.from(targetArray) is there so that the original variable targetArray is not edited.
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
return shuffled;
}
function diceRoller(times, sides) {
let results = [];
for (let i = 0; i < times; i++){
results.push(Math.floor(Math.random() * sides + 1));
}
return results;
}
function sumArrayElements(array){
let sum = 0;
for (let i = 0; i < array.length; i++){
sum += array[i];
}
return sum;
}