Pong Setup

HTML and CSS for pong game

by Roberta Himes

HTML

<div id='playingField'>
    <div id='output'></div>
    <div id='ball'></div>
    <div id='paddle'></div>
    <div id='instructions'>Click To Start</div>
    <div id='scorePanel'>Score: 0</div>
</div>

CSS

#playingField {
    position: relative;
    top: 0;
    left: 0;
}
#ball {
    position: absolute;
}
#paddle {
    position: absolute;
    background-color: #aaa;
}
#instructions {
    display : block;
    position: relative;
    top: 40%;
    margin-left: auto;
    margin-right: auto;
    padding : 10px;
    background-color: white;
    border : 2px solid red;
    border-radius: 5px;
    width: 20%;
}
#scorePanel {
    display: block;
    position: absolute;
    top: 0px;
    left: 150px;
    width: 200px;
    height: 20px;
    background-color: white;
    border: 1px solid red;
    border-radius: 4px;
}

JavaScript

// Pong game
// Bouncing ball and user-controlled paddle

// Game configuration
// Change these values to customize your game
var fieldWidth = 600; // how wide is the playing field
var fieldHeight = 400; // how tall is the playing field
var fieldColor = 0x337733; // what color is the playing field

var paddleWidth = 10; // how wide is the paddle
var paddleHeight = 50; // how tall is the paddle
var paddleColor = 0xAAAAAA; // what color is the paddle
var paddleSpeed = 10; // how fast will the paddle move
var paddleXPos = fieldWidth - Math.floor(fieldWidth / 10); // 10% from right
var paddleYPos = Math.floor((fieldHeight - paddleHeight) / 2); // middle

var ballSize = 10; // how big is the ball
var ballXPos = Math.floor(fieldWidth / 10); // start 10% from left
var ballYPos = Math.floor((fieldHeight - ballSize) / 2); // middle
var ballXSpeed = Math.floor(Math.random() * 5) + 2; // what is the initial velocity of the ball
var ballYSpeed = 2;
var ballColor = 0xffffff; // what color is the ball
var newBallColor = ballColor;

var keyState = 0; // current state of arrow keys
var intTimeHandle = 0; // pointer to the interval timer

var score = 0; // score - ball hits paddle count
var highScore = 0; // highest score this session

// Debug output
// you can send debug print message to the screen using this function
// this is helpful if you are not getting the results that you expect
function output(message) {
    document.getElementById("output").innerHTML += message + "<br/>\n";
}

function setPosition(x, y) {
    this.xpos = x;
    this.ypos = y;
    this.obj.style.top = y.toString() + "px";
    this.obj.style.left = x.toString() + "px";
}

function setColor(newColor) {
    newColor = "000000" + newColor.toString(16);
    this.obj.style.backgroundColor = "#" + newColor.substr(newColor.length - 6);
}

// Playing field object
function PlayingField(width, height, color) {
    this.width = width;
    this.height = height;
    this.obj =...