Help with canvas pong game

Hi all,

I have this code that is supposed to have the ball bouncing lateral between the racket but I can not get it to work. can I get help?

<!DOCTYPE html>
<html>

<head>
    <title>Pong lab task</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <canvas id="sCanvas" width="600" height="400" style="border: solid;"></canvas>
    <script type="text/javascript">
        "use strict";
        //******************
        // Variables
        //******************
        var c = document.getElementById("sCanvas");
        var ctx = sCanvas.getContext("2d");
        var cHeight = sCanvas.height;
        var cWidth = sCanvas.width;
       // var img = new Image();
       // img.src= 'your picture here'; 
       // var beep = new Audio('your sound file here');
       // var changedirection = false; //
       // var score1 = 0;  // for score board
       // var score2 = 0;  // for score board
        
              
        //******************
        //Objects
        //******************
         //create paddle object
            class Paddle{
                constructor(x,y){
                  //position, colour, size, speed for the paddle
                    this.xPosPaddle = x;
                    this.yPosPaddle = y;
                    this.paddleWidth = 20;
                    this.paddleHeigth = 80;
                    this.colour = "#9178D5";
                    this.speedYpaddle = 30;
                    this.speedXpaddle = 30;
                }
                drawMePaddle(){
               //your code here
                ctx.beginPath();
                ctx.rect(this.xPosPaddle, this.yPosPaddle, this.paddleWidth, this.paddleHeigth);
                ctx.fillStyle = this.colour;
                ctx.fill();
                
                }
            } // end paddle object

        //create the sphere object
        class Sphere {
            constructor() {
                    this.radius = (10);
                    this.colour = "blue";
                    this.xPos = Math.random() * cWidth;
                    this.yPos = Math.random() * cHeight;
                    this.speedY = 8 * Math.random();
                    this.speedX = 8 * Math.random();
                }
               
            drawMe() {
                //method to draw itself
                ctx.beginPath();
                ctx.arc(this.xPos, this.yPos, this.radius, 0, Math.PI * 2, true);
                ctx.fillStyle = this.colour;
                ctx.fill();
              
            }
            //method to move itself
            moveMe(){
                this.yPos += this.speedY;
                this.xPos += this.speedX;

                        //bounce off the bottom wall
                if (this.yPos > cHeight - this.radius){
            this.speedY = - this.speedY;
                    
            }           //bounce off the top wall
                else if(this.yPos < 0 + this.radius){
            this.speedY= -this.speedY;
                }

            //stop ball if hit right side
             if (this.xPos >cWidth){
                    this.speedX =0;
                    this.speedY =0;
                    
                    }
                    //bounce off player 2 paddle
               else if (this.xPos >player2.xPosPaddle && (this.yPos > player2.xPosPaddle && this.yPos< (player2.xPosPaddle+player2.paddleHeigth) ) ){
            this.speedX = - this.speedX;
            
            }
            //stop ball if hit left side
             if (this.yPos >cHeight){
                    this.speedX =0;
                    this.speedY =0;
                    
                    }
                    //bounce off player 2 paddle
               else if (this.yPos >player1.yPosPaddle && (this.yPos > player1.yPosPaddle && this.yPos< (player1.yPosPaddle+player1.paddleWidth) ) ){
            this.speedY = - this.speedY;
                   
                   
               }
        

                }//end moveMe function
            }// end Sphere object

        //******************
        // create game objects
        //******************

            var ball = new Sphere();
            var player1 = new Paddle(20,150);
            var player2  = new Paddle(550,150);

            //*********************
            // Deal with key presses
            // **********************

            var keysDown = []; //empty array to store which keys are being held down


        window.addEventListener("keydown", function (event) {
           keysDown[event.keyCode] = true; //store the code for the key being pressed
        });

        window.addEventListener("keyup", function (event) {
         delete  keysDown[event.keyCode] ;
        });

        function checkKeys() {
            //set the code keys for players
            if (keysDown[90]) {
                if(player1.yPosPaddle > 0){
                    player1.yPosPaddle -= player1.speedXpaddle; //z
                }
            }
             
            if (keysDown[88]) {
                if(player1.yPosPaddle < (cHeight-player1.height) ){
                    player1.yPosPaddle += player1.speedXpaddle; //x
                 }
            }
            //set the code key , . for player
            if (keysDown[190]){
                if (player2.yPosPaddle > 0){
                    player2.yPosPaddle -= player2.speedXpaddle;
                }
            }
            
            if (keysDown[188]){
                if(player2.yPosPaddle < (cHeight - player2.paddleHeigth)){
                    player2.yPosPaddle += player2.speedXpaddle;
                }
            }
   
        }

            //*********************
            // Make the score board
            // **********************
        
  

            //*********************
            // launch the ball from the centre, left and right, on space bar
            // **********************
 

        function render() {
            requestAnimationFrame(render);
            ctx.clearRect(0, 0, cWidth, cHeight);
            ball.drawMe();
            ball.moveMe();
            player1.drawMePaddle();
            player2.drawMePaddle();
            checkKeys();
           // scoreBoard();
        }
    
        render(); //set the animation and drawing on canvas going
    
    </script>
