Repository navigation
Expand file tree
/
Copy path05.js
More file actions
91 lines (74 loc) · 1.7 KB
/
Copy path05.js
File metadata and controls
91 lines (74 loc) · 1.7 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
/*
Lös problemen i koden. Exempel på körning visar följande:
Omgång 1
Tärningsvärden
5
4
1
2
3
-----
Antal tärningsvärden
1: 1
2: 1
3: 1
4: 1
5: 1
6: 0
[osv, fem omgångar]
*/
class Die {
constructor(id) {
this.value = this.getNewValue();
this.id = id;
}
throw() {
this.value = this.getNewValue();
}
getNewValue() {
return Math.floor((Math.random() * 6) + 1);
}
}
class Dice {
constructor(size) {
this.dice = [];
this.dice_values = new Array(7).fill(0);
for (let i = 0; i < size; i++) {
this.dice.push(new Die("dice_" + (i + 1)));
}
this.calculateDiceValues();
}
calculateDiceValues() {
this.dice_values = new Array(7).fill(0);
this.dice.map(current_value => {
this.dice_values[current_value.value]++;
})
}
show_dice() {
this.dice.map(current_value => {
console.log(current_value.value);
})
}
show_dice_values() {
for ( let i = 1; i < 7; i++ ) {
console.log(i + ': ' + this.dice_values[i]);
}
}
throw() {
for (let die of this.dice) {
die.throw();
}
this.calculateDiceValues();
}
}
let dice = new Dice(5);
for ( let i = 1; i <= 5; i++ ) {
dice.throw(); // Get new dice values
console.log('Omgång ' + i);
console.log('Tärningsvärden');
dice.show_dice(); // Show the values of the dice, like: 1, 1, 2, 4, 6
console.log('-----');
console.log('Antal tärningsvärden');
dice.show_dice_values(); // Show how many of each value we have, like: 1: 2, 2: 1, 3: 0, 4: 1, 5: 0, 6: 1
console.log('---------');
}