DEV Community

Cover image for Getting Started with TCJSGame - Complete Setup Guide
Kehinde Owolabi
Kehinde Owolabi

Posted on

Getting Started with TCJSGame - Complete Setup Guide

Getting Started with TCJSGame - Complete Setup Guide

TCJSGame Banner

Introduction to TCJSGame

TCJSGame is a lightweight, powerful JavaScript game engine designed for creating 2D games with HTML5 Canvas. Whether you're a beginner looking to learn game development or an experienced developer wanting to prototype quickly, TCJSGame provides an intuitive API that makes game creation accessible and fun.

In this comprehensive setup guide, we'll walk through everything you need to start creating games with TCJSGame v3, including performance optimizations and best practices.

๐Ÿš€ What You'll Learn

  • How to set up your first TCJSGame project
  • Understanding the core architecture
  • Basic game object creation and management
  • Performance optimization techniques
  • Building your first complete game

๐Ÿ“‹ Prerequisites

Before we begin, you should have:

  • Basic knowledge of HTML and JavaScript
  • A text editor (VS Code, Sublime Text, etc.)
  • A modern web browser
  • No game development experience required!

๐Ÿ—๏ธ Step 1: Project Structure Setup

Create a simple folder structure for your project:

my-tcjsgame-project/
โ”‚
โ”œโ”€โ”€ index.html
โ”œโ”€โ”€ js/
โ”‚   โ”œโ”€โ”€ tcjsgame-v3.js
โ”‚   โ””โ”€โ”€ game.js
โ””โ”€โ”€ assets/
    โ”œโ”€โ”€ images/
    โ””โ”€โ”€ sounds/
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ป Step 2: Basic HTML Template

Create your index.html file with the following structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First TCJSGame Project</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #1a1a1a;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            font-family: Arial, sans-serif;
        }

        #game-container {
            text-align: center;
            color: white;
        }

        canvas {
            border: 3px solid #333;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
        }

        .controls {
            margin-top: 15px;
            color: #ccc;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <h1>๐ŸŽฎ My TCJSGame Project</h1>
        <p>Use arrow keys to move | Space to jump</p>
        <!-- The canvas will be inserted here automatically -->
        <div class="controls">
            <p>Built with <a href="https://tcjsgame.vercel.app" style="color: #4FC3F7;">TCJSGame v3</a></p>
        </div>
    </div>

    <!-- Include TCJSGame v3 from CDN -->
    <script src="https://tcjsgame.vercel.app/mat/tcjsgame-v3.js"></script>

    <!-- Your game code -->
    <script>
        // Our game code will go here!
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Step 3: Initializing TCJSGame

Now let's add the basic TCJSGame initialization code:

// Initialize the display
const display = new Display();

// Start the game with custom dimensions
display.start(800, 450, document.getElementById('game-container'));

// Set a beautiful gradient background
display.lgradient("bottom", "#0f2027", "#203a43, #2c5364");

// Add some styling to the canvas
display.borderColor("#34495e");
display.borderSize("3px");
display.borderStyle("solid");

console.log("๐ŸŽฏ TCJSGame v3 initialized successfully!");
console.log("Canvas size:", display.canvas.width, "x", display.canvas.height);
Enter fullscreen mode Exit fullscreen mode

๐Ÿƒ Step 4: Creating Your First Game Object

Let's create a player character and some interactive elements:

// Create player character
const player = new Component(40, 40, "#e74c3c", 100, 100, "rect");
player.physics = true;      // Enable physics
player.gravity = 0.5;       // Add gravity
player.bounce = 0.3;        // Bounce effect
player.name = "Player";     // Give it a name for debugging

// Create a platform
const platform = new Component(300, 20, "#2ecc71", 250, 350, "rect");
platform.physics = true;    // Make it solid
platform.name = "Platform";

// Create a collectible coin
const coin = new Component(20, 20, "#f1c40f", 400, 200, "rect");
coin.name = "Coin";

// Add all components to the display
display.add(player);
display.add(platform);
display.add(coin);

console.log("โœ… Game objects created successfully!");
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฎ Step 5: Adding Game Logic

Now let's add the game loop and player controls:

// Game state variables
let score = 0;
let isGameRunning = true;

// Create score display
const scoreText = new Component("20px", "impact", "white", 20, 20, "text");
scoreText.text = `Score: ${score}`;
display.add(scoreText);

// Main update function - called every frame
function update() {
    if (!isGameRunning) return;

    // Player controls
    if (display.keys[37]) { // Left arrow
        player.speedX = -5;
    } else if (display.keys[39]) { // Right arrow
        player.speedX = 5;
    } else {
        // Smooth deceleration when no key pressed
        player.speedX *= 0.9;
        if (Math.abs(player.speedX) < 0.1) player.speedX = 0;
    }

    // Jumping (Spacebar or Up arrow)
    if ((display.keys[32] || display.keys[38]) && player.gravitySpeed === 0) {
        player.speedY = -12;
    }

    // Check collision with platform
    if (player.crashWith(platform)) {
        player.hitBottom();
    }

    // Check if player collected the coin
    if (player.crashWith(coin)) {
        score += 100;
        scoreText.text = `Score: ${score}`;

        // Move coin to random position
        coin.x = Math.random() * (display.canvas.width - coin.width);
        coin.y = Math.random() * 200;

        console.log("๐Ÿ’ฐ Coin collected! Score:", score);
    }

    // Game over condition (falling off screen)
    if (player.y > display.canvas.height + 100) {
        isGameRunning = false;
        console.log("๐Ÿ’€ Game Over! Final score:", score);

        // Show game over message
        const gameOverText = new Component("30px", "impact", "red", 250, 200, "text");
        gameOverText.text = "GAME OVER - Refresh to play again!";
        display.add(gameOverText);
    }
}

console.log("๐ŸŽฎ Game logic implemented!");
Enter fullscreen mode Exit fullscreen mode

โšก Step 6: Performance Optimization

TCJSGame v3 includes several performance features. Here's how to use them effectively:

// Performance monitoring
let frameCount = 0;
let lastFpsUpdate = 0;
let currentFPS = 0;

// Create FPS counter (optional - for debugging)
const fpsText = new Component("16px", "impact", "#95a5a6", display.canvas.width - 100, 20, "text");
display.add(fpsText);

function updatePerformance() {
    frameCount++;
    const now = Date.now();

    // Update FPS counter every second
    if (now - lastFpsUpdate >= 1000) {
        currentFPS = frameCount;
        frameCount = 0;
        lastFpsUpdate = now;
        fpsText.text = `FPS: ${currentFPS}`;
    }
}

// Enhanced update function with performance monitoring
function enhancedUpdate() {
    updatePerformance(); // Monitor performance
    update();           // Original game logic

    // Optional: Add visual effects based on performance
    if (currentFPS < 30) {
        fpsText.color = "red"; // Warning: Low FPS
    } else if (currentFPS < 50) {
        fpsText.color = "yellow"; // Caution: Medium FPS
    } else {
        fpsText.color = "green"; // Good: High FPS
    }
}

// Replace the original update function
// Note: In a real scenario, you'd integrate this differently
Enter fullscreen mode Exit fullscreen mode

๐ŸŽจ Step 7: Adding Visual Polish

Let's enhance the visual appeal of our game:

// Add visual effects to the coin
function animateCoin() {
    // Make the coin pulse
    coin.width = 20 + Math.sin(display.frameNo * 0.1) * 5;
    coin.height = coin.width; // Keep it circular

    // Rotate the coin slightly
    coin.angle += 0.02;
}

// Add particle effect when collecting coins
function createCoinEffect(x, y) {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            const particle = new Component(5, 5, "#f1c40f", x, y, "rect");
            particle.physics = true;
            particle.gravity = 0.2;
            particle.speedX = (Math.random() - 0.5) * 10;
            particle.speedY = (Math.random() - 0.5) * 10;
            particle.bounce = 0.8;
            display.add(particle);

            // Remove particle after 1 second
            setTimeout(() => {
                const index = comm.findIndex(c => c.x === particle);
                if (index !== -1) comm.splice(index, 1);
            }, 1000);
        }, i * 100);
    }
}

