JavaFar Academy - Learn to Code with Java & PythonJavaFar Academy - Learn to Code with Java & Python

Mobile Pong Game Development: Swipe-Controlled Classic Paddle Action – Building a Timeless Arcade Experience with Java

Creating a mobile version of the classic Pong game involves handling touch inputs for paddle control and implementing the logic for bouncing a ball back and forth between two paddles. In this example, we’ll outline a basic web version that can be adapted for touch controls, suitable for mobile browsers. We’ll focus on a single-player version against a simple AI to keep it straightforward.

Step 1: HTML Structure

Create a basic HTML file to define the game area, including the player’s paddle, AI paddle, and the ball.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pong Game</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="gameContainer">
        <div id="paddlePlayer"></div>
        <div id="paddleAI"></div>
        <div id="ball"></div>
    </div>
    <script src="game.js"></script>
</body>
</html>

Step 2: CSS Styling

Add styles to create visible elements for the game. This includes the game area, paddles, and the ball.

#gameContainer {
    width: 400px;
    height: 600px;
    background-color: black;
    position: relative;
    overflow: hidden;
}

#paddlePlayer, #paddleAI {
    width: 15px;
    height: 90px;
    background-color: white;
    position: absolute;
}

#paddlePlayer {
    left: 20px;
}

#paddleAI {
    right: 20px;
}

#ball {
    width: 20px;
    height: 20px;
    background-color: white;
    position: absolute;
    border-radius: 50%;
}

Step 3: JavaScript Logic

Implement the game logic, including paddle movement, ball movement, and collision detection.

document.addEventListener('DOMContentLoaded', () => {
    const paddlePlayer = document.getElementById('paddlePlayer');
    const paddleAI = document.getElementById('paddleAI');
    const ball = document.getElementById('ball');
    let ballSpeedX = 2, ballSpeedY = 2;

    // Function to move player paddle
    document.addEventListener('touchmove', (e) => {
        // Convert touch event to a position within the game container
        let touchY = e.touches[0].clientY - gameContainer.getBoundingClientRect().top;
        // Prevent the paddle from moving out of bounds
        if (touchY < gameContainer.offsetHeight - paddlePlayer.offsetHeight && touchY > 0) {
            paddlePlayer.style.top = touchY + 'px';
        }
    });

    // Ball movement
    function moveBall() {
        let ballPosX = ball.offsetLeft + ballSpeedX;
        let ballPosY = ball.offsetTop + ballSpeedY;

        // Collision with top or bottom
        if (ballPosY <= 0 || ballPosY >= gameContainer.offsetHeight - ball.offsetHeight) {
            ballSpeedY *= -1;
        }

        // Collision with player or AI paddle
        if ((ballPosX <= paddlePlayer.offsetWidth && ballPosY + ball.offsetHeight >= paddlePlayer.offsetTop && ballPosY <= paddlePlayer.offsetTop + paddlePlayer.offsetHeight) ||
            (ballPosX + ball.offsetWidth >= gameContainer.offsetWidth - paddleAI.offsetWidth && ballPosY + ball.offsetHeight >= paddleAI.offsetTop && ballPosY <= paddleAI.offsetTop + paddleAI.offsetHeight)) {
            ballSpeedX *= -1;
        }

        ball.style.left = ballPosX + 'px';
        ball.style.top = ballPosY + 'px';
    }

    setInterval(moveBall, 10);

    // Simple AI Movement (Follow the ball)
    function moveAIPaddle() {
        let middlePaddle = paddleAI.offsetTop + paddleAI.offsetHeight / 2;
        if (middlePaddle < ball.offsetTop) {
            paddleAI.style.top = paddleAI.offsetTop + 2 + 'px';
        } else if (middlePaddle > ball.offsetTop + ball.offsetHeight) {
            paddleAI.style.top = paddleAI.offsetTop - 2 + 'px';
        }
    }

    setInterval(moveAIPaddle, 20);
});

Game Mechanics Explained

  • Player Paddle Movement: The player controls their paddle by swiping up and down on the screen. The touchmove event listener converts the touch position to a paddle position within the game container.
  • Ball Movement: The ball moves continuously, bouncing off the top and bottom edges of the game container and reversing direction when it hits a paddle.
  • Simple AI Movement: The AI paddle moves towards the ball’s position, attempting to block it. This is a very basic implementation and can be improved for a more challenging game.
  • Collision Detection: Checks if the ball collides with the paddles or the edges of the game container, changing direction as necessary.

Summary

This setup provides a basic framework for a Pong game that can be played on mobile devices using touch controls to move the player’s paddle. To further develop this game, consider adding a scoring system, increasing the difficulty level over time, or implementing a more sophisticated AI for the opponent..

HTML Structure

<div id="gameContainer">
    <div id="paddlePlayer"></div>
    <div id="paddleAI"></div>
    <div id="ball"></div>
</div>
  • gameContainer: This is the area where our game takes place, representing the space in which the ball moves and where the paddles are located.
  • paddlePlayer: Your paddle. You move this up and down to hit the ball back.
  • paddleAI: The opponent’s paddle, controlled by the computer (AI).
  • ball: The object both players try to hit back and forth.

