-
Notifications
You must be signed in to change notification settings - Fork 0
/
MMM-Snake.js
executable file
·348 lines (299 loc) · 10.5 KB
/
MMM-Snake.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
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
Module.register("MMM-Snake", {
getStyles: function() {
return [ this.file('public/snake.css') ];
},
getDom: function() {
if (!this.gameRunning) {
var startscreen = document.createElement("div");
var snake_text_div = document.createElement("div");
snake_text_div.style.fontFamily = "gameFont";
snake_text_div.style.fontSize = "200px";
snake_text_div.style.textAlign = "center";
snake_text_div.style.marginTop = "300px";
var snake_text = document.createTextNode("SNAKE");
var play_text_div = document.createElement("div");
play_text_div.style.fontFamily = "gameFont";
play_text_div.style.textAlign = "center";
play_text_div.style.fontSize = "100px";
play_text_div.style.marginTop = "90px";
var play_text = document.createTextNode("Press Play");
snake_text_div.appendChild(snake_text);
play_text_div.appendChild(play_text);
//startscreen.appendChild(img);
startscreen.appendChild(snake_text_div);
startscreen.appendChild(play_text_div);
return startscreen;
}
var canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
gameOver = () => {
drawText(
"Game over",
"150px gameFont",
canvas.width/2 - 330,
canvas.height/2
);
clearInterval(this.gameLoop);
this.gameover = true;
if (this.score > this.highscore) {
drawText(
"New Highscore!",
"100px gameFont",
canvas.width/2 - 330,
canvas.height/2 + 200
);
this.send({
type: "highscore",
value: this.score
});
this.highscore = this.score;
}
}
function drawText(text, font, x, y) {
ctx.beginPath();
ctx.font = font;
ctx.fillText(text, x, y);
ctx.closePath();
}
// move snake in next pos
this.snakeX += this.nextX;
this.snakeY += this.nextY;
// snake over game world?
if (this.snakeX < 0) {
this.snakeX = this.gridSizeX - 1;
}
if (this.snakeX > this.gridSizeX - 1) {
this.snakeX = 0;
}
if (this.snakeY < 0) {
this.snakeY = this.gridSizeY - 1;
}
if (this.snakeY > this.gridSizeY - 1) {
this.snakeY = 0;
}
//snake bite apple?
if (this.snakeX == this.appleX && this.snakeY == this.appleY) {
this.tailSize += 2;
this.score += 10;
this.appleX = Math.floor(Math.random() * this.gridSizeX);
this.appleY = Math.floor(Math.random() * this.gridSizeY);
}
//paint background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// paint snake
ctx.fillStyle = "white";
for (var i = 0; i < this.snakeTrail.length; i++) {
ctx.fillRect(
this.snakeTrail[i].x * this.tileSize,
this.snakeTrail[i].y * this.tileSize,
this.tileSize-5,
this.tileSize-5
);
//snake bites it's tail?
if (this.snakeTrail[i].x == this.snakeX && this.snakeTrail[i].y == this.snakeY) {
gameOver();
}
}
// paint score
ctx.beginPath();
ctx.font = "40px Arial";
ctx.fillStyle = "white";
ctx.fillText("Score: " + this.score, 10, canvas.height - 10);
ctx.fillText("Highscore: " + this.highscore, 490, canvas.height - 10);
ctx.closePath();
// paint apple
ctx.fillStyle = "white";
ctx.fillRect(this.appleX * this.tileSize, this.appleY * this.tileSize, this.tileSize-5, this.tileSize-5);
//set snake trail
this.snakeTrail.push({ x: this.snakeX, y: this.snakeY });
while (this.snakeTrail.length > this.tailSize) {
this.snakeTrail.shift();
}
return canvas;
},
start: function() {
Log.log("Starting module: ", this.name);
//setup signal server connection
this.SignalConnection = new WebSocket('ws://localhost:9090');
this.SignalConnection.onmessage = (message) => {
var data = JSON.parse(message.data);
switch(data.type) {
case "offer":
this.onOffer(data.offer, data.name);
break;
case "candidate":
this.onCandidate(data.candidate);
break;
case "highscore":
this.highscore = data.value;
break;
case "leave":
clearInterval(this.gameLoop);
this.start();
break;
default:
break;
}
};
this.SignalConnection.onopen = () => {
this.send({type: "gameready"});
};
this.SignalConnection.onerror = (err) => {
console.log("Got error", err);
};
//creating our RTCPeerConnection object
this.configuration = {};
this.RTCConnection = new RTCPeerConnection(this.configuration);
this.openDataChannel();
//setup ice handling
//when the browser finds an ice candidate we send it to another peer
this.RTCConnection.onicecandidate = (event) => {
if (event.candidate) {
this.send({
type: "candidate",
candidate: event.candidate
});
}
};
this.RTCConnection.ondatachannel = (event) => {
this.dataChannel = event.channel;
this.dataChannel.onerror = function (error) {
console.log("Error:", error);
};
};
// game world
this.tileSize = 30;
this.gridSizeX = Math.ceil(window.innerWidth / this.tileSize);
this.gridSizeY = Math.ceil(window.innerHeight / this.tileSize);
this.nextX = 1;
this.nextY = 0;
// snake
this.defaultTailSize = this.config.startsize;
this.tailSize = this.defaultTailSize;
this.snakeTrail = [];
this.snakeX = 10;
this.snakeY = 10;
// apple
this.appleX = Math.floor(Math.random() * this.gridSizeX);
this.appleY = Math.floor(Math.random() * this.gridSizeY);
// score
this.score = 0;
// render X times per second
this.x = this.config.speed;
this.gameRunning = false;
this.gameover = false;
this.sendSocketNotification('ready');
this.updateDom();
},
// only notifications from node_helper
socketNotificationReceived: function (notification, payload) {
switch(notification) {
case 'PLAY':
this.showGame();
break;
case 'STOP':
this.hideGame();
break;
default:
break;
}
},
showGame: function () {
var self = this;
self.show(1000, function () {
}, {lockString: self.identifier});
MM.getModules().exceptModule(self).enumerate(function (module) {
module.hide(1000, function() {
}, {lockString: self.identifier});
});
},
hideGame: function () {
var self = this;
this.hide(1000, function () {
}, {lockString: self.identifier});
MM.getModules().exceptModule(self).enumerate(function (module) {
module.show(1000, function () {
}, {lockString: self.identifier});
});
},
openDataChannel: function() {
var dataChannelOptions = {
reliable:false
};
this.dataChannel = this.RTCConnection.createDataChannel("myDataChannel", dataChannelOptions);
this.dataChannel.onerror = function (error) {
console.log("Error:", error);
};
this.dataChannel.onmessage = (event) => {
this.remoteCommand(event.data);
};
},
onOffer: async function (offer, name) {
await this.RTCConnection.setRemoteDescription(offer);
answer = await this.RTCConnection.createAnswer();
await this.RTCConnection.setLocalDescription(answer);
this.send({type: "answer", answer: answer});
this.gameRunning = true;
this.gameLoop = setInterval(() => {
this.updateDom();
}, 1000 / this.x);
},
//when we got ice candidate from another user
onCandidate: async function (candidate) {
await this.RTCConnection.addIceCandidate(candidate);
},
// Alias for sending messages in JSON format
send: function (message) {
message.name = "game";
this.SignalConnection.send(JSON.stringify(message));
},
resetGame: function() {
this.tailSize = this.defaultTailSize;
this.snakeTrail = [];
this.snakeX = 10;
this.snakeY = 10;
this.score = 0;
this.nextX = 1;
this.nextY = 0;
this.gameLoop = setInterval(() => {
this.updateDom();
}, 1000 / this.x);
},
// input webrtc
remoteCommand: function (command) {
if (this.gameover) {
this.gameover = false;
this.resetGame();
return;
}
switch (command) {
case "l": // left
if (this.nextX != 1) {
this.nextX = -1;
this.nextY = 0;
}
break;
case "u": // up
if (this.nextY != 1) {
this.nextX = 0;
this.nextY = -1;
}
break;
case "r": // right
if (this.nextX != -1) {
this.nextX = 1;
this.nextY = 0;
}
break;
case "d": // down
if (this.nextY != -1) {
this.nextX = 0;
this.nextY = 1;
}
break;
}
}
});