//get info, process data, update screen objects
//instance vars
var ball;
var paddle;
var score;
var hiScore;
//initial speeds
var dx = 6;
var dy = 6;
var currentScore = 0;
var highScore = 0;
var timer;
//set initial conditions for ball and paddle
var paddleLeft = 228;
var ballLeft = 200;
var ballTop = 4;
function init() {
//instantiate HTML object instance vars
ball = document.getElementById('ball');
paddle = document.getElementById('paddle');
score = document.getElementById('score');
hiScore = document.getElementById('hiScore');
//resister key listener with document object
document.onkeydown = keyListener;
//start the game loop
start();
}
function keyListener(e) {
if (!e) {
//for IE
e = window.event;
}
if (e.keyCode == 37 && paddleLeft > 0) {
//keycode 37 is left arrow
paddleLeft -= 10;
paddle.style.left = paddleLeft + 'px';
}
if (e.keyCode == 39 && paddleLeft < 436) {
//keycode 39 is right arrow
paddleLeft += 10;
paddle.style.left = paddleLeft + "px";
}
// FYI - Keycode 38 is up arrow,
// Keycode 40 is down arrow
}
function start() {
//game loop
detectCollisions();
render();
difficulty();
//end conditions
if (ballTop < 470) {
//still in play - keep the loop going
timer = setTimeout('start()', 50);
}
else {
gameOver();
}
}
function detectCollisions() {
//just reflect the ball on a collision
//a more robust engine could change trajectory of
//the ball based on where the ball hits the paddle
if (collisionX())
dx = dx * -1;
if (collisionY())
dy = dy * -1;
}
function collisionX() {
//check left and right boundaries
if (ballLeft < 4 || ballLeft > 480)
return true;
return false;
}
function collisionY() {
//check if at top of playing area
if(ballTop < 4)
return true;
//check to see if ball collided with paddle
if(ballTop >450) {
if(ballLeft > paddleLeft && ballLeft < paddleLeft + 64)
return true;
}
return false;
}
function render() {
moveBall();
updateScore();
}
function moveBall() {
ballLeft += dx;
ballTop += dy;
ball.style.left = ballLeft;
ball.style.top = ballTop;
}
function updateScore() {
currentScore += 10;
score.innerHTML = 'Score: ' + currentScore;
}
function difficulty() {
//as the game progresses, increase magnitude of the vertical speed
if (currentScore % 1000 == 0) {
if (dy > 0)
dy += 1;
else
dy -= 1;
}
}
function gameOver() {
//end the game by clearing the timer and modifying the score label
//If score is higher then high score, replaces the high score
clearTimeout(timer);
score.innerHTML += " - Game Over";
score.style.backgroundColor = 'rgb(128,0,0)';
if (parseInt(currentScore) >= parseInt(highScore)) {
highScore = currentScore;
hiScore.innerHTML = 'High Score: ' + highScore;
}
hiScore.style.backgroundColor = 'rgb(128,0,0)';
}
function resetg() {
//Resets the game back to it's starting points but leaves the high score
currentScore = 0;
paddleLeft = 228;
ballLeft = 200;
ballTop = 4;
start();
score.style.backgroundColor = 'rgb(32,128,64)';
hiScore.style.backgroundColor = 'rgb(32,128,64)';
}
|