-
Notifications
You must be signed in to change notification settings - Fork 8
/
pong.js
619 lines (541 loc) · 18.8 KB
/
pong.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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
/*@author Kyle Wenholz, Joey Lange, David Eva, Kyle Brooks,
* Contains user interface information, as well as communication to the
* server and the wiimote.
*/
//========================================================================
//========================================================================
//===========================GLOBAL VARIABLES=============================
//========================================================================
//========================================================================
////////////////////
/// VISUALS ///
////////////////////
//The canvas object handle.
var context;
//Standard 100x100 game space.
var gameX = 100;
var gameY = 100;
//Defining the screen modifiers.
var screenModifierX;
var screenModifierY;
//Positions of rightPad and leftPad
var rightPad = gameY/2;
var leftPad = gameY/2;
//Size of paddles.
var paddleWidth = 3;
var paddleHeight = gameY/5;
//Step motion size.
var motionStep = 10;
//Ball position.
var xBall = gameX/2;
var yBall = gameY/2;
//Size of the ball
var ballR = gameX/20;
//Current score
var scoreLeft = 0;
var scoreRight = 0;
//Which paddle we are
var paddleID;
//Player names
var playerOneName = "P1";
var playerTwoName = "P2";
////////////////////
/// UTILITIES ///
////////////////////
var socket;
var roomList = [];
// Various flags
var fieldStyleFlag;
var wiiFlag = false;
var iOSWiiFlag = false;
var authLooping = false;
var gameOn = false;
//Local accel.
var watchID;
var updateFrequencyCounter = 0;
//Username and password.
var name;
var pass;
//========================================================================
//========================================================================
//=============================DRAWING CODE===============================
//========================================================================
//========================================================================
/**
* Starts the pong game & grabs the canvas so that we can modify it in JS.
*/
function initCanvas(){
displaySelection(fieldStyleFlag);
context = document.getElementById("gameCanvas").getContext("2d");
context.canvas.width = window.innerWidth*(0.90);
context.canvas.height = window.innerHeight*(0.75);
screenModifierX = context.canvas.width/100;
screenModifierY = context.canvas.height/100;
var size = context.canvas.width;
size = Math.floor(size*.04+.92);
var font = String(size);
context.fillStyle = "#ddd";
var text = size+"px Silkscreen-Expanded";
context.font = text;
context.textBaseline = "top";
};
/**
* Serves as a filter for various display options. Game canvases,
* buttons, input options, and even game end screens are initialized here.
*@param {selection} a string representing the desired display: gameCanvas,
* gameCanvasWithButtons, inputMethodSelection, selectRoom, newRoom, or gameEnd
*@param {options} any of various options that go with {selection}
*/
function displaySelection(selection, options){
var view = document.getElementById("view");
if(selection == "gameCanvas"){
//A game canvas with no buttons
view.innerHTML = "<canvas id=\"gameCanvas\" height=\"100\" "+
"width=\"100\"></canvas><br />";
gameOn = true;
}if(selection == "gameCanvasWithButtons"){
//A game canvas with arrow buttons, very nice
view.innerHTML = "<canvas id=\"gameCanvas\" height=\"100\" "+
"width=\"100\"></canvas><br /><a href=\"#\" "+
"<a href=\"#\" onClick=\"changePaddlePosition('W');\"><img "+
"src=\"graphics/uparrow-green.png\" style=\"position: absolute; "+
"bottom: 8%; left: 5%;\"></a>"+
"<a href=\"#\" onClick=\"changePaddlePosition('S');\"><img "+
"src=\"graphics/downarrow-green.png\" style=\"position: "+
"absolute; bottom: 8%; right: 5%;\"></a>\"";
}else if(selection == "inputMethodSelection"){
//A screen for selecting input methods
view.innerHTML = detectViableInputMethods() +
"<p style=\"color:white\" align=\"center\">Disclaimer: At the "+
"time of this writing, the gods of computing have not made it "+
"possible to automagically detect your device. So, please "+
"don\'t select an input method your device doesn\'t support. "+
"Refer to the VirPong website for more information.</p>";
}else if(selection == "selectRoom"){
if(roomList.length == 0){
displaySelection("newRoom");
return;
}
var roomButtons = "";
for(i=0; i<roomList.length; i=i+1){
roomButtons=roomButtons+"<a class=\"button\" onclick=\"joinRoom(\'"+
roomList[i]+"\',\'player\');\">"+roomList[i]+"</a>";
}
//A screen for selecting a room, new or existing
view.innerHTML = "<div id=\"mainWrapper\"><h1 align=\"center\">Do "+
"you want to create a new room?</h1><a align=\"center\" "+
"class=\"button\" onclick=\"displaySelection('newRoom', "+
"'bleh');\" href=\"#\">New Room</a>"+roomButtons+"</div>";
}else if(selection == "newRoom"){
view.innerHTML = " <div id=\"mainWrapper\"><h1 align=\"center\">"+
"What do you want to name your game room?</h1><!-- Room -->"+
"<input type=\"text\" value=\"\" name=\"userName\" id=\"roomName\" "+
"onFocus=\"this.value=\"\"\" autocapitalize=\"off\" "+
"autocorrect=\"off\" /><!-- Submit --><input type=\"button\" "+
"value=\"Select Room\" id=\"selectRoom\" onClick=\"handleNewRoom()"+
"\" /><br /></div>";
}else if(selection == "gameEnd"){
//A screen for the game finishing. Also takes care of some cleanup.
view.innerHTML = "<div id=\"mainWrapper\"><h1>The game is over. You "+
options+".</h1><a align=\"center\" class=\"button\" "+
"onclick=\"displaySelection('selectRoom');\" href=\"#\">Play again.</a>"+
"<a align=\"center\" class=\"button\" onclick=\"\" href="+
"\"index.html\">Return to the main screen.</a>";
if(wiiFlag){
alert("Prepare to disconnect your Wii Remote. (Select "+
"your primary keyboard.");
window.KeySelect.showKeyBoards();
}
}
};
/**
* Draws the game state.
*/
function draw(){
context.clearRect(0,0, Math.floor(gameX*screenModifierX),
Math.floor(gameY*screenModifierY)); //clear the frame
drawPaddles();
//alert("clearRect2");
drawBall();
//alert("drawn");
drawScore();
drawHalfCourt();
};
/*
* Draws a half court line.
*/
function drawHalfCourt() {
var width = 3;
var height = 3;
var topY = 1.5*height;
while(topY < gameY*screenModifierY - 1.5*height) {
drawRect(gameX*screenModifierX/2 - .5*width, topY, width, height,
"rgb(240,240,240)");
topY = topY + 2*height;
}
};
/**
* Draws paddles based on the field positions.
*/
function drawPaddles() {
drawRect(0,
Math.floor(leftPad*screenModifierY),
Math.floor(paddleWidth*screenModifierX),
Math.floor(paddleHeight*screenModifierY),
"rgb(240,240,240)");//xpos, ypos, width, height
drawRect(Math.floor((gameX-paddleWidth)*screenModifierX),
Math.floor(rightPad*screenModifierY),
Math.floor(paddleWidth*screenModifierX),
Math.floor(paddleHeight*screenModifierY),
"rgb(240,240,240)");
};
/**
* Draws rectangles on the canvas.
* @param a top-left x-position
* @param b top-left y-position
* @param c bottom-right x-position
* @param d bottom-right y-position
* @param col color of the paddle
*/
function drawRect(a, b, c, d, col){
context.save();
context.beginPath();
context.fillStyle = col; //color to fill shape in with
context.rect(a,b,c,d); //draws rect with top left corner a,b
context.closePath();
context.fill();
context.restore();
};
/**
* Draws the ball at current position.
*/
function drawBall(){
//Draw square "ball"
var tlX = (xBall*screenModifierX)-10;
var tlY = (yBall*screenModifierY)-10;
var brX = ballR*3;
var brY = ballR*3;
drawRect(tlX, tlY, brX, brY, "rgb(240,240,240)");
};
/**
* Draws current score on the canvas.
*/
function drawScore(){
var score;
score = String(scoreLeft);
context.fillText(playerOneName+": " + score, gameX*screenModifierX/5, 10);
score = String(scoreRight);
context.fillText(playerTwoName+": "+ score, 2.5*gameX*screenModifierX/4,10);
};
//========================================================================
//========================================================================
//==============================INPUT CODE================================
//========================================================================
//========================================================================
/**
* Initializes the appropriate input methods for playing a game.
* @param {method} a string for the desired input method.
* "K" = Keyboard
* "T" = Touchscreen
* "W" = Wii Remote
* "A" = Local Accelerometer
**/
function handleInputSelect(method){
if(method == "keys"){
fieldStyleFlag = "gameCanvas";
document.onkeydown = movePaddle;
}else if(method == "touchscreen"){
fieldStyleFlag = "gameCanvasWithButtons"
}else if(method == "wii"){
//display the select
fieldStyleFlag = "gameCanvas";
alert("Select VirPongIME in the next popup.");
window.KeySelect.showKeyBoards();
document.onkeydown = movePaddle;
wiiFlag = true;
}else if(method == "appleWii") {
fieldStyleFlag = "gameCanvas";
iOSWiiFlag = true;
setupLocalAccelerometer();
}else if(method == "localAccel"){
setupLocalAccelerometer();
fieldStyleFlag = "gameCanvas";
}
connectToServer();
};
/**
* Receive the input and send it to changePaddlePosition(), which actually
* changes the paddle position.
* @param {e} the event passed by the keypress.
*/
function movePaddle(e) {
var evntObj = (document.all)?event.keyCode:e.keyCode;
var actualKey = String.fromCharCode(evntObj);
changePaddlePosition(actualKey);
};
/**
* Change the value of leftPaddle or rightPaddle so that it will draw in
* the correct place. This method is for a string input. "W" is down and
* "S" is up.
* @param {actualKey} The string value of the key pressed.
*/
function changePaddlePosition(actualKey) {
if(paddleID == 0){
if(actualKey == "W"){ //check which key was pressed
if(leftPad > 0){
//do nothing if it would move paddle out of frame
leftPad = leftPad - motionStep;
}
}else if(actualKey == "S"){
if(leftPad < (gameY - paddleHeight)){
leftPad = leftPad + motionStep;
}
}updatePaddleToServer(leftPad);
}else{
if(actualKey == "W"){ //check which key was pressed
if(rightPad > 0){
// do nothing if it would move paddle out of frame
rightPad = rightPad - motionStep;
}
}if(actualKey == "S"){
if(rightPad < (gameY - paddleHeight)){
rightPad = rightPad + motionStep;
}
}updatePaddleToServer(rightPad);
}
};
function updateWiiPosition() {
wiiGetPosition();
updatePaddleToServer(storedPosition);
}
function detectViableInputMethods() {
/* Figure out what platform we"re running on, return the correct
choices for input selection. */
var userAgent = navigator.userAgent;
// var thePlatform;
var theReturn = "<div id=\"mainWrapper\"><h1 align=\"center\">"+
"Select your input method.</h1>";
if((userAgent.indexOf("iPad")!=-1)||(userAgent.indexOf("iPhone")!=-1)
||(userAgent.indexOf("iPod")!=-1)) {
// iOS device, so we get touchscreen buttons, accelerometer, and
// Wii Remote.
// thePlatform = "iOS";
theReturn = theReturn + "<a class=\"button\" onclick="+
"\"handleInputSelect('touchscreen');\">Touchscreen Buttons</a>" +
"<a class=\"button\" onclick=\"handleInputSelect('localAccel');\">"+
"Local Accelerometer</a>"+
"<a class=\"button\" onclick=\"handleInputSelect('appleWii');\">"+
"Wii Remote</a>";
} else if((userAgent.indexOf("Android")!=-1)) {
// Android device, so we get touchscreen buttons, keyboard input,
// and Wii Remote.
theReturn = theReturn +
"<a class=\"button\" onclick=\"handleInputSelect('touchscreen');\">"+
"Touchscreen Buttons</a><a class=\"button\" onclick="+
"\"handleInputSelect('localAccel');\">Local Accelerometer</a>" +
"<a class=\"button\" onclick=\"handleInputSelect('wii');\">Wii Remote</a>";
} else {
// Browser, so we get onscreen buttons and keyboard.
theReturn = theReturn + "<a class=\"button\" onclick="+
"\"handleInputSelect('keys');\">Keyboard</a><a align=\"center\""+
"class=\"button\" onclick=\"handleInputSelect('touchscreen');\">"+
"On-Screen Buttons</a>";
}
theReturn = theReturn + "</div>";
return theReturn;
};
function setupLocalAccelerometer() {
// Set the frequency of refresh for Accelerometer data.
var options = { frequency: 50 };
// Start watching accerlation and point to it with watchID.
watchID = navigator.accelerometer.watchAcceleration(onSuccess,
onError,
options);
};
var localAccelPaddlePosition = 50;
/*
* Contains the work done each time acceleration is audited. Right now,
* we display the raw data with a timestamp, as well as the calculated
* position, which is taken from the getPosition function.
* @param acceleration An object containing the current acceleration
* values. (x,y,z,timestamp).
*/
function onSuccess(acceleration) {
if(iOSWiiFlag) {
updateWiiPosition();
} else {
if(acceleration.x<-.2) {
if(localAccelPaddlePosition < 90) {
localAccelPaddlePosition = localAccelPaddlePosition + 5;
}
} else if(acceleration.x>.2) {
if(localAccelPaddlePosition > 0) {
localAccelPaddlePosition = localAccelPaddlePosition - 5;
}
}
updatePaddleToServer(localAccelPaddlePosition);
}
};
/*
* Fires off an alert if there's an error in the collection of acceleration.
*/
function onError(acceleration) {
alert("Error with acceleration.");
};
//========================================================================
//========================================================================
//=============================SERVER CODE================================
//========================================================================
//========================================================================
/**
* The 'document.addEventListener' contains reactions to information sent
* by the server.
*/
document.addEventListener("DOMContentLoaded", function() {
// The DOMContentLoaded event happens when the parsing of
// the current page is complete. This means that it only tries to
//connect when it's done parsing.
displaySelection("inputMethodSelection");
});
/**
* Sets up the connection to the server and registers multiple event
* listeners.
**/
function connectToServer(){
try{
socket = io.connect("10.150.1.204:3000");
}catch(err){
alert("There was an error connecting to the server."+
" Returning to the previous page.");
history.go(-1);
}
performAuthentication();
/* A failed authentication event. */
socket.on("authFailed", function(data){
if(authLooping){
alert("Login is not working. The server may be down. We'll "+
"take you back home now.");
window.navigate("index.html");
}
isGuest = confirm("Your login failed. Would you like to proceed as a guest?");
if(isGuest){
authLooping = true;
socket.emit("auth", {username: "guest", password: "1111"});
}else{
alert("You will now be returned to the previous page.");
history.go(-1);
}
});
/* A successful authentication event. */
socket.on("authGranted", function(data){
authLooping = false;
});
/* Tells us which paddle we are. */
socket.on("paddleID", function(data){
if(data.paddleID == 0){
alert("You are the left paddle.");
}else{
alert("You are the right paddle.");
}
paddleID = data.paddleID;
initCanvas();
});
/* Retrievs the user names */
socket.on("gameInfo", function(data){
playerOneName = data.names[0];
playerTwoName = data.names[1];
});
/** Updates the state of the game (basically coordinates). */
socket.on("gameState", function(data){
//expecting arrays for paddle1, paddle2, ballPos
leftPad = data.paddle[0];
rightPad= data.paddle[1];
xBall = data.ball[0];
yBall = data.ball[1];
draw();
});
socket.on("scoreUpdate", function(data){
scoreLeft = data.score[0];
scoreRight = data.score[1];
});
/**When the server sends a room list, the player can pick a room or
start a new one. */
socket.on("roomList", function(data){
roomList = [];
for(i=0; i<data.rooms.length; i=i+1){
if(data.rooms[i] != null){
roomList.push(data.rooms[i]);
}
}
if(gameOn){
return;
}
displaySelection("selectRoom", roomList);
});
/* A function for the end of a game. It notifies the player of whether
he or she won/lost. */
socket.on("gameEnd", function(data){
resultString = "";
if(scoreLeft<scoreRight){
if(paddleID == 0){
displaySelection("gameEnd", "lost");
}else{
displaySelection("gameEnd", "won");
}
}else{
if(paddleID == 0){
displaySelection("gameEnd", "won");
}else{
displaySelection("gameEnd", "lost");
}
}
});
/* A function for alerting the client when a disconnect occurs. */
socket.on("disconnect", function(data){
alert("You have been disconnected from the server! You will"+
" be returned to the previous page.");
if(wiiFlag){
alert("You should now select your regular input method.");
window.KeySelect.showKeyBoards();
}
history.go(-1);
});
};
/**
* Select the room to join.
*@param room a string representing the room name
*@param clientType player or spectator as a string
*/
function joinRoom(room, clientType){
socket.emit("joinRoom", {name: room, clientType: clientType});
};
/**
* Tells the server to make a room just for me.
* @param {roomName} the name of the room to create
*/
function createRoom(roomName){
socket.emit("createRoom", {name: roomName});
};
/**
* Update our paddle position with the server.
* @param {position} the new position of the paddle
*/
function updatePaddleToServer(position){
socket.emit("paddleUpdate", {pos: position});
};
/**
* Loads in login information from local storage to send to the server.
*/
function performAuthentication(){
var username = localStorage.getItem("username");
var pin = localStorage.getItem("pin");
socket.emit("auth", {username: username, password: pin});
};
/**
* Grabs the room name from an element roomName.roomName and submits it as
* a new room to the server.
*/
function handleNewRoom(){
var room = document.getElementById("roomName").value;
createRoom(room);
};