</body>

</html>

Welcome to freecodecamp community @jgarcia ! :smiley:
Looks like some code is missing^^
I tried to use it and i had to add the html with the canvas; furthermore you have lots of vars commented out ( which prevented the code to execute causing few errors).

I am not sure if you want to get it to work or your code works but it behaves weirdly: If the former is the case, the following code will work (just copy it in an html file and open it with a browser).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <canvas id="sCanvas"></canvas>
    <script>
        "use strict"; //****************** // Variables //****************** 
        var c = document.getElementById("sCanvas"); 
        var ctx = sCanvas.getContext("2d"); 
        var cHeight = sCanvas.height; 
        var cWidth = sCanvas.width; 
        // var img = new Image(); 
        // img.src= 'your picture here'; 
        // var beep = new Audio('your sound file here'); 
        // var changedirection = false; 
        // var score1 = 0; // for score board 
        // var score2 = 0; // for score board
        //******************
        //Objects
        //******************
         //create paddle object
            class Paddle{
                constructor(x,y){
                  //position, colour, size, speed for the paddle
                    this.xPosPaddle = x;
                    this.yPosPaddle = y;
                    this.paddleWidth = 20;
                    this.paddleHeigth = 80;
                    this.colour = "#9178D5";
                    this.speedYpaddle = 30;
                    this.speedXpaddle = 30;
                }
                drawMePaddle(){
               //your code here
                ctx.beginPath();
                ctx.rect(this.xPosPaddle, this.yPosPaddle, this.paddleWidth, this.paddleHeigth);
                ctx.fillStyle = this.colour;
                ctx.fill();
                
                }
            } // end paddle object
        
        //create the sphere object
        class Sphere {
            constructor() {
                    this.radius = (10);
                    this.colour = "blue";
                    this.xPos = Math.random() * cWidth;
                    this.yPos = Math.random() * cHeight;
                    this.speedY = 8 * Math.random();
                    this.speedX = 8 * Math.random();
                }
               
            drawMe() {
                //method to draw itself
                ctx.beginPath();
                ctx.arc(this.xPos, this.yPos, this.radius, 0, Math.PI * 2, true);
                ctx.fillStyle = this.colour;
                ctx.fill();
              
            }
            //method to move itself
            moveMe(){
                this.yPos += this.speedY;
                this.xPos += this.speedX;
        
                        //bounce off the bottom wall
                if (this.yPos > cHeight - this.radius){
            this.speedY = - this.speedY;
                    
            }           //bounce off the top wall
                else if(this.yPos < 0 + this.radius){
            this.speedY= -this.speedY;
                }
        
            //stop ball if hit right side
             if (this.xPos >cWidth){
                    this.speedX =0;
                    this.speedY =0;
                    
                    }
                    //bounce off player 2 paddle
               else if (this.xPos >player2.xPosPaddle && (this.yPos > player2.xPosPaddle && this.yPos< (player2.xPosPaddle+player2.paddleHeigth) ) ){
            this.speedX = - this.speedX;
            
            }
            //stop ball if hit left side
             if (this.yPos >cHeight){
                    this.speedX =0;
                    this.speedY =0;
                    
                    }
                    //bounce off player 2 paddle
               else if (this.yPos >player1.yPosPaddle && (this.yPos > player1.yPosPaddle && this.yPos< (player1.yPosPaddle+player1.paddleWidth) ) ){
            this.speedY = - this.speedY;
                   
                   
               }
        
        
                }//end moveMe function
            }// end Sphere object
        
        //******************
        // create game objects
        //******************
        
            var ball = new Sphere();
            var player1 = new Paddle(20,150);
            var player2  = new Paddle(550,150);
        
            //*********************
            // Deal with key presses
            // **********************
        
            var keysDown = []; //empty array to store which keys are being held down
        
        
        window.addEventListener("keydown", function (event) {
           keysDown[event.keyCode] = true; //store the code for the key being pressed
        });
        
        window.addEventListener("keyup", function (event) {
         delete  keysDown[event.keyCode] ;
        });
        
        function checkKeys() {
            //set the code keys for players
            if (keysDown[90]) {
                if(player1.yPosPaddle > 0){
                    player1.yPosPaddle -= player1.speedXpaddle; //z
                }
            }
             
            if (keysDown[88]) {
                if(player1.yPosPaddle < (cHeight-player1.height) ){
                    player1.yPosPaddle += player1.speedXpaddle; //x
                 }
            }
            //set the code key , . for player
            if (keysDown[190]){
                if (player2.yPosPaddle > 0){
                    player2.yPosPaddle -= player2.speedXpaddle;
                }
            }
            
            if (keysDown[188]){
                if(player2.yPosPaddle < (cHeight - player2.paddleHeigth)){
                    player2.yPosPaddle += player2.speedXpaddle;
                }
            }
        
        }
        
            //*********************
            // Make the score board
            // **********************
        
        
        
            //*********************
            // launch the ball from the centre, left and right, on space bar
            // **********************
        
        
        function render() {
            requestAnimationFrame(render);
            ctx.clearRect(0, 0, cWidth, cHeight);
            ball.drawMe();
            ball.moveMe();
            player1.drawMePaddle();
            player2.drawMePaddle();
            checkKeys();
           // scoreBoard();
        }
        
        render(); //set the animation and drawing on canvas going
        
        </script>
        
</body>
</html>

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

I’ve also retitled your post: I have assumed that you want help with the game code, not the HTML, and there is no CSS.

Many thanks for the help but the challenge is in getting the ball to move lateral between the 2 rackets as in my case the ball goes all over the place.

Here we are :slight_smile:

I had to make few changes^^

Here in the comment you say

stop ball if hit left side

But the code check for the height.I changed that


//stop ball if hit left side

if (this.yPos >cHeight){

this.speedX =0;

this.speedY =0;

}

to this


if (this.xPos <0){

this.speedX =0;

this.speedY =0;

}

Now, here you compare yPos with xPosPaddle.


else if (this.xPos >player2.xPosPaddle && (this.yPos > player2.xPosPaddle && this.yPos< (player2.xPosPaddle+player2.paddleHeigth) ) ){

Try this:


else if (this.xPos >player2.xPosPaddle && (this.yPos > player2.yPosPaddle && this.yPos< (player2.yPosPaddle+player2.paddleHeigth) ) ){

Here you made a strange mix :stuck_out_tongue:
It made little sense to me so i changed it to mirror player2 behaviour (I could have missed something in your code structure though)


else if (this.yPos >player1.yPosPaddle && (this.yPos > player1.yPosPaddle && this.yPos< (player1.yPosPaddle+player1.paddleWidth) ) ){

Try this:


else if (this.xPos <(player1.xPosPaddle + player1.paddleWidth) && (this.yPos > player1.yPosPaddle && this.yPos< (player1.yPosPaddle+player1.paddleHeight) ) ){

With these changes up the ball bounce between paddles (i made them full-height for testing purpose)^^ The ball starts here and there in my test code but that’s simply related to Math.random() and values around ^^

Hope this could be of any help!