-
Notifications
You must be signed in to change notification settings - Fork 0
/
MathsMania.js.save
557 lines (394 loc) · 19.5 KB
/
MathsMania.js.save
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
var myGameInstances = []; // Stores the game instances so that the state of different game lobbies is not lost
// Raw (game logic only) Class
class Game {
// Setting up instance variables that store game state...
constructor(roomId, io) {
this.MAX = 2; // Max number of players for game, this is specific for the game - ie. for pong this would be 2.
this.endScore = 8;
this.endTime = null; //Note: will add a countdown timer to games, perhaps decide on max time allowed for any game
this.roomId = roomId;
this.num = 0;
this.io = io;
this.Users = []; // --> Stores the games user's state including their username and score.
this.gUsers = []; // --> Stores the socket objects and their respective names, which is used when removing a user from the game, on disconnect.
this.tester = null;
// Player position variables
this.player_1 = 0;
this.player_2 = 0;
// Ball position variables
this.ball_x = 300; // Initially set to horizontal center
this.ball_y = 200; // Initially set to vertical center
// Ball velocity variables
this.vel_x = 7// Initially set to one
this.vel_y = 7; // Initially set to one
}
showUsers() {
console.log("Number of players in the lobby: " + this.gUsers.length);
if (this.gUsers.length == 2) {
// Sets the maximum number of users needed to start the game, this should really be dynamic instead of hardcoded (user choice?)
//this.startGame();
// When number of users required has been met, the game is started and game logic starts execution.z
this.io.sockets.in(this.roomId).emit("gameStarted");
this.dummyStart();
console.log("game should start...");
}
}
addUsertoGame(socketId, name) { // When a new user has connected to a particular lobby, we add thre socketId and associcated name for reference in
// various methods.
this.Users.push(socketId);
this.Users.push(name);
this.num = this.num + 1;
this.getSide(socketId, this.num);
console.log("your side: " + this.num );
};
InformUserOfLobby(socket) {
socket.emit("test", this.roomId);
}
addUser(playerName) { // A new users state is strored in a user variable which is then added to the list of users.
var user = {
name: playerName,
score: 0
}
this.gUsers.push(user);
this.updateUsers();
}
// Method to remove a user from the list of users when they have disconnnected
removeUser(user) {
for (var i = 0; i < this.gUsers.length; i++) {
// Iterate through list of users until correct user is identified...
if (user == this.gUsers[i].name) {
// Removing user entry from list of users...
this.gUsers.splice(i, 1);
console.log("User: " + user + " has left the game");
this.updateUsers();
console.log("");
console.log("PLAYER " + user + " HAS LEFT THE GAME...");
console.log("");
};
};
if (this.gUsers.length == 1) {
this.endGame();
}
}
updateUsers() {
// Broadcast all the user names of the users that are in the game to all of the users...
console.log("Users present in the game: " + this.gUsers.length);
//this.io.sockets.in(this.roomId).emit("users", this.gUsers);
};
// This will cause the client loading screen to be hidden and the first question of the game generated by the updateQuestion() method
startGame() {
//this.io.sockets.in(this.roomId).emit("gameStarted", true);
//this.updateQuestion(); This needs to call dummyStart()
}
/*This method is triggered in the case when there is only one user left in the game and so they win by default.
IMPORTANT: This method will need to redirect the user back to the game page when the game ends so that they are not just stuck on the game
page. In addition when the game is over the game instance needs it summary data written to the SQL database and it will then need to be removed
from the myGameInstances array.*/
endGame() {
console.log("endGame() is called");
var destination = '/home.html';
clearInterval(this.tester);
this.io.sockets.in(this.roomId).emit("gameEnded",{"destination": destination, "users": this.gUsers});
}
getSide(socket, num){
socket.emit("playerNumber", num);
socket.emit("here", "ok");
}
updateScores(increment, player){
player.score = player.score + increment; // Calculating new score
if(player.score == this.endScore){ // Check if winning score has been achieved by player.
this.endGame();
}
this.io.sockets.in(this.roomId).emit("scoreUpdate", {"player": player.name, "score": player.score});
console.log("score increase triggered");
}
collideWithPaddle(){
if((this.player_1) < this.ball_y && (this.player_1 + 100) > this.ball_y && (this.ball_x <= 20)){
this.vel_x = -(this.vel_x * 1.05); // Ball gets faster after each ralley to prevent never ending games.
console.log("paddle 1 new vel " + this.vel_x);
this.vel_y = this.vel_y + Math.floor(Math.random() * 2 + 1); // Randomness introduced for rebound velocity.
}
else if((this.player_2) < this.ball_y && (this.player_2 + 100) > this.ball_y && (this.ball_x >= (1149-30))){
this.vel_x = -(this.vel_x * 1.05);
this.vel_y = this.vel_y + Math.floor(Math.random() * 2 + 1);
console.log("paddle 2 new vel " + this.vel_x);
}
}
setPlayer(number, position){
console.log("---" + number + "-----")
console.log("NO!");
if(number == 1){
this.player_1 = position;
console.log("yes" + "" + number + "" + position);
}
else if(number == 2){
this.player_2 = position;
console.log("yes" + "" + number + "" + position);
}
}
collideWithWall(){
if( this.ball_y >= 763 || this.ball_y <= 0){
this.vel_y = - this.vel_y
}
else if(this.ball_x >= 1149 || this.ball_x <= 0){
// When there is a collision with a wall, update score.
if(this.ball_x >= 1149){
this.ball_x = (1149/2); // Reset to horizontal center
this.ball_y = (763/2); // Reset set to vertical center
this.vel_x = 7; // Reset x-axis velocity the the original
this.vel_y = 7; // Reset y-axis velocity the the original
//this.gUsers[0].score+=1;
console.log("score for player 1: " + this.gUsers[0])
this.updateScores(1, this.gUsers[0]);
} // If ball hits right wall, award player 1 a point
if(this.ball_x <= 0){
this.ball_x = (1149/2); // Reset to horizontal center
this.ball_y = (763/2); // Reset set to vertical center
this.vel_x = 7; // Reset x-axis velocity the the original
this.vel_y = 7; // Reset y-axis velocity the the original
//this.gUsers[1].score+=1;
console.log("score for player 2: " + this.gUsers[1]);
this.updateScores(1, this.gUsers[1]);
} // If ball hits left wall, award player 2 a point
this.vel_x = -this.vel_x;
}
}
dummyStart(){
this.io.sockets.in(this.roomId).emit('playerJoin', {"users": this.gUsers}); // set up scores
var self = this;
this.tester = setInterval(function(){
self.collideWithWall();
self.collideWithPaddle();
console.log("paddle 1-2 new vel " + self.vel_x);
self.ball_x = self.ball_x + self.vel_x;
self.ball_y = self.ball_y + self.vel_y;
//self.io.sockets.emit("drawBall", {"x": self.ball_x, "y": self.ball_y, "y1": self.player_1, "y2": self.player_2});
self.io.sockets.in(self.roomId).emit("drawBall", {"x": self.ball_x, "y": self.ball_y, "y1": self.player_1, "y2": self.player_2});
console.log(self.player_1 + "||" + self.player_2);
},
(1000/30)); // FPS set to 30
}
}
/////////// index.js -> The (eventual)framework ///////////
/*TODO:
Make a leaderboard
Clean up code considerably! -- /// CURRENT TASK /// --> Due: 25th Febuary
Prevent users from joining when the game has begun -- for now an error message or redirect is adequate
Have dummy list of current lobbies that have spaces - 'could be in a view lobbies section'
Writing code to database
Author: Benedict Uttley
Last Revision: 13/02/2018
Version 1.1
*/
/* The code contained in index.js sets up a web server using the Node js run time environment. I have created a set of functions that allow simple
client to server communication. Although the functions actual data will change (perhaps only slightly) from game to game, the structure can be used
as the foundation of most of the games we will make.*/
/* For this simple maths game and games in the future, a number of tools have been used in addition to the basic Node install. Firstly to make the
creation of the web server easier, the express framework has been used which just makes the same functionality possible in fewer lines and it makes
tasks like serving the html pages to the users much easier. Secondly, what has made this multiplayer game creation not only possible but fast to
create is the use of Socket.io which is a javascript library that allows for bi-directional communication between the users web browser and the
server but also makes this communication real time, which is what gives it an interactive feel. It basically manages socket connections meaning
when a new user connects (at the moment just to localhost:8080 on my computer) they have a socket created for them. This socket is like a
communication channel between them and the server. This means that you can essentially send messages from server to client (or server to all
clients, a broadcast) and from client to server.*/
/* When you have installed node you can install express and socket.io from the command line using the node package manager(npm). For example to
install socket.io you would type npm install socket.io and it should then be installed.*/
//////////////////////////////////////////////////////////// CODE START //////////////////////////////////////////////////////////////////////////
var myGameInstances = []; // Stores the game instances so that the state of different game lobbies is not lost
/////////// Application Setup ///////////
// We use express to set up the application
var express = require('express');
var app = express();
// We create the http server
var server = require('http').createServer(app);
// We use sockets for our communication and the sockets will communicate on the server created above
var io = require('socket.io').listen(server);
var bodyParser = require('body-parser')
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
// This module is needed for this application as the game creates random usernames, the moniker module is used to generate these names
var Moniker = require('moniker');
// Here we declare the file we want to send to the client when a new user connects to the server, in this example it is page.HTML
var game_Name = "";
var user_name = "";
var game_type = "";
var lobby_input = "";
//app.use(express.static(__dirname + '/public'));
//app.use(express.static(__dirname + '/Maths_Mania'));
app.use(express.static(__dirname + '/public'));
app.post('/', function(req, res) {
// POST data to decide type of game and lobby to join...
console.log("username of user " + req.body.user.name);
user_name = req.body.user.name;
console.log("Type of lobby to join " + req.body.lobby.type);
game_type = req.body.lobby.type;
if (game_type == 'Private') {
lobby_input = req.body.lobby.name;
} else {
lobby_input = null;
}
// console.log("Lobby to join " + req.body.p_or_r.lobby)
// POST data to decide type of game and lobby to join...
var url = require("url");
var params = url.parse(req.url,true).query;
console.log(params.game_Name);
game_Name = params.game_Name;
res.sendFile(__dirname + '/index.html');
});
// We will run the web server on port 8080 which is the standard for a web server application
server.listen(8081);
/////////// Application Setup ///////////
/////////// Listeners (required regardless of game played) ///////////
/* This is the first use of socket.io in this application. io.sockets.on() is used when you are referring to all connections, so all the current
players in the maths game. Here we are saying that when a new connection is established (which is detected automatically) then a socket is
created for that connection and this socket is unique to that client. */
//var num = 0;
var name; // Holds the username of connection
var game; // Holds the game instance
//pong = new Game("",io);
io.sockets.on('connection', function(socket) {
socket.username = user_name;
name = user_name;
console.log(user_name);
//num++;
//console.log(num); // For now, let num be ~ username
//pong.getSide(socket, num);
//pong.addUser(num);
//if(num == 2){
//pong.dummyStart();
//}
//const Game = require('./gameServer_Side.js');
// Print out a log indicating there has been a new connection, just useful for testing
console.log("Successful Connection!");
// socket.on('login', function(playerName) {
// name = playerName;
// socket.username = user_name;
// console.log("player name is: " + user_name);
// });
// --- TODO CURRENTLY BEING WORKED ON ---
var assigned = false;
// socket.on('room', function(room) {
if(game_type == "Random" && myGameInstances.length > 0) {
// Search for best game to join.
let current_contender = null;
for(var i = 1; i<myGameInstances.length; i = i+2) {
if((current_contender == null) && (myGameInstances[i].gUsers.length < myGameInstances[i].MAX)) {
current_contender = myGameInstances[i];
console.log('ppp');
console.log("Game Object: " + current_contender);
}
if( (myGameInstances[i].gUsers.length > current_contender.gUsers.length) &&
(current_contender.gUsers.length < current_contender.MAX)) { // Store current 'most populated' game, as this is the one to be added to,
// as long as the max allowed for that game is not exceeded.
current_contender = myGameInstances[i];
}
}
// TODO: Assign to random game -- Need to implement 'balanced' game assigning.
console.log("Looking for random lobby to join. New or random.");
// Fetch the room of the game to be joined and set the room variable to it...
room = current_contender.roomId;
console.log("roomId: " + current_contender.roomId);
if(room == null) { // If there are no free rooms then make a new roomId, which is a randomly generated ID.
'_' + Math.random().toString(36).substr(2, 9);
}
}
} else if(game_type == "Random" && myGameInstances.length == 0){
room = '_' + Math.random().toString(36).substr(2, 9); // If this is the only game, then generate a ramdom new roomId.
}
// --- TODO CURRENTLY BEING WORKED ON ---
else if (game_type == "private") {
room = lobby_input;
console.log("Joining a private game lobby, which has a specific name.");
}
console.log("newroom: " + room);
if (io.sockets.adapter.rooms[room]) { // Check if room the user wants to join already exists...
console.log("room being checked for: " + room )
socket.join(room); // joining the new room
socket.room = room;
// search for existing game object...
for (var i = 0; i < myGameInstances.length; i++) {
// joining the existing room;
if (myGameInstances[i] == room) {
// Fetch the respective game instance...
game = myGameInstances[i + 1];
console.log("existing game");
}
}
// should really store game data in Json or some other more readable format rather than a object array...
// If the user wants to join a new lobby...
} else {
console.log("room being checked for: " + room )
socket.join(room); // joining the new room
socket.room = room;
game = new Game(socket.room, io);
myGameInstances.push(room);
myGameInstances.push(game);
console.log("new Game");
};
//game.getSide(socket, num);
socket.emit("details", {'username':user_name,'room':room});
console.log("£££" + user_name);
io.sockets.in(room).emit('message', 'User ' + socket.username + ' has joined the lobby');
game.addUsertoGame(socket,name);
game.addUser(name);
socket.emit("yourGame", game.roomId);
game.showUsers();
//io.sockets.in(room).emit('playerJoin', {"users": game.gUsers});
/////////// Listeners (required regardless of game played) ///////////
/////////// Listeners (chat specific) ///////////
socket.on('clientMessage', function(data){
io.sockets.in(room).emit('message', socket.username + ' ~ ' + data );
});
socket.on("lobbyOver", function(){
for(var i = 0; i< myGameInstances.length; i+=2){
if (myGameInstances[i] == socket.room) {
gamea = myGameInstances[i + 1];
gamea.endGame();
}
}
});
//var listeners = require('./gameListeners.js')(socket, game, io, myGameInstances);
//console.log("Number of lobbies for the game: " + (myGameInstances.length / 2));
socket.on("mousemove", function(data){
console.log("mouse move triggered..." + data.number);
var gamea;
for(var i = 0; i< myGameInstances.length; i+=2){
if (myGameInstances[i] == data.theGame) {
console.log("mouse move triggered... again" + data.number);
gamea = myGameInstances[i + 1];
gamea.setPlayer(data.number, data.position);
}
}
});
socket.on('disconnect', function() {
console.log("disconnection detected...");
for(var i = 0; i< myGameInstances.length; i+=2){
console.log("-------------------");
console.log(myGameInstances[i]);
if (myGameInstances[i] == socket.room) {
gamea = myGameInstances[i + 1];
for (var i = 0; i < gamea.Users.length; i += 2) { // Search for player name to remove
if (gamea.Users[i] == socket) { //pb
var playerToRemove = gamea.Users[i + 1];
gamea.removeUser(playerToRemove);
io.sockets.in(gamea.roomId).emit('message', 'User ' + socket.username + ' has left the lobby');
}
}
if(gamea.gUsers.length == 0) {
console.log("Lobby empty, closing game...");
myGameInstances = myGameInstances.splice(i, 1); // Remove game name from array of games...
myGameInstances = myGameInstances.splice(i,1); // Elements shift down by one, remove game object...
}
}
console.log("Current number of games: " + myGameInstances.length/2);
}
});
// });
});
/* Just a quick overview of what has happened in the above core functions:
The addUser function creates a new user with a unique random name and appends it to the array called users.
The removeUser function removes a given user form the array called users.
The updateUsers function sends a string containing a list of all the current users in the game including the users name and score.*/