$10 ### Image of the Day Submit IOTD | Top Screenshots ### The latest, straight to your Inbox. Subscribe to GameDev.net's newsletters to receive the latest updates and exclusive content. Sign up now ## Error in pong script. Old topic! Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic. 12 replies to this topic ### #1Rezkon Members Posted 26 June 2013 - 08:03 AM 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 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)

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>  ### #2HappyCoder Members Posted 26 June 2013 - 10:32 AM 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. Edited by HappyCoder, 26 June 2013 - 10:35 AM. My current game project Platform RPG ### #3Rezkon Members Posted 26 June 2013 - 09:50 PM 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 ### #4HappyCoder Members Posted 26 June 2013 - 10:38 PM 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 ### #5Rezkon Members Posted 26 June 2013 - 11:26 PM 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".

### #6Rezkon  Members

Posted 26 June 2013 - 11:50 PM

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.

Edited by Rezkon, 26 June 2013 - 11:59 PM.

### #7Rezkon  Members

Posted 27 June 2013 - 12:09 AM

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

/*This block gives the canvas
a centered element*/
#pongGame
{
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" />
<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);

//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
//draw the comp paddle, passing variables defined above
}
//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.closePath();
ctx.fillStyle="6DB33F";
ctx.fill();

}
//This draws the paddle//
{
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,

### #8Rezkon  Members

Posted 27 June 2013 - 08:42 AM

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?

### #9marcClintDion  Members

Posted 27 June 2013 - 10:08 AM

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.

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

### #10Rezkon  Members

Posted 27 June 2013 - 09:43 PM

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

### #11Rezkon  Members

Posted 28 June 2013 - 05:35 AM

As i think i fixed the error being canvas missed <canvas id="pongGame"

And then

Uncaught ReferenceError: onKeyDown is not defined

Edited by Rezkon, 28 June 2013 - 05:58 AM.

### #12Juliean  GDNet+

Posted 28 June 2013 - 07:53 AM

Javascript functions don't work like that. Eigther store the onKeyXXX-functions in an object (then you can reference them by the objects name) or register them directely in those lines as anonymous functions.

Posted 29 June 2013 - 10:27 AM

I took a look at your code and after fiddling with it for a while it seems to run fine in chrome. You should store key presses in a buffer though, here's an example:

//a buffer of boolean values, to tell us whether or not the key is down
var keys = [];

//attach your event listeners
document.onkeydown = function(e){
keys[e.keyCode] = true;
};
document.onkeyup = function(e){
keys[e.keyCode] = false;
};

//now when you want to check if a key is down just do this
if(keys[40] == true){
//do something
}

This method of getting input allows you to store keypresses a lot easier, for a list of all the javascript keycodes I recommend going here -> http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Edited by xDarkShadowKnightx, 29 June 2013 - 10:28 AM.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.