<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Riley</title>
    <description>The latest articles on DEV Community by Riley (@riley320).</description>
    <link>https://dev.to/riley320</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2433098%2F863d9a8a-decc-4b59-8784-09123eeb8993.png</url>
      <title>DEV Community: Riley</title>
      <link>https://dev.to/riley320</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/riley320"/>
    <language>en</language>
    <item>
      <title>Building a 2D Pong Game in JS</title>
      <dc:creator>Riley</dc:creator>
      <pubDate>Wed, 01 Jan 2025 11:05:04 +0000</pubDate>
      <link>https://dev.to/riley320/building-a-2d-pong-game-in-js-450o</link>
      <guid>https://dev.to/riley320/building-a-2d-pong-game-in-js-450o</guid>
      <description>&lt;p&gt;It's a simple game with two paddles, a ball, and a score counter. Even though Pong is an old game, building it can teach you a lot about game gameplay, animations, and handling user input. &lt;/p&gt;

&lt;p&gt;So here I'll guide you through the process step by step...&lt;/p&gt;

&lt;p&gt;Before we start, let's set up the basic structure of our project. First, you'll need a text editor like Visual Studio Code, Sublime Text, or Notepad++. Then, create a folder for your project, and inside that folder, create an HTML file and a JavaScript file.&lt;/p&gt;

&lt;h3&gt;
  
  
  Writing the HTML
&lt;/h3&gt;