// Enhanced collision detection with effects
function enhancedCollisionCheck() {
    if (player.crashWith(coin)) {
        score += 100;
        scoreText.text = `Score: ${score}`;

        // Create visual effect
        createCoinEffect(coin.x, coin.y);

        // Move coin with animation
        move.glideTo(coin, 0.5, 
            Math.random() * (display.canvas.width - coin.width),
            Math.random() * 200
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง Step 8: Advanced Features Setup

Now let's add some advanced TCJSGame features:

// Camera system for larger worlds
display.camera.worldWidth = 1600;
display.camera.worldHeight = 900;
display.camera.follow(player, true); // Smooth camera follow

// Sound system (if you have audio files)
const jumpSound = new Sound("assets/jump.wav");
const coinSound = new Sound("assets/coin.wav");

// Enhanced jump with sound
function enhancedJump() {
    if ((display.keys[32] || display.keys[38]) && player.gravitySpeed === 0) {
        player.speedY = -12;
        // jumpSound.play(); // Uncomment when you have audio files
    }
}

// Mobile touch support
function setupTouchControls() {
    const leftBtn = new Component(60, 60, "rgba(255,255,255,0.3)", 50, 350, "rect");
    const rightBtn = new Component(60, 60, "rgba(255,255,255,0.3)", 130, 350, "rect");
    const jumpBtn = new Component(60, 60, "rgba(255,255,255,0.3)", 650, 350, "rect");

    display.add(leftBtn);
    display.add(rightBtn);
    display.add(jumpBtn);

    // Touch event handling would go here
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ› Step 9: Debugging and Testing

Add debugging utilities to help during development:

// Debug information display
const debugInfo = new Component("14px", "impact", "#7f8c8d", 20, 40, "text");
display.add(debugInfo);

function updateDebugInfo() {
    const info = [
        `Pos: ${Math.round(player.x)},${Math.round(player.y)}`,
        `Speed: ${player.speedX.toFixed(1)},${player.speedY.toFixed(1)}`,
        `Gravity: ${player.gravitySpeed.toFixed(1)}`,
        `Frame: ${display.frameNo}`
    ];
    debugInfo.text = info.join(' | ');
}

// Enhanced final update function
function finalUpdate() {
    updatePerformance();
    updateDebugInfo();
    animateCoin();
    enhancedCollisionCheck();

    // Original game logic
    if (!isGameRunning) return;

    // Player controls
    if (display.keys[37]) player.speedX = -5;
    else if (display.keys[39]) player.speedX = 5;
    else player.speedX *= 0.9;

    enhancedJump();

    if (player.crashWith(platform)) {
        player.hitBottom();
    }

    // Game over check
    if (player.y > display.canvas.height + 100) {
        isGameRunning = false;
        const gameOverText = new Component("25px", "impact", "#e74c3c", 200, 200, "text");
        gameOverText.text = "Game Over! Final Score: " + score;
        display.add(gameOverText);
    }
}

// Replace the update function with our enhanced version
// Note: This is conceptual - in practice, you'd modify the existing update function
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฑ Step 10: Responsive Design

Make your game work well on different screen sizes:

// Responsive canvas scaling
function setupResponsiveDesign() {
    function resizeGame() {
        const container = document.getElementById('game-container');
        const maxWidth = window.innerWidth - 40;
        const maxHeight = window.innerHeight - 200;

        const scaleX = maxWidth / 800;
        const scaleY = maxHeight / 450;
        const scale = Math.min(scaleX, scaleY, 1);

        display.canvas.style.transform = `scale(${scale})`;
        display.canvas.style.margin = '20px auto';
    }

    window.addEventListener('resize', resizeGame);
    resizeGame(); // Initial call
}

// Call this after display.start()
setupResponsiveDesign();
Enter fullscreen mode Exit fullscreen mode

โœ… Complete Working Example

Here's the complete code for your first TCJSGame project:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First TCJSGame Project</title>
    <style>
        body { margin: 0; padding: 20px; background: #1a1a1a; display: flex; justify-content: center; font-family: Arial; }
        #game-container { text-align: center; color: white; }
        canvas { border: 3px solid #333; border-radius: 8px; }
        .controls { margin-top: 15px; color: #ccc; font-size: 14px; }
    </style>
</head>
<body>
    <div id="game-container">
        <h1>๐ŸŽฎ My TCJSGame Project</h1>
        <p>Use arrow keys to move | Space to jump</p>
    </div>

    <script src="https://tcjsgame.vercel.app/mat/tcjsgame-v3.js"></script>
    <script>
        // Initialize game
        const display = new Display();
        display.start(800, 450, document.getElementById('game-container'));
        display.lgradient("bottom", "#0f2027", "#203a43", "#2c5364");

        // Create game objects
        const player = new Component(40, 40, "#e74c3c", 100, 100, "rect");
        const platform = new Component(300, 20, "#2ecc71", 250, 350, "rect");
        const coin = new Component(20, 20, "#f1c40f", 400, 200, "rect");
        const scoreText = new Component("20px", "impact", "white", 20, 20, "text");

        player.physics = true; player.gravity = 0.5; player.bounce = 0.3;
        platform.physics = true;

        let score = 0;
        scoreText.text = `Score: ${score}`;

        display.add(player); display.add(platform); display.add(coin); display.add(scoreText);

        // Camera setup
        display.camera.worldWidth = 1600; display.camera.worldHeight = 900;
        display.camera.follow(player, true);

        function update() {
            // Controls
            if (display.keys[37]) player.speedX = -5;
            else if (display.keys[39]) player.speedX = 5;
            else player.speedX *= 0.9;

            if ((display.keys[32] || display.keys[38]) && player.gravitySpeed === 0) {
                player.speedY = -12;
            }

            // Collisions
            if (player.crashWith(platform)) player.hitBottom();

            if (player.crashWith(coin)) {
                score += 100;
                scoreText.text = `Score: ${score}`;
                coin.x = Math.random() * (display.canvas.width - coin.width);
                coin.y = Math.random() * 200;
            }
        }

        // Responsive design
        function resizeGame() {
            const scale = Math.min((window.innerWidth - 40) / 800, (window.innerHeight - 200) / 450, 1);
            display.canvas.style.transform = `scale(${scale})`;
            display.canvas.style.margin = '20px auto';
        }
        window.addEventListener('resize', resizeGame);
        resizeGame();
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Next Steps

Congratulations! You've successfully set up your first TCJSGame project. Here's what to explore next:

  1. Experiment with different game objects and physics properties
  2. Add more levels using the TileMap system
  3. Create enemy AI with movement patterns
  4. Implement power-ups and special abilities
  5. Add sound effects and background music

๐Ÿ“š Additional Resources

๐Ÿ†˜ Need Help?

If you encounter any issues:

  1. Check the browser console for error messages
  2. Ensure the TCJSGame script is loading correctly
  3. Verify all component properties are set properly
  4. Join the TCJSGame community for support

Happy game developing! ๐Ÿš€

Top comments (0)