//
// Definition of a pong game in JavaScript. 
// The 'P' key moves the right paddle up; the 'L' key moves it down.
// The 'Q' key moves the left paddle up; the 'A' key moves it down.
// However, the game has been slightly hacked so that animation of
// the paddles is automated.  Also, the game has been reformatted so
// that the scores for each player are not visible, although they are still
// calculated; and, the ball is set to move much slower than it should.
//
// Warren Sack <wsack@ucsc.edu>
//


        var ball;                 // This will refer to the HTML element "ball".
        var leftPaddle;           // This will also refer to an HTML element.
        var rightPaddle;          // This will also refer to an HTML element.
        var leftScore;            // This will also refer to an HTML element.
        var rightScore;           // This will also refer to an HTML element.
        var currentLeftScore;     // Left player's score.
        var currentRightScore;    // Right player's score.
        var scoreHasBeenUpdated;  // Is true just after a point has been scored.
        var timer;                // Defines the framerate of the game.
        var leftPaddleYPos;       // Vertical position of the leftPaddle;
        var leftPaddleXPos;       // Horizontal position of the leftPaddle.
        var leftDY;               // Vertical speed of leftPaddle.
        var rightPaddleYPos;      // Vertical position of the rightPaddle;
        var rightPaddleXPos;      // Horizontal position of the rightPaddle.
        var rightDY;              // Vertical speed of rightPaddle.
        var ballYPos;             // Vertical position of the ball.
        var ballXPos;             // Horizontal position of the ball.
        var ballDX;               // Horizontal speed of the ball.
        var ballDY;               // Vertical speed of the ball.
        var keysAndValuesAreMoving;  // Text of the page moves with the ball.

        // 
        // Assign JavaScript variables to the HTML elements;
        // position the paddles and initialize the scores to 0;
        // serve the ball into playing area; define handlers
        // for keyUp and keyDown events; start the game.
        //
        function init(){
            // window.resizeTo(660,600);
            leftPaddle = document.getElementById('leftPaddle');
            rightPaddle = document.getElementById('rightPaddle');
	    keysAndValues = document.getElementById('keysAndValues');
            leftPaddleYPos = 218
            rightPaddleYPos = 218;
            leftPaddleXPos = 0;
            rightPaddleXPos = 584;
            leftDY = 0;
            rightDY = 0;
            leftScore = document.getElementById('leftScore');
            rightScore = document.getElementById('rightScore');
            currentLeftScore = 0;
            currentRightScore = 0;
            scoreHasBeenUpdated = false;
            ball = document.getElementById('ball');
            serveBall();
            document.onkeydown = keyDownHandler;
            document.onkeyup = keyUpHandler;
	    document.onmousedown = mouseDownHandler;
            keysAndValuesAreMoving = false;
            start();
        }


        //
        // Define a handler for keyDown events for the keys
        // [q] and [a] (which move the leftPaddle); and keys
        // [p] and [l] (which move the rightPaddle).  The
        // keys set of the direction and speed of the paddles.
        // For quicker moving paddles, replace the "4"s and "-4"s
        // with larger and smaller numbers respectively.
        //
        function keyDownHandler(e){
            if(!e) e = window.event; // Special case for IE browsers.
            if(e.keyCode==81 && leftPaddleYPos > 0) {
               // keyCode 81 is the [q] key
               leftDY = -4;
            }
            if(e.keyCode==65 && leftPaddleYPos < 436) {
               // keyCode 65 is the [a] key
               leftDY = 4;
            }
            if(e.keyCode==80 && rightPaddleYPos > 0) {
               // keyCode 80 is the [p] key
               rightDY = -4;
            }
            if(e.keyCode==76 && rightPaddleYPos < 436) {
               // keyCode 76 is the [l] key
               rightDY = 4;
            }
        }


        //
        // Define a handler for all keyUp events.  When 
        // any key is released, the paddles will stop
        // moving.
        //
        function keyUpHandler(e){
            leftDY = 0;
            rightDY = 0;
        }

        //
        // Move the ball if the user clicks on the window.
        //
        function mouseDownHandler(e) {
	    ballXPos = e.clientX;
	    ballYPos = e.clientY;
	}


        // 
        // If the ball hits the top or bottom of the
        // playing area or hits a paddle, then turn it
        // around (by multiplying its speed by -1).
        // Change these lines if you want a non-Newtonian
        // physics for the ball.
        //
        function detectCollisions(){
            if(collisionX()) 
                ballDX = ballDX * -1;
            if(collisionY())
                ballDY = ballDY * -1;
        }


        //
        // Check to see if the ball is approaching the
        // top or the bottom of the playing area.
        //
        function collisionY(){
            if(ballYPos < 4 || ballYPos > 480)
                return true;
            return false;
        }

    
        //
        // Check to see if ball collided with a paddle.
        // If the ball is near the lefthand or righthand side
        // of the playing area and is not near a paddle, then
        // update the score.
        //
        function collisionX(){
            if (ballXPos > 584) {
               if ((ballYPos > rightPaddleYPos)
                   && (ballYPos < (rightPaddleYPos + 64))) {
                    return true;
               }
               else {
                  updateLeftScore();
                  return false;
               }
            }
            if (ballXPos < 16) {
               if ((ballYPos > leftPaddleYPos)
                    && (ballYPos < (leftPaddleYPos + 64))) {
                    return true;
               }
               else {
                  updateRightScore();
                  return false;
               }
            }
            return false;
        }


        //
        // Put the ball into play by starting it at the middle of the
        // playing area and by assigning it a random speed and direction.
        //
        function serveBall() {
            var XDirection = Math.floor(Math.random() * 2);
            if (XDirection == 0) { XDirection = -1; }
            ballDX = XDirection * (Math.floor(Math.random() * 3) + 10);
            var YDirection = Math.floor(Math.random() * 2);
            if (YDirection == 0) { YDirection = -1; }
            ballDY = YDirection * (Math.floor(Math.random() * 3) + 10);
            ballXPos = 300;
            ballYPos = 50 + Math.floor(Math.random() * 400);
         }
             
        
        //
        // If the ball has gone off the lefthand or righthand side
        // of the playing area, then put it back into play by serving
        // the ball again.  Otherwise, change position of the ball by
        // adding its speed to its current position.
        //
        function moveBall(){
            if ((ballXPos > 600) || (ballXPos < 0)) {
               serveBall();
               scoreHasBeenUpdated = false;
            } 
            else {
               ballXPos += ballDX;
               ballYPos += ballDY;
            }
            ball.style.left = ballXPos + 'px';
            ball.style.top = ballYPos + 'px';
	    if (keysAndValuesAreMoving == true) {
	        keysAndValues.style.top = (ballYPos - 60) + 'px';
            }
        }


        // 
        // Using the paddle speeds (leftDY and rightDY) assigned
        // by the keyDown handler, update the current positions
        // of the paddles.
        //
        function movePaddles(){
            leftPaddleYPos = leftPaddleYPos + leftDY;
	    //            if (ballDX <= 0) { leftPaddleYPos = ballYPos - 32; }
            leftPaddleYPos = ballYPos - 32;
            leftPaddle.style.top = leftPaddleYPos + 'px';
            rightPaddleYPos = rightPaddleYPos + rightDY;
	    //            if (ballDX > 0) { rightPaddleYPos = ballYPos - 32; }
            rightPaddleYPos = ballYPos - 32; 
            rightPaddle.style.top = rightPaddleYPos + 'px';
        }

      
        // 
        // Increment the left score and display its new value; record the
        // fact that the score has just been updated by assigning "true"
        // to the variable scoreHasBeenUpdated.
        //
        function updateLeftScore(){
            if (!scoreHasBeenUpdated) {
               currentLeftScore += 1;
               leftScore.innerHTML = '<center>' + currentLeftScore + '</center>';       
	       scoreHasBeenUpdated = true;
            }
        }


        //
        // Same, as above, to update the right player's score.
        //
        function updateRightScore(){
            if (!scoreHasBeenUpdated) {
               currentRightScore += 1;
               rightScore.innerHTML = '<center>' + currentRightScore + '</center>';
	       scoreHasBeenUpdated = true;
            }
        }


        //
        // Start the game and perform the following actions once
        // every 50 milliseconds: detectCollisions between the ball
        // the edges of the playing area and the paddles; move the ball;
        // and move the paddles.
        //
        function start(){
            detectCollisions();
            moveBall();
            movePaddles();
            timer = setTimeout('start()',50);
        }
