Pong Game

From CSE330 Wiki
Revision as of 06:06, 19 November 2013 by Shane (talk | contribs) (Adding flow chart)
Jump to navigationJump to search

This article documents pong-game.js, a pre-built JavaScript file that helps you implement your pong game.

Setup

First thing first: set up a static file server running Node.JS. We will need it in order to serve up our HTML and JavaScript content.

File 1: pong-game.js

The first file you can save in your static directory will be pong-game.js, which you can download from here: http://classes.engineering.wustl.edu/cse330/content/pong-game.js

We created the pong-game.js file for you to save you time and so that you can focus on the Node.JS and Socket.IO aspects of this module. This file contains the core Pong engine, but it does not establish communication between users of any kind.

File 2: client.js

You should create an additional file, client.js, which you include into client.html and which contains the client-side logic for your Pong game. It should load after pong-game.js. You will be saving all of you client-side code in this file.

File 3: client.html

The third file you can save in your static directory should be an HTML file created from your favorite Quick and Easy Page Layout. You need to add the following CSS rules:

#gameContainer{
	margin: 0 auto;
	width: 960px;
	height: 500px;
}
#controls{
	height: 20px;
	text-align: center;
}
#game{
	width: 960px;
	height: 480px;
	border: 1px solid black;
}

Add the following HTML inside your main div; this is what will contain the Pong game canvas:

<div id="gameContainer" style="display:none;">
	<div id="game"></div>
</div>

You also need to require pong-game.js and client.js.

<script src="pong-game.js"></script>
<script src="client.js"></script>

Connecting to Socket.IO

Now that you have your static fileserver running that serves up your three files (pong-game.js, client.html, and client.js), we need to connect everything with Socket.IO.

Set up a static fileserver by following the instructions in the Node.JS guide. When finished, add the following lines:

io.listen(app).sockets.on("connection", function(socket){
	// This closure runs when a new Socket.IO connection is established.
	
	// Listen for client messaging server:
	socket.on("message", function(content){
		// do stuff
	});
	
	// Send a message from the server to the client:
	socket.emit("message", {some:"data"});
});

Don't forget to require socket.io at the top of your file!

io = require("socket.io")

You also need to make sure to install socket.io from npm.

Inside of the io.listen callback function is where most of your server-side code will go.

On the client side, you need to include the Socket.IO library (put this above pong-game.js and client.js):

<script src="/socket.io/socket.io.js"></script>

And finally, you need to connect your client to the Socket.IO server (put this in client.js):

var socket = io.connect(window.location.origin);

But enough of us giving you all the code! It's time for you to start being creative.

The API

For the remainder of this module, your work will be in three files:

  • app.js (or whatever you called your Node.JS file)
  • client.html
  • client.js

What you need to do is to build a system that enables two players who are both viewing client.html to choose each other (e.g., from a lobby) and play a game of Pong.

You should be wondering, "how do I interact with the Pong game?" The public interface is as follows.

