Online Game Development Course (4)

Hello, and welcome to the fourth session of our online Snake game development course. Today, we will learn about front-end development, focusing on game rendering with Canvas and user interface design.

Easy-to-Follow Table of Contents

  1. Setting Up HTML Structure
  2. Applying CSS Styling
  3. Configuring Canvas and Rendering the Game
  4. Implementing User Interface and Displaying Game State
  5. Applying Responsive Design
  6. Adding Touch Controls
  7. Implementing the Game Over Screen
    Conclusion

1. Setting Up HTML Structure

First, let’s create the basic HTML structure.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiplayer Snake Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="gameContainer">
        <div id="menu">
            <button id="createRoom">Create Room</button>
            <input type="text" id="roomCodeInput" placeholder="Enter Room Code">
            <button id="joinRoom">Join Room</button>
        </div>
        <canvas id="gameCanvas"></canvas>
        <div id="playerInfo"></div>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
    <script src="game.js"></script>
</body>
</html>

2. Applying CSS Styling

Let’s enhance the appearance of the game with CSS.

body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

#gameContainer {
    text-align: center;
}

#menu {
    margin-bottom: 20px;
}

button {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}

input {
    padding: 10px;
    font-size: 16px;
}

#gameCanvas {
    border: 2px solid #333;
}

#playerInfo {
    margin-top: 20px;
    font-size: 18px;
}

3. Configuring Canvas and Rendering the Game

We will use the p5.js library to render the game.

let canvas;
const canvasSize = 400;
const gridSize = 20;

function setup() {
    canvas = createCanvas(canvasSize, canvasSize);
    canvas.parent('gameCanvas');
    frameRate(10);
}

function draw() {
    background(51);
    if (gameState) {
        drawFood();
        drawPlayers();
    }
}

function drawFood() {
    fill(255, 0, 0);
    for (let food of gameState.foods) {
        rect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
    }
}

function drawPlayers() {
    for (let player of gameState.players) {
        if (player.alive) {
            fill(player.color);
            for (let segment of player.segments) {
                rect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
            }
        }
    }
}

4. Implementing User Interface and Displaying Game State

We will add functionality to display the game state and player information.

function updatePlayerInfo() {
    const playerInfoDiv = document.getElementById('playerInfo');
    playerInfoDiv.innerHTML = '';

    if (gameState) {
        gameState.players.forEach((player, index) => {
            const playerDiv = document.createElement('div');
            playerDiv.textContent = `Player ${index + 1}: ${player.score}`;
            playerDiv.style.color = player.color;
            playerInfoDiv.appendChild(playerDiv);
        });
    }
}

socket.on('gameState', (newGameState) => {
    gameState = newGameState;
    updatePlayerInfo();
});

5. Applying Responsive Design

Let’s make the design responsive to accommodate different screen sizes.

@media (max-width: 600px) {
    #gameContainer {
        width: 100%;
    }

    #gameCanvas {
        width: 100%;
        height: auto;
    }

    button, input {
        width: 100%;
        margin-bottom: 10px;
    }
}

6. Adding Touch Controls

We will add touch controls to make the game playable on mobile devices.

let touchStartX = 0;
let touchStartY = 0;

function touchStarted() {
    touchStartX = mouseX;
    touchStartY = mouseY;
    return false;
}

function touchEnded() {
    const diffX = mouseX - touchStartX;
    const diffY = mouseY - touchStartY;

    if (Math.abs(diffX) > Math.abs(diffY)) {
        if (diffX > 0) {
            changeDirection('RIGHT');
        } else {
            changeDirection('LEFT');
        }
    } else {
        if (diffY > 0) {
            changeDirection('DOWN');
        } else {
            changeDirection('UP');
        }
    }
    return false;
}

function changeDirection(direction) {
    socket.emit('changeDirection', { roomCode, direction });
}

7. Implementing the Game Over Screen

We will add a screen to display the results when the game ends.

function showGameOver(winners) {
    const gameOverDiv = document.createElement('div');
    gameOverDiv.id = 'gameOver';
    gameOverDiv.innerHTML = `
        <h2>Game Over</h2>
        <p>Winner: Player ${winners[0].number}</p>
        <button onclick="restartGame()">Play Again</button>
    `;
    document.body.appendChild(gameOverDiv);
}

function restartGame() {
    document.getElementById('gameOver').remove();
    socket.emit('restartGame', roomCode);
}

socket.on('gameOver', (winners) => {
    showGameOver(winners);
});

Conclusion

In this post, we focused on front-end development, including game rendering with Canvas, user interface design, responsive web design, and touch control implementation. These elements significantly enhance the user experience and make the game enjoyable on various devices.

In the next post, we will delve deeper into backend server development, covering server setup with Express.js and implementing RESTful APIs. Thank you!

Leave a Reply

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