• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Rezkon

Error in pong script.

12 posts in this topic

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>

0

Share this post


Link to post
Share on other sites
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
1

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
<!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,

0

Share this post


Link to post
Share on other sites

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?

0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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

dry.png


And then

Uncaught ReferenceError: onKeyDown is not defined

Edited by Rezkon
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0