-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.html
368 lines (320 loc) Β· 10.4 KB
/
index.html
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<html>
<header>
<meta charset="UTF-8">
<title>Snake face</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-164614767-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-164614767-1');
</script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core@1.7.3"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-converter@1.7.3"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/facemesh@0.0.3"></script>
<script>
function load_video() {
var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.srcObject = stream;
video.play();
});
}
}
var video;
var model;
async function init() {
video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
//video.src = window.URL.createObjectURL(stream);
video.srcObject = stream;
video.play();
}).catch(function() {
document.getElementById('warning').innerHTML = "Please check your permissions: access to camera is needed to estimate head direction to control the snake."
});
}
model = await facemesh.load();
}
var preds;
var left_cheek;
var right_cheek;
var lips_lower_inner;
var left_diff;
var right_diff;
var lr;
var ud;
var cross;
var init_lr;
var init_ud;
var direction = "centre";
var pred_interval;
async function main() {
const predictions = await model.estimateFaces(video);
return predictions
}
function cross_normalised(x, y){
cross = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1]
- x[1] * y[0] ];
norm = Math.sqrt((cross[0] ** 2) + (cross[1] ** 2) + (cross[2] ** 2));
return [cross[0] / norm, cross[1] / norm, cross[2] / norm]
}
function get_predictions() {
predictions = main()
predictions.then(function(val){
if (val.length > 0){
preds = val[0];
left_cheek = preds["annotations"]["leftCheek"][0]
right_cheek = preds["annotations"]["rightCheek"][0]
lips_lower_inner = [0, 0, 0]
lips_coords = preds["annotations"]["lipsLowerInner"]
for (i=0; i < lips_coords.length; i++) {
for (j=0; j < 3; j++){
lips_lower_inner[j] += lips_coords[i][j]
}
}
for (j=0; j < 3; j++){
lips_lower_inner[j] = lips_lower_inner[j] / lips_coords.length
}
left_diff = [];
right_diff = [];
for (i=0; i< 3; i++){
left_diff.push(left_cheek[i] - lips_lower_inner[i]);
right_diff.push(right_cheek[i] - lips_lower_inner[i]);
}
cross = cross_normalised(left_diff, right_diff)
console.log(cross);
lr = cross[0];
ud = cross[1];
if (init_lr === undefined){
init_lr = lr
}
if (init_ud === undefined){
init_ud = ud
}
tol = 0.2
if (lr - init_lr > tol){
direction = "left";
} else if (lr - init_lr < -tol) {
direction = "right";
} else if (ud - init_ud > tol) {
direction = "down";
} else if (ud - init_ud < -tol) {
direction = "up";
} else {
direction = "centre";
}
document.getElementById('direction').innerHTML = direction;
}
});
}
function start_pred() {
document.getElementById('direction').innerHTML = "Thinking...";
pred_interval = window.setInterval(() => get_predictions(), 1000/10)
}
function stop_pred() {
window.clearInterval(pred_interval)
}
</script>
<script>
class Board {
constructor(canvas){
this.canvas = canvas;
this.length = 1;
this.direction = "D";
this.positions = [[5,10]];
this.box_dim = 10;
this.grid_size = 20;
this.context = this.canvas.getContext("2d");
var random_pos_x = 4 + Math.floor(Math.random() * 12);
var random_pos_y = 4 + Math.floor(Math.random() * 12);
this.food = [random_pos_x, random_pos_y];
}
plot(obj) {
obj.context.fillStyle = "#FFFFFF";
obj.context.fillRect(0, 0,
obj.box_dim * obj.grid_size, obj.box_dim * obj.grid_size);
obj.context.fillStyle = "#000000";
obj.context.fillRect(0, 0, 1, obj.box_dim * obj.grid_size);
obj.context.fillRect(0, 0, obj.box_dim * obj.grid_size, 1);
obj.context.fillRect(0, obj.box_dim * obj.grid_size - 1,
obj.box_dim * obj.grid_size, 1);
obj.context.fillRect(obj.box_dim * obj.grid_size - 1, 0,
1, obj.box_dim * obj.grid_size);
obj.context.fillStyle = "#0000FF";
obj.context.fillRect(
obj.food[0] * obj.box_dim, obj.food[1] * obj.box_dim,
obj.box_dim, obj.box_dim
);
obj.context.fillStyle = "#FF0000";
var i;
var x;
var y;
for (i=0; i < obj.positions.length; i++){
x = obj.positions[i][0];
y = obj.positions[i][1];
obj.context.fillRect(
x * obj.box_dim, y * obj.box_dim,
obj.box_dim, obj.box_dim
);
}
document.getElementById('score').innerHTML = obj.positions.length
if (obj.positions.length > 9) {
document.getElementById('circle').style.visibility = "visible";
}
return;
}
new_food(obj){
var random_pos_x = 4 + Math.floor(Math.random() * 12);
var random_pos_y = 4 + Math.floor(Math.random() * 12);
while (obj.check_intersects(obj, [random_pos_x, random_pos_y])){
random_pos_x = Math.floor(Math.random() * obj.grid_size);
random_pos_y = Math.floor(Math.random() * obj.grid_size);
}
obj.food = [random_pos_x, random_pos_y];
}
check_intersects(obj, coords){
var x;
var y;
var i;
for (i=0; i < obj.positions.length; i++){
x = obj.positions[i][0];
y = obj.positions[i][1];
if ((x == coords[0]) && (y == coords[1])){
return Boolean(1);
}
}
return Boolean(0);
}
end_if_intersects(obj, new_head){
var x;
var y;
var i;
for (i=0; i < obj.positions.length; i++){
x = obj.positions[i][0];
y = obj.positions[i][1];
if ((x == new_head[0]) && (y == new_head[1]) ||
(new_head[0] < 0 || new_head[1] < 0 || new_head[0] >
obj.grid_size - 1 ||
new_head[1] > obj.grid_size - 1) ){
window.clearInterval(interval);
document.getElementById('status').innerHTML = "Game over! Your score:";
}
}
}
update_step(obj){
if (direction == 'down' && obj.direction != 'U'){
obj.direction = "D";
} else if (direction == 'up' && obj.direction != 'D'){
obj.direction = "U";
} else if (direction == 'left' && obj.direction != 'R'){
obj.direction = "L";
} else if (direction == 'right' && obj.direction != 'L'){
obj.direction = "R";
}
var head = obj.positions[obj.positions.length - 1];
var new_head;
if (obj.direction == "D"){
new_head = [head[0], head[1] + 1];
} else if (obj.direction == "U"){
new_head = [head[0], head[1] - 1];
} else if (obj.direction == "R"){
new_head = [head[0] + 1, head[1]];
} else if (obj.direction == "L"){
new_head = [head[0] - 1, head[1]];
}
obj.end_if_intersects(obj, new_head);
obj.positions.push(new_head);
if (new_head[0] != obj.food[0] | new_head[1] != obj.food[1]){
obj.positions.shift();
} else {
obj.new_food(obj);
}
obj.plot(obj);
return;
}
}
var interval;
function begin_game() {
if (pred_interval === undefined){
start_pred()
}
var c = document.getElementById("snake_board");
snake_game = new Board(c);
document.getElementById('status').innerHTML = "Score:";
document.getElementById('button').innerHTML = "Restart game";
var speed;
if (document.getElementById('r1').checked){
speed = 400
} else if (document.getElementById('r2').checked) {
speed = 300
} else if (document.getElementById('r3').checked) {
speed = 200
} else if (document.getElementById('r4').checked) {
speed = 150
}
if (interval){
window.clearInterval(interval);
}
interval = window.setInterval(
() => snake_game.update_step(snake_game), speed);
}
</script>
<style>
video {
transform: rotateY(180deg);
-webkit-transform:rotateY(180deg); /* Safari and Chrome */
-moz-transform:rotateY(180deg); /* Firefox */
}
.content {
margin: auto;
text-align:center;
}
button {
background-color: #555555;
border: none;
color: white;
padding: 10px 17px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
</style>
</header>
<div class="content">
<body onload="init()">
<h2> Play snake with your face! </h2>
<p> Look straight ahead, press "Begin game" and have a moment of patience
before the game begins.
<br>Best performance on desktop.</p>
<br>
<div id='warning'></div>
<canvas id="snake_board" width="200" height="200"></canvas>
<br>
<div id="status">Score: </div> <div id="score"></div>
<br>
Difficulty:
<input id="r1" type="radio" name="difficulty" value="easy" checked /> Easy
<input id="r2" type="radio" name="difficulty" value="medium" /> Medium
<input id="r3" type="radio" name="difficulty" value="hard" /> Hard
<!--<input id='difficulty' type="range" min="1" max="7" value="3"> -->
<br>
<br>
<button id="button" onclick=begin_game()>Begin game</button>
<br>
<br>
<video id="video" width="320" height="240" autoplay playsinline></video>
<div id="direction"> </div>
<!-- <button onclick="start_pred()"> Start! </button>
<button onclick="stop_pred()"> Stop </button> -->
<br>
<br>
<a href="https://github.com/paruby/snake-face">Source on GitHub</a>
<br>
<a href="http://paulrubenstein.co.uk/">http://paulrubenstein.co.uk/</a>
</body>
</div>
</html>