CSS Styling

#gameContainer {
    background-color: black;
}

#paddlePlayer, #paddleAI, #ball {
    background-color: white;
}
  • The game container is styled to look like the space (black background), making the white paddles and ball stand out for visibility.
  • Paddles and the ball are given a white color to contrast with the black background, making them easily visible.

JavaScript Logic

Touch Movement for Paddles

document.addEventListener('touchmove', (e) => {
    let touchY = e.touches[0].clientY - gameContainer.getBoundingClientRect().top;
    paddlePlayer.style.top = touchY + 'px';
});
  • This listens for touch movements on the screen. When you swipe up or down, it calculates the position where you touched relative to the game container’s top edge and moves your paddle (paddlePlayer) to that position.

Ball Movement

function moveBall() {
    ball.style.left = ballPosX + 'px';
    ball.style.top = ballPosY + 'px';
}
  • The ball’s position is updated continuously, simulating movement across the game container. It bounces back when hitting the game’s top or bottom edges or a paddle.

Collision Detection

  • The game checks if the ball hits the top or bottom of the game container or collides with a paddle. If it hits a paddle, the ball’s direction changes, simulating a bounce.

AI Paddle Movement

function moveAIPaddle() {
    if (middlePaddle < ball.offsetTop) {
        paddleAI.style.top = paddleAI.offsetTop + 2 + 'px';
    } else if (middlePaddle > ball.offsetTop + ball.offsetHeight) {
        paddleAI.style.top = paddleAI.offsetTop - 2 + 'px';
    }
}
  • A simple AI controls the opponent’s paddle, moving it towards the ball’s current position to block or hit it back. This AI follows the ball, trying to keep its paddle aligned with the ball’s vertical position.

Summary for Students

In this simple Pong game:

  • You control a paddle by swiping up or down on the screen, trying to hit a moving ball back towards the opponent’s side.
  • The ball moves automatically, bouncing off walls and paddles.
  • The opponent’s paddle (AI) moves on its own, trying to block your shots and bounce the ball back to you.
  • The goal is to hit the ball past the opponent’s paddle while preventing the ball from getting past yours.

This breakdown explains the basic components and logic needed to create a simple Pong game that can be played on mobile devices, focusing on touch controls for moving the paddle.

HTML Structure

The HTML sets up the visual elements of our game:

  • gameContainer: This is like our game’s “court” or “field.” It’s a defined space where all the action happens, including where the ball moves and the paddles are located.
  • paddlePlayer: This represents your paddle. You’ll move this up and down to block the ball and bounce it back toward the other side.
  • paddleAI: This is the computer’s paddle or your opponent’s paddle in a single-player game. It automatically moves to hit the ball back to you.
  • ball: This is the game’s ball, which moves back and forth between the paddles. The goal is to hit the ball past your opponent’s paddle.

CSS Styling

The CSS makes our game visually recognizable and defines how different elements (like the paddles and the ball) appear:

  • The game container is styled to be a rectangular area, typically with a black background to mimic space or a classic arcade screen.
  • Paddles are given a specific size and color (often white) so they stand out against the background, making them visible as the objects players control.
  • The ball is also styled distinctly, often as a white square or circle, to be easily seen as it moves across the game area.

JavaScript Logic

The JavaScript part is where the game’s interactivity is coded:

  • Touch Movement for Paddles: When you touch and drag (swipe) up or down on the screen, the game detects this movement and moves your paddle accordingly. This allows you to position your paddle to hit the ball back.
  • Ball Movement: The ball has its own logic to move across the screen. When the game starts, it moves in a direction until it hits a paddle or the edge of the game area, at which point it bounces off and changes direction.
  • Collision Detection: The game continuously checks if the ball has hit a paddle or gone past it. If the ball hits a paddle, it bounces back. If it goes past your paddle (or the AI’s), the other player scores a point.
  • AI Paddle Movement: In a single-player game, the computer controls the opponent’s paddle (AI paddle). It moves automatically, trying to block and return your shots. The AI’s movement is programmed to follow the ball to make the game challenging.

Gameplay Explanation

In this Pong game:

  1. You control a paddle by swiping on the screen. Your objective is to prevent the ball from getting past your paddle and to try and get it past your opponent’s paddle.
  2. The ball starts moving when the game begins, bouncing off walls and paddles according to the rules of physics coded into the game.
  3. You play against an AI opponent that moves its paddle to try and block your shots, making the game a back-and-forth challenge.

Summary for Students

The Pong game on mobile involves controlling a paddle to hit a ball back and forth with an opponent. Your goal is to score points by getting the ball past the opponent’s paddle while preventing the ball from getting past yours. The game uses touch input for moving the paddle, and everything happens within a defined game area. It’s a digital version of table tennis, offering a simple yet engaging gameplay experience.

Reference Links:

  • Java game development frameworks: (consider Lightweight Java Game Library – LWJGL if you want more direct control)
  • Touchscreen input handling in Java

Leave a Reply

Your email address will not be published. Required fields are marked *