&lt;p&gt;Open your &lt;code&gt;index.html&lt;/code&gt; file and start by setting up a basic HTML structure. We'll add the &lt;code&gt;&amp;lt;canvas&amp;gt;&lt;/code&gt; element where we'll draw everything.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Pong Game&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        body {
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #000;
        }
        canvas {
            border: 2px solid #fff;
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;canvas id="pong" width="800" height="400"&amp;gt;&amp;lt;/canvas&amp;gt;
    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, we've set the width of the canvas to 800 pixels and the height to 400 pixels, which is a standard size for a 2D Pong game.&lt;/p&gt;

&lt;p&gt;Now, let's move on to the JS part. This will be the core of the game.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Set Up the Canvas&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;script.js&lt;/code&gt; file, start by selecting the canvas element and setting up the drawing context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const canvas = document.getElementById("pong");
const ctx = canvas.getContext("2d");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;canvas.getContext("2d")&lt;/code&gt; method gives us access to the drawing tools. We’ll use this to draw the paddles, ball, and score.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Define the game objects&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, we'll define the paddles and the ball. The paddles are rectangles, and the ball is a circle. Here's how you can define them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Paddle 1 (left)
const paddleWidth = 10, paddleHeight = 100;
const leftPaddle = {
    x: 0,
    y: canvas.height / 2 - paddleHeight / 2,
    width: paddleWidth,
    height: paddleHeight,
    color: "#00f",
    dy: 0 // Velocity of the paddle's movement
};

// Paddle 2 (right)
const rightPaddle = {
    x: canvas.width - paddleWidth,
    y: canvas.height / 2 - paddleHeight / 2,
    width: paddleWidth,
    height: paddleHeight,
    color: "#f00",
    dy: 0
};

// Ball
const ballRadius = 10;
const ball = {
    x: canvas.width / 2,
    y: canvas.height / 2,
    radius: ballRadius,
    color: "#fff",
    dx: 4, // Ball speed in X direction
    dy: 4  // Ball speed in Y direction
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we've set the paddle height to 100 pixels, and the ball radius to 10 pixels. The ball's speed is set to 4 pixels per frame in both the X and Y directions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Draw the Game Objects&lt;/strong&gt;&lt;br&gt;
To render everything, we'll need a function to draw the paddles, ball, and score on the canvas. Let's write a &lt;code&gt;draw()&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function draw() {
    // Clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw paddles
    ctx.fillStyle = leftPaddle.color;
    ctx.fillRect(leftPaddle.x, leftPaddle.y, leftPaddle.width, leftPaddle.height);

    ctx.fillStyle = rightPaddle.color;
    ctx.fillRect(rightPaddle.x, rightPaddle.y, rightPaddle.width, rightPaddle.height);

    // Draw ball
    ctx.fillStyle = ball.color;
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
    ctx.fill();
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function clears the canvas each frame and redraws the paddles and ball. The paddles are drawn using the &lt;code&gt;fillRect()&lt;/code&gt; method, and the ball is drawn using the &lt;code&gt;arc()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Move the Ball and Paddles&lt;/strong&gt;&lt;br&gt;
Now, let's make the ball move. We'll update its position each frame. For the paddles, we'll also add movement. Here's the code to handle the ball and paddle movement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function moveBall() {
    ball.x += ball.dx;
    ball.y += ball.dy;

    // Ball collision with top and bottom
    if (ball.y + ball.radius &amp;gt; canvas.height || ball.y - ball.radius &amp;lt; 0) {
        ball.dy = -ball.dy; // Reverse the Y direction
    }

    // Ball collision with paddles
    if (
        (ball.x - ball.radius &amp;lt; leftPaddle.x + leftPaddle.width &amp;amp;&amp;amp; ball.y &amp;gt; leftPaddle.y &amp;amp;&amp;amp; ball.y &amp;lt; leftPaddle.y + leftPaddle.height) ||
        (ball.x + ball.radius &amp;gt; rightPaddle.x &amp;amp;&amp;amp; ball.y &amp;gt; rightPaddle.y &amp;amp;&amp;amp; ball.y &amp;lt; rightPaddle.y + rightPaddle.height)
    ) {
        ball.dx = -ball.dx; // Reverse the X direction
    }

    // Ball out of bounds (left or right side)
    if (ball.x + ball.radius &amp;lt; 0 || ball.x - ball.radius &amp;gt; canvas.width) {
        // Reset ball position to the center
        ball.x = canvas.width / 2;
        ball.y = canvas.height / 2;
        ball.dx = 4; // Ball speed reset
        ball.dy = 4;
    }
}

function movePaddle(paddle) {
    paddle.y += paddle.dy;

    // Prevent paddle from going out of bounds
    if (paddle.y &amp;lt; 0) {
        paddle.y = 0;
    } else if (paddle.y + paddle.height &amp;gt; canvas.height) {
        paddle.y = canvas.height - paddle.height;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in this function, the ball will bounce off the walls and paddles. The paddles can move up and down, but they won't go off the screen.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Handle User Input&lt;/strong&gt;&lt;br&gt;
We need to allow the player to control the paddles. We'll add event listeners for the up and down arrow keys.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.addEventListener("keydown", function (event) {
    if (event.key === "ArrowUp") {
        rightPaddle.dy = -5; // Move up
    } else if (event.key === "ArrowDown") {
        rightPaddle.dy = 5; // Move down
    }

    if (event.key === "w") {
        leftPaddle.dy = -5; // Move up
    } else if (event.key === "s") {
        leftPaddle.dy = 5; // Move down
    }
});

document.addEventListener("keyup", function (event) {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
        rightPaddle.dy = 0; // Stop movement
    }

    if (event.key === "w" || event.key === "s") {
        leftPaddle.dy = 0; // Stop movement
    }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The up and down arrow keys control the right paddle, while the W and S keys control the left paddle.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Putting It All Together&lt;/strong&gt;&lt;br&gt;
Finally, we need to call the functions in a game loop to make the game run continuously. Use &lt;code&gt;requestAnimationFrame()&lt;/code&gt; to create a smooth animation loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function gameLoop() {
    draw();
    moveBall();
    movePaddle(leftPaddle);
    movePaddle(rightPaddle);
    requestAnimationFrame(gameLoop); // Call the gameLoop again
}

gameLoop(); // Start the game loop

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finally...&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;And there you have it! You've now built a basic 2D Pong game in JS. This game isn't overly complex, but it gives you a good foundation for understanding how game mechanics work. You can further enhance it by adding features like scoring, sound effects, or AI for single player mode.&lt;/p&gt;

&lt;p&gt;Quick intro about me: So I am nothing but a game developer and a gamer as well. Worked on many gaming projects like &lt;a href="https://spendbillmoney.com/" rel="noopener noreferrer"&gt;Spend Bill Gates Money&lt;/a&gt; a simulator game.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
