-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
116 lines (98 loc) · 2.66 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
108
109
110
111
112
113
114
115
116
// Game state variable: Training 0, Game 1, Game over 2
let gameState = 0;
// Webcam input and regression model
let video;
let regressor;
let currentPrediction = 0;
// Buttons
let leftButton, centerButton, rightButton, trainButton;
// Game variables
let dodged;
let hiScore = 0;
let ship, meteors, stars;
function setup() {
const canvas = createCanvas(640, 480);
background(0);
noStroke(30);
select('#canvas').child(canvas);
// Camera
video = createCapture(VIDEO, () => {
console.log('Video ready');
});
video.hide();
// Load model
const mobileNet = ml5.featureExtractor('MobileNet', () => {
console.log('MobileNet ready');
});
regressor = mobileNet.regression(video, () => {
console.log('Model ready');
})
// Buttons
const buttonDiv = select('#buttons');
leftButton = createButton('Move left');
leftButton.parent(buttonDiv);
leftButton.mouseClicked(() => {
regressor.addImage(-1)
});
centerButton = createButton('No movement');
centerButton.parent(buttonDiv);
centerButton.mouseClicked(() => {
regressor.addImage(0)
});
rightButton = createButton('Move right');
rightButton.parent(buttonDiv);
rightButton.mouseClicked(() => {
regressor.addImage(1)
});
trainButton = createButton('Train');
select('#train').child(trainButton);
trainButton.mouseClicked(() => {
select('#info').html('Training - please wait');
regressor.train((loss) => {
if (loss === null) {
console.log("Training done");
setInterval(updatePrediction, 200);
changeState(1);
}
console.log(loss);
});
});
changeState(0);
}
function keyPressed() {
if (key === ' ' && gameState === 2) {
changeState(1);
}
}
function draw() {
if (gameState === 0) {
trainNetwork();
}
if (gameState === 1) {
gameLoop();
}
if (gameState === 2) {
gameOver();
}
}
function changeState(state) {
gameState = state;
if (state === 0) {
select('#info').html('Add images you wish to correspond to relevant movements. Press train when done.');
select('#buttons').show();
select('#train').show();
} else {
select('#buttons').hide();
select('#train').hide();
}
if (state === 1) {
dodged = 0;
ship = new Ship();
meteors = [new Meteor()];
makeStars();
select('#info').html('0 meteors dodged. High score: ' + hiScore);
}
if (state === 2) {
select('#info').html('Press space to restart');
}
}