-
Notifications
You must be signed in to change notification settings - Fork 0
/
sketch.js
107 lines (85 loc) · 2.09 KB
/
sketch.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
let ball;
let leftPaddles;
let rightPaddles;
let generation;
const GA = new GeneticAlgorithm();
const POPULATION = 100;
function init() {
ball = new Ball();
leftPaddles = [];
rightPaddles = [];
for (let i = 0; i < POPULATION; i++) {
leftPaddles.push(new Paddle(true));
rightPaddles.push(new Paddle());
}
}
function gameover() {
const newLeftPaddles = [];
const newRightPaddles = [];
GA.calculateFitness();
for (let i = 0; i < POPULATION; i++) {
newLeftPaddles.push(GA.selectOne(true));
newRightPaddles.push(GA.selectOne());
}
for (let i = 0; i < POPULATION; i++) {
leftPaddles[i].brain.clear();
rightPaddles[i].brain.clear();
}
ball = new Ball();
leftPaddles = newLeftPaddles;
rightPaddles = newRightPaddles;
generation++;
loop();
}
function setup() {
createCanvas(600, 400);
tf.setBackend('cpu');
generation = 1;
init();
}
function draw() {
background(0);
// const ballDir = {x: random()
let activePlayersLeft = POPULATION;
let activePlayersRight = POPULATION;
for (let i = 0; i < POPULATION; i++) {
const leftPaddle = leftPaddles[i];
const rightPaddle = rightPaddles[i];
if (!leftPaddle.isGameOver) {
if (leftPaddle.pos.x === ball.pos.x) {
const isHit = leftPaddle.hit(ball);
if (isHit) {
leftPaddle.score += 1;
if (ball.dir.x === -1) ball.changeDir();
} else {
leftPaddle.isGameOver = true;
}
}
leftPaddle.update(ball);
leftPaddle.show();
} else {
activePlayersLeft--;
}
if (!rightPaddle.isGameOver) {
if (rightPaddle.pos.x === ball.pos.x) {
const isHit = rightPaddle.hit(ball);
if (isHit) {
rightPaddle.score += 1;
if (ball.dir.x === 1) ball.changeDir();
} else {
rightPaddle.isGameOver = true;
}
}
rightPaddle.update(ball);
rightPaddle.show();
} else {
activePlayersRight--;
}
if (activePlayersLeft === 0 || activePlayersRight === 0) {
noLoop();
gameover();
}
}
ball.update();
ball.show();
}