Methods

  • pong.init()
    Initialize the game client.
  • pong.resetBall([x, y])
    Arbitrarily set the position of the ball. Defaults to the center if no arguments are given. Cancels all animations currently acting on the ball.
  • pong.launch(angle, direction)
    Launch the ball from its current position in the specified angle (-89 to +89) and direction (-1 for left or 1 for right).
  • pong.updateOpponentPaddle(position)
    Set the position of the opponent paddle to position. (Hint: the position value should have been generated by the opponent's paddlemove event)
  • pong.pauseOrResumeGame()
    Set the game in a paused state, or remove the game from a paused state.
  • pong.ready()
    Returns true if the game is not in a "paused" state.
  • pong.setScore(score)
    Display score on the game canvas. score is an object literal containing two fields: left and right.

Events

All events for the pong game are fired on the window.

  • paddlemove
    The player's paddle has moved.
    This event will fire only after the paddle has moved 15 pixels or more.
    • event.detail.position
      The new y coordinate of the paddle.
  • paddlehit-left
    The ball has hit the left side of the screen.
    • event.detail.hit
      True if the ball hit the player's paddle; false otherwise.
    • event.detail.angle
      If the ball was reflected, the new angle of the ball's rightward movement.
    • event.detail.position
      The position at which the ball hit the left side.

Problems with Our Interface

There are at least two major problematic issues with our API:

  • We are firing events on the window. We should have taken the time to make our Pong class implement the EventTarget interface directly.
  • We are putting more trust in the client than we should, because the client can fake any angle and position upon the paddlehit-left event and manipulate the game in his or her favor. The trajectory should be computed on the Node.JS side.

Just be aware of the above issues as you complete this lab. You won't be required to fix them, although if you do (and if you recompile your modified code with Lime) you may be a candidate for extra credit.

Enabling a Player to Pause

You do not need to implement pausing for the purposes of Module 7. If you do, you can earn 5 points of creative portion.

Implementing a game pause is more difficult for a network game than it is for a game that runs on just one computer: you need to make sure that the game is in a state such that you won't run into any race conditions, etc.

One situation during a Pong game when it makes sense to enable a user to pause the game is after a user has lost a round. Since the game at that point in time is waiting for the player to launch the next ball, we shouldn't have any race conditions.

If you implement pausing, the pong.pauseOrResumeGame() and pong.ready() functions will come in handy.

Examples

Starting a Pong Game

Once two players have formed a pair, one of them needs to initialize the game with a certain angle and direction for the ball. Here is how you might go about doing this:

// generate an initial angle between -60 degrees and +60 degrees:
var initAngle = -60 + 120*Math.random();

// randomly choose the initial direction of the ball:
var initDirection = Math.random() < 0.5 ? -1 : 1;

// show the game canvas:
document.getElementById("gameContainer").style.display = "block";

// initialize the game canvas:
pong.init();

// move the ball to the center:
pong.resetBall();

// set the ball into motion:
pong.launch(initAngle, initDirection);

// tell the server about the ball's initial angle and direction.  For example:
socket.emit("launch", {
	angle: initAngle,
	direction: initDirection
});

When a Player Reflects the Ball

When the ball hits a player's side, the paddlehit-left event fires on the window. Here is how you might listen for this event in your client.js and transmit this information over your socket:

window.addEventListener("paddlehit-left", function(e){
	// e.detail.hit will be true if the client hit the ball with his/her paddle.
	if (e.detail.hit) {
		console.log("HIT PADDLE.  New angle: %f", e.detail.angle); // log a message to the console
		
		// Tell our opponent via Socket.IO about the ball's new angle and position:
		socket.emit("reflect", {
			angle: e.detail.angle,
			position: e.detail.position
		});
		
		// Note: The game automatically launches the ball and determines the angle based on the ball's position relative to the paddle position.  We therefore do not need to call pong.launch() in here (but our opponent will, as shown below).
	}else{
		console.log("MISSED PADDLE");
		
		// in here, we will update the score, check for victory condition, launch a new ball (perhaps after a timeout), etc.
	}
});

Here is what you might have in app.js inside of your Socket.IO callback function:

// Listen for the "reflect" message from the client
socket.on("reflect", function(data){
	// Tell our opponent about the reflection.
	// Note: In this sample implementation, we store the opponent in `socket.opponent`.
	// You might use a different mechanism for storing the opponent's socket.
	socket.opponent.emit("reflect", data);
});

Finally, here is what you might have on the opponent's end (hint: this is also in client.js):

// Listen for the "reflect" message from the server
socket.on("reflect", function(data){
	// In order to make up for any network lag, immediately move the ball to its correct position:
	pong.resetBall(960, data.position);
	
	// Finally, launch the ball on our local game client:
	pong.launch(data.angle, -1);
});

Flow Chart

If you are a visual learner, this flow chart of the logic you need to build for the pong game might be useful.

Module 7 Flow Chart.png

How We Built pong-game.js

If you are curious, we used the LimeJS framework as the backbone of pong-game.js. You can find the pre-compiled source code for the Pong game here:

We then used the Google Closure Compiler to compile all of the libraries you need into the one modular JavaScript file.

Just to be clear, for the purposes of Module 7, you do not need to bother with either LimeJS or Google Closure.