Error in pong script.

Started by
11 comments, last by luveti 10 years, 9 months ago

ok so im working on a pong game and i dont know many good programming practice's, placements, and that which im trying to learn now this is a draft of the script im trying to use uncomplete so id like someone even proof-read it, confirm if its a bad or a simple error

The File is the code im using smile.png im still learning alot but i play to make pong then snake then more of those "Classic" Games to get a idea of programming games

Edit: File wont attach, ill post script here





<script>
 $(document).ready(function()
 {
    {
  
    //Global Variables
    
    //Stage
 var canvas; 
 var ctx; //delcaring the context of the element
 var WIDTH; //Width of the canvas element
 var HEIGHT;//this will be the height of the cnavas element
 
 //ball
 var x;//Postion of X-Ball
 var y;//Postion of Y-Ball
 var ballRadius = 10; //This is the radius of the ball (pxiels)
 
 //Paddles
 var paddleHeight = 70;/*This displays 
 the height of paddles*/
 var paddleWidth = 10;//Displays width of paddles// 
 var playerPaddle; //this the variable of the player paddle//
 var playerPaddleColour = "#EE3424";//Delcares the paddle to being white aka colour//
 var compPaddle; //Same as players expecet COMP//
 var compPaddleColour = "EE8722";//this is the colour of the computers paddle (orange)
 
 
 
 //attach event listeners
 $(document).keydown(onKeyDown);
 $(document).keyup(onKeyUp);
 
 //flags
 var upPressed = false;
 var downPressed = false;
 
  //interval variable
   var refreshStage;
 
 //set upPressed or downPressed if up or down are pressed//
 function onKeyDown(evt)
 {
     if (evt.keyCode == 38)
         {
             upPressed = true;
         }
         else if (evt.keyCode == 40)
             {
                 downPressed = true;
             }
 }
 //unset upPressed or downPressed if the up or down are let go
 function onKeyUp(evt)
 {
     if (evt.keyCode == 38)
         {
             upPressed = true;
         }
         else if (evt.KeyCode == 40)
             {
                 downPressed = false;
             }
 }
 function clearStage()
 { 
     ctx.clearRect(0,0,WIDTH,HEIGHT);
 }
 init();
  };
 function init()
{
   //get the canvas element
   canvas = $('#pongGame')[0];
   //get the context of the element
   ctx = canvas.getContext("2d");
   //set our width and height variables equal to the width
   //and height of the canvas element
   WIDTH = canvas.width;
   HEIGHT = canvas.height;
   
   //set the starting height of the paddles to the center 
   //of the y-axis
   playerPaddle = (HEIGHT / 2) - (paddleHeight/2);
   compPaddle = (HEIGHT/ 2) - (paddleHeight/2);
   
   //set the x and y values for where the ball will start
   //in this case the center of the canvas
   x = 400;
   y = 250;
   
   //This Function clears the stage below every 100th of
   //a second (10ms)
   refreshStage = setInterval(drawGame, 10);
   
 
//This function Draw the Game Stage
function drawGame()
{
    //First wipe the old frame
    clearStage();
    //draw the sidelines
    drawSideLines();
    //Draw the ball
    drawBall();
    //check to see if the downPressed flag equals true
    if (downPressed == true)
        {
         //make sure there is room for the paddle to move further down
         if(playerPaddle + paddleHeight + 20 <= HEIGHT)
             {
                 //set the new postition of the playerPaddle down 5 pixels
                 playerPaddle +=5;
             }
        }
        //check to see if the UpPressed flag equals true//
        else if (upPressed == true)
            {
                //make sure there is room for the paddle to move up
                if(playerPaddle - 20 >= 0)
                    {
                        //set the new postion of the paddle up 5 pxs
                        playerPaddle -= 5;
                    }
            }
            
                    }
    //Draw the Player paddle, passing variables defined above
    drawPaddle(0,playerPaddle,paddleWidth,PaddleHeight,playerPaddleColour);
    //draw the comp paddle, passing variables defined above
    drawPaddle(WIDTH - 10,comPaddle,PaddleWidth,paddleHeight,compPaddleColour);
}
//this is a function to draw the side lines//
function drawSideLines()
{
    ctx.beginPath();
    ctx.rect(0,0,WIDTH,15);
    ctx.closePath();
    ctx.fillStyle="#1666AF";
    ctx.fill();
    
    ctx.beginPath();
    ctx.rect(0,HEIGHT - 15,WIDTH,15);
    ctx.closePath();
    ctx.fillStyle="#1666AF";
    ctx.fill();
}

//This is drawing the ball, simples!//
function drawBall()
{
    ctx.beginPath();
    ctx.arc(x,y, ballRadius,0,Math.PI*2, true);
    ctx.closePath();
    ctx.fillStyle="6DB33F";
    ctx.fill();
    
}
//This draws the paddle//
function drawPaddle(xaxis,yaxis,pwidth,pheight,pcolour)
{
    ctx.beginPath();
    ctx.rect(xaxis,yaxis,pwidth,pheight);
    ctx.closePath();
    ctx.fillStyle=pcolour;
    ctx.fill();
    
 
}
</script>


<style type="text/css">
 /*This block gives the canvas 
 a centered element*/
 #pongGame
 {
     background:url(http://www.allstate.com/resources/Allstate/images/ni/NI-LinkedIm-Banner.jpg);
     background-size: 75%;
     background-repeat:no-repeat;
     background-position:center;
     border:1px solid #1666AF;
 }
 /*This block centers the contiant of the page*/
 #container
 {
     position: fixed;
     top: 50%;
     left: 50%;
     ;
     margin-top: -275px;
     text-align: center;
}

/*This is the font for the scoreboard 
and text*/
#Score
{
    margin-left: 500px;
    font-family: 'Rambla', sans-serif;
    font-size:28px;
    color: #717073;
    border: 2px solid #1666AF;
    margin-bottom: 5px;
}
/*This block sets the color 
 text of the score board*/
#playerScore
{
color: #EE3424; 
}
#compScore
{
    color: #EE8722;
}

</style>

<link href="http://fonts.googleapis.com/css?family=Rambla:700" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="container">
  <div id="Score">
      You: <span id="playerScore">0</span> <span style="color: #6db33f;"><b>//</b></span> Computer: <span id="compScore">0</span>
 </div>
<canvas width="800" height="500">
     Your browser does not support HTML5
</canvas>  
</div>

Advertisement
Is there a specific error you are having?

I don't see any major issues in the code, although I did just a quick glance over it.

I think you made a good move by making a single draw paddle function then passing parameters to it. I also like how you declared constants at the top of the file for the width and height of the paddle.

Something I would recommend on your next project is learning how to use javascript prototypes to use a more object oriented programming style. Pong and snake are simple enough that they are easily manageable without good object oriented design practice, but when you attempt to take on a larger game project it will be really hard to manage if you don't have a good object oriented design.

Good work so far, and if you are experiencing a bug at the time please post what it is so I can look at that code in more detail.

EDIT:

I just noticed that you have inconsistent capitalization on your variable names.
When you declare paddleWidth and paddleHeight you have the first letter lower case, but when you use them in drawPaddle half of them are capitalized to be PaddleWidth or PaddleHeight. JavaScript is case sensitive so you will need to make the capitalization consistent.
My current game project Platform RPG

Thanks man, some of the errors were simple as Missing ; or == should be === but the issue im having is nothing is showing up when i run it on chrome or firefox, just a Scoreboard :\ Im not quiet sure why though, it seems like the code is correct i might have some of it in the wrong place though

Have you tried using the developer tools in chrome and using them to set break points to see if the drawing code is even reached?
My current game project Platform RPG

Just tried and i got a error

  1. Uncaught ReferenceError: $ is not defined index.html:3
Resource interpreted as Font but transferred with MIME type font/woff: "http://themes.googleusercontent.com/static/fonts/rambla/v1/kIZPeiOLKnKdd6L5mB1Cnz8E0i7KZn-EPnyo3HZu7kw.woff".

I think its because my script isnt with in the <body> Tags.

Tried switching some things up but nothing seemed to fix anything, i just get the scoreboard there isnt any errors in NetBeans, so im not sure atm.


<!DOCTYPE html>
<html>   
<style type="text/css">

 /*This block gives the canvas 
 a centered element*/
 #pongGame
 {
     background:url(http://www.allstate.com/resources/Allstate/images/ni/NI-LinkedIm-Banner.jpg);
     background-size: 75%;
     background-repeat:no-repeat;
     background-position:center;
     border:1px solid #1666AF;
 }
 /*This block centers the contiant of the page*/
 #container
 {
     position: fixed;
     top: 50%;
     left: 50%;
     ;
     margin-top: -275px;
     text-align: center;
}

/*This is the font for the scoreboard 
and text*/
#Score
{
    margin-left: 500px;
    font-family: 'Rambla', sans-serif;
    font-size:28px;
    color: #717073;
    border: 2px solid #1666AF;
    margin-bottom: 5px;
}
/*This block sets the color 
 text of the score board*/
#playerScore
{
color: #EE3424; 
}
#compScore
{
    color: #EE8722;
}
</style> 
<meta charset="utf-8" />    
<link href="http://fonts.googleapis.com/css?family=Rambla:700" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div id="container">
  <div id="Score">
      You: <span id="playerScore">0</span> <span style="color: #6db33f;"><b>//</b></span> Computer: <span id="compScore">0</span>
 </div>
    
<canvas width="800" height="500">
     Your browser does not support HTML5
</canvas>  
</div>
<script>
 $(document).ready(function()
 {
 //Global Variables
 var directionX;
 var directionY;
    //Stage
 var canvas; 
 var ctx; //delcaring the context of the element
 var WIDTH; //Width of the canvas element
 var HEIGHT;//this will be the height of the cnavas element
 
 //ball
 var x;//Postion of X-Ball
 var y;//Postion of Y-Ball
 var ballRadius = 10; //This is the radius of the ball (pxiels)
 
 //Paddles
 var PaddleHeight = 70;/*This displays 
 the height of paddles*/
 var PaddleWidth = 10;//Displays width of paddles// 
 var playerPaddle; //this the variable of the player paddle//
 var playerPaddleColour = "#EE3424";//Delcares the paddle to being white aka colour//
 var compPaddle; //Same as players expecet COMP//
 var compPaddleColour = "EE8722";//this is the colour of the computers paddle (orange)
 
 
 
 //attach event listeners
 $(document).keydown(onKeyDown);
 $(document).keyup(onKeyUp);
 
 //flags
 var upPressed = false;
 var downPressed = false;
 
  //interval variable
   var refreshStage;
 
 //set upPressed or downPressed if up or down are pressed//
 function onKeyDown(evt)
 {
     if (evt.keyCode === 38)
         {
             upPressed = true;
         }
         else if (evt.keyCode === 40)
             {
                 downPressed = true;
             }
 }
 //unset upPressed or downPressed if the up or down are let go
 function onKeyUp(evt)
 {
     if (evt.keyCode === 38)
         {
             upPressed = true;
         }
         else if (evt.KeyCode === 40)
             {
                 downPressed = false;
             }
 }
 
 function init()
{
   //get the canvas element
   canvas = $('#pongGame')[0];
   //get the context of the element
   ctx = canvas.getContext("2d");
   //set our width and height variables equal to the width
   //and height of the canvas element
   WIDTH = canvas.width;
   HEIGHT = canvas.height;
   
   //set the starting height of the paddles to the center 
   //of the y-axis
   playerPaddle = (HEIGHT / 2) - (PaddleHeight/2);
   compPaddle = (HEIGHT/ 2) - (PaddleHeight/2);
   
   //set the x and y values for where the ball will start
   //in this case the center of the canvas
   x = 400;
   y = 250;
   // Direction of the Ball Via X,Y
    directionX = 4;
    directionY = 6;
   //This Function clears the stage below every 100th of
   //a second (10ms)
   refreshStage = setInterval(drawGame, 10);
   
   //this function brings it white
   function clearStage()
   {
       ctx.clearRect(0,0,WIDTH, HEIGHT);
   }
   
}
//This function Draw the Game Stage
function drawGame()
{
    //Controls the Direction again//
    x += directionX;
    y += directionY;
    //First wipe the old frame
    clearStage();
    //draw the sidelines
    drawSideLines();
    //Draw the ball
    drawBall();
    //check to see if the downPressed flag equals true
    if (downPressed === true)
        {
         //make sure there is room for the paddle to move further down
         if(playerPaddle + PaddleHeight + 20 <= HEIGHT)
             //sets the postion of the paddle to move further down
    //Draw the Player paddle, passing variables defined above
    drawPaddle(0,playerPaddle,PaddleWidth,PaddleHeight,playerPaddleColour);
    //draw the comp paddle, passing variables defined above
    drawPaddle(WIDTH - 10,comPaddle,PaddleWidth,PaddleHeight,compPaddleColour);
}
//this is a function to draw the side lines//
function drawSideLines()
{
    ctx.beginPath();
    ctx.rect(0,0,WIDTH,15);
    ctx.closePath();
    ctx.fillStyle="#1666AF";
    ctx.fill();
    
    ctx.beginPath();
    ctx.rect(0,HEIGHT - 15,WIDTH,15);
    ctx.closePath();
    ctx.fillStyle="#1666AF";
    ctx.fill();
}

//This is drawing the ball, simples!//
function drawBall()
{
    ctx.beginPath();
    ctx.arc(x,y, ballRadius,0,Math.PI*2, true);
    ctx.closePath();
    ctx.fillStyle="6DB33F";
    ctx.fill();
    
}
//This draws the paddle//
function drawPaddle(xaxis,yaxis,pwidth,pheight,pcolour)
{
    ctx.beginPath();
    ctx.rect(xaxis,yaxis,pwidth,pheight);
    ctx.closePath();
    ctx.fillStyle=pcolour;
    ctx.fill();
    //call the init function
    init();
 

}
}
 });
</script>
</body>
</html>

So far ive tried to fix my capitalization, tryed to put them in the right tags hoping that it would run via that, but nothing atm

Sometimes a blue background will show up but its not very consistent,

So i tried running it with JSbin and it seems it stops around where the CSS Ends and doesnt really reach the script at all, anyone see a reason why?

I pasted this code into a text file and renamed the extension to .html. I opened it in Chrome and the following screenshot is the result. Based on what I'm seeing here, the first thing I'd do is verify that the rest is not being drawn somewhere way off screen.

pongPositioning.jpg

Consider it pure joy, my brothers and sisters, whenever you face trials of many kinds, 3 because you know that the testing of your faith produces perseverance. 4 Let perseverance finish its work so that you may be mature and complete, not lacking anything.

Well it seems all the CSS is fine in the code, centered; and that :S I cant see a reason it wouldnt be

This topic is closed to new replies.

Advertisement