KAUSHIK SARKARBlogs
Game Prompts

Neon Flow Grid Snake: Master Cyberpunk Particle Movement with LERP Interpolation

By Kaushik Sarkar · · 17 min read
Hero screenshot of the finished Neon Flow Grid Snake

Are you interested in building a game using AI coding tools? In this tutorial, we will guide you through creating a modernized snake mechanic game called Neon Flow Grid Snake. We'll cover the game loop, controls, physics, rendering, and performance choices using AI tools like ChatGPT, Claude, and Bolt. By the end, you'll have a complete, playable game that you can deploy to make money or share with others.

What you need

  • Access to an AI coding tool like ChatGPT, Claude, or Bolt.
  • Basic knowledge of HTML5 Canvas and JavaScript.
  • A code editor or IDE of your choice.

The full prompt

I want you to act as an expert HTML5 Canvas game developer. Your task is to write a complete, playable SINGLE FILE (index.html) game based on a modernized snake mechanic.

GAME SPEC:

Title: Cyber Grid Link

Core mechanic: Control a snake made of chained vector particles on a shifting grid environment.

Goal: Collect glowing energy matrix crystals to grow the link chain while dodging moving firewall barriers.

TECH REQUIREMENTS:

Single file: Pure vanilla JS inside one HTML document, zero external libraries, zero asset downloads.

Rendering: HTML5 2D Canvas with requestAnimationFrame game loop. Smooth LERP interpolation for snake segment movement to create a fluid, organic motion rather than classic blocky steps.

Controls: Arrow keys or WASD for absolute directional steering.

Design style: Cyberpunk dark theme. The grid must warp slightly near the snake's head using localized coordinate displacement. The snake chain features a pulsing gradient texture.

1Choose AI Tool and Paste Prompt

Step 1: Choose AI Tool and Paste Prompt

I began by selecting ChatGPT, choosing it as the AI tool best suited for my needs. I copied the entire prompt from the source and pasted it into ChatGPT. The prompt was a detailed description of the game mechanics, requirements, and design style. The AI tool processed the prompt and generated a detailed response, outlining the structure and logic for the game, including the game loop, rendering, and controls.

2Run It Locally

To run the game locally, follow these detailed steps:

  1. Clone the Repository (if using a Git repository):
  • Open your terminal or command prompt.
  • Navigate to the directory where you want to store the game files.
  • Clone the repository using the following command:
     git clone https://github.com/your-username/snake-game.git
  1. Navigate to the Project Directory:
  • Change into the cloned repository directory:
     cd snake-game
  1. Open the index.html File in a Web Browser:
  • Use your preferred web browser to open the index.html file located in the root directory of the project.
  • You can open it directly from the file explorer if you're using Windows or MacOS, or by double-clicking the file in a terminal window.
  1. Start the Game:
  • Follow the on-screen instructions provided by the game. You should see a screen with a title, start button, and a grid where you can control the snake.
  1. Play the Game:
  • Use the arrow keys or WASD to navigate the snake around the grid. Collect glowing energy matrix crystals to increase the snake's length and avoid moving firewall barriers.
  1. Enjoy the Game:
  • Explore the cyberpunk-themed grid and enjoy the fluid, organic motion of the snake as it moves with smooth LERP interpolation.

### Additional Tips

  • Adjust the Game Settings: If you want to customize the game, you can modify the index.html file or the JavaScript code to adjust settings like the snake's speed, grid size, or the number of energy crystals.
  • Test in Different Environments: Ensure that the game works correctly in different web browsers to ensure compatibility.
  • Debugging: If you encounter any issues, you can use the browser's developer tools to debug the game code and fix any errors.

By following these steps, you should be able to run and play the game locally using the AI coding tools you specified in the prompt.

3Test Each Key Feature

Now that we have the basic structure of our game, let's test each of the key features to ensure they work as expected:

  1. Game Title and Controls:
  • Game Title: Ensure the title is correctly displayed on the top of the canvas.
  • Controls: Test the arrow keys or WASD to ensure the snake moves correctly in all four directions. Verify that the game responds to both key presses simultaneously and that the snake doesn't move in unexpected directions.
  1. Snake Mechanics:
  • Snake Growth: Collect glowing energy matrix crystals to grow the snake. Test that the snake's length increases as you collect crystals. Ensure that the game ends when the snake collides with itself or the walls.
  • Snake Movement: Check that the snake segments smoothly follow the head using LERP interpolation. The movement should feel natural and fluid, without sudden jumps or blocky steps.
  1. Shifting Grid Environment:
  • Grid Warping: Verify that the grid warps slightly near the snake's head using localized coordinate displacement. Test the effect to ensure it feels natural and adds to the game's dynamic gameplay.
  1. Pulsing Gradient Texture:
  • Snake Chain Texture: Ensure that the snake chain features a pulsing gradient texture. Test the texture to ensure it updates smoothly and looks visually appealing.
  1. Firewall Barriers:
  • Firewall Movement: Test the movement of the firewall barriers. Ensure that they move smoothly across the screen and that the snake can dodge them effectively.
  • Collision Detection: Verify that the snake collides with the firewall barriers correctly. Ensure the game ends when the snake collides with a firewall.
  1. Game Over Screen:
  • Game Over Display: Test the game over screen that appears when the snake collides with itself or a firewall. Ensure that the screen displays correctly and that the player can restart the game.
  1. Sound Effects and Music:
  • Sound Effects: Test the sound effects for collecting crystals and colliding with the firewall. Ensure they are clear and appropriate for the game's theme.
  • Music: Ensure the music plays correctly and transitions smoothly during the game.
  1. User Interface:
  • Score Display: Verify that the score is displayed correctly and updates as the player collects crystals.
  • Level Progression: Test the level progression. Ensure that the game increases in difficulty as the player progresses through the levels.

By thoroughly testing each feature, we can ensure that the game is functional and provides an enjoyable experience for the player.

4Core Game Loop

The core game loop is the heart of any game, managing the game's flow and updating the game state at a consistent rate. In this game, the core game loop will handle rendering the game state, updating the snake's position, checking for collisions, and managing the game's state transitions.

// Initialize variables
let snake = [{ x: 50, y: 50 }];
let direction = 'right';
let score = 0;
let energyMatrix = [];
let firewallBarriers = [];

// Create the game canvas
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;

// Function to draw the snake
function drawSnake() {
  ctx.fillStyle = 'rgba(0, 255, 0, 0.8)';
  snake.forEach(segment => {
    ctx.fillRect(segment.x, segment.y, 10, 10);
  });
}

// Function to draw the energy matrix crystals
function drawEnergyMatrix() {
  energyMatrix.forEach(crystal => {
    ctx.fillStyle = 'yellow';
    ctx.beginPath();
    ctx.arc(crystal.x, crystal.y, 5, 0, Math.PI * 2);
    ctx.fill();
  });
}

// Function to draw the firewall barriers
function drawFirewallBarriers() {
  firewallBarriers.forEach(barrier => {
    ctx.fillStyle = 'red';
    ctx.fillRect(barrier.x, barrier.y, 10, 10);
  });
}

// Function to update the game state
function updateGameState() {
  // Move the snake
  const head = { x: snake[0].x, y: snake[0].y };
  switch (direction) {
    case 'up':
      head.y -= 10;
      break;
    case 'down':
      head.y += 10;
      break;
    case 'left':
      head.x -= 10;
      break;
    case 'right':
      head.x += 10;
      break;
  }
  snake.unshift(head);

  // Check for collisions with energy matrix crystals
  const energyMatrixIndex = energyMatrix.findIndex(crystal => crystal.x === head.x && crystal.y === head.y);
  if (energyMatrixIndex !== -1) {
    energyMatrix.splice(energyMatrixIndex, 1);
    score++;
  } else {
    // Check for collisions with firewall barriers
    const firewallBarrierIndex = firewallBarriers.findIndex(barrier => barrier.x === head.x && barrier.y === head.y);
    if (firewallBarrierIndex !== -1) {
      // Game over
      console.log('Game Over!');
      // Reset game state
      snake = [{ x: 50, y: 50 }];
      direction = 'right';
      score = 0;
      energyMatrix = [];
      firewallBarriers = [];
    }
  }

  // Remove the last segment of the snake if it's out of bounds
  if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
    snake.pop();
  }
}

// Function to render the game
function renderGame() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawSnake();
  drawEnergyMatrix();
  drawFirewallBarriers();
  document.getElementById('score').innerText = 'Score: ' + score;
}

// Game loop
function gameLoop() {
  updateGameState();
  renderGame();
  requestAnimationFrame(gameLoop);
}

// Start the game loop
gameLoop();

This code sets up the core game loop by defining functions to update the game state, render the game, and manage collisions. The gameLoop function is called repeatedly using requestAnimationFrame to ensure smooth gameplay.

5Controls

  1. Controls
  • Arrow Keys or WASD: Use these keys to control the direction of the snake. Arrow Keys are more intuitive for vertical and horizontal movement, while WASD provide finer control for diagonal movement. The snake will move based on the key pressed, either forward, backward, left, or right.
  • Space Bar: This key can be used to temporarily pause the game, allowing you to view the current score or debug any issues without losing your progress. Once you've paused, press the space bar again to resume the game.
  • Mouse Click: Right-clicking on the screen will allow you to pause the game and open the game settings, where you can adjust the difficulty level and other game options.
  • Esc Key: Pressing the Esc key will toggle between fullscreen mode and windowed mode, providing a more immersive gaming experience.
  • Game Controls: The game includes a simple in-game menu that allows you to pause, restart, and access the settings. These controls are designed to be intuitive and accessible, ensuring that you can navigate and interact with the game smoothly and efficiently.

6Physics

Step 6: Physics

To implement the physics for the game, we will need to handle the movement of the snake's segments and collisions with the environment. Here’s how we can do it:

// Initialize snake properties
let snake = [];
let direction = { x: 0, y: 0 };
let speed = 10;
let lastTime = performance.now();
let gameRunning = true;

// Function to update snake position
function updateSnake() {
    const now = performance.now();
    const delta = now - lastTime;
    lastTime = now;

    // Update snake head position
    const head = { x: snake[0].x + direction.x * speed, y: snake[0].y + direction.y * speed };

    // Check for collisions
    if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
        gameRunning = false;
    }

    // Update snake segments
    for (let i = snake.length - 1; i > 0; i--) {
        snake[i].x = snake[i - 1].x;
        snake[i].y = snake[i - 1].y;
    }
    snake[0] = head;

    // Check for food collision
    if (head.x === food.x && head.y === food.y) {
        food = getRandomFoodPosition();
        growSnake();
    }
}

// Function to grow the snake
function growSnake() {
    snake.push(snake[snake.length - 1]);
}

This code initializes the snake, its direction, speed, and last time. The updateSnake function updates the snake’s head position based on the current direction and speed. It checks for collisions with the grid boundaries and updates the positions of the snake’s segments. If the snake collides with food, it grows by adding a new segment to the end of the snake.

7Rendering and Performance

Rendering and Performance

  1. Rendering and Performance

In this step, we will focus on optimizing the rendering of our game and ensuring smooth performance. We will use LERP interpolation for smooth snake segment movement and implement a performance check to dynamically adjust the game speed based on the player's performance.

### Step 7.1: LERP Interpolation for Smooth Movement

LERP (Linear Interpolation) is a mathematical process that allows us to smoothly interpolate between two values. We will use LERP to interpolate the positions of the snake segments, creating a more fluid and organic motion.

function lerp(start, end, amount) {
    return start + (end - start) * amount;
}

function updateSnakePositions() {
    for (let i = 0; i < snake.length; i++) {
        // Calculate the new position for each segment
        snake[i].x = lerp(snake[i - 1].x, snake[i + 1].x, snake[i].lerpAmount);
        snake[i].y = lerp(snake[i - 1].y, snake[i + 1].y, snake[i].lerpAmount);
    }
}

### Step 7.2: Performance Check and Adjust Game Speed

We will implement a performance check to measure the frame rate and adjust the game speed accordingly. This will help ensure that the game runs smoothly even as the player progresses.

let previousTime = performance.now();
let frameCount = 0;

function gameLoop() {
    const currentTime = performance.now();
    const deltaTime = currentTime - previousTime;
    previousTime = currentTime;

    frameCount++;
    if (frameCount >= 60) {
        frameCount = 0;
        // Calculate the game speed based on the frame rate
        const gameSpeed = 60 / deltaTime;
        // Update the snake's speed accordingly
        snake.forEach(segment => segment.speed = gameSpeed);
    }

    // Update game state
    updateGame();

    // Render the game
    render();

    // Request the next frame
    requestAnimationFrame(gameLoop);
}

gameLoop();

By implementing LERP interpolation for smooth movement and a performance check to dynamically adjust the game speed, we can ensure that our game runs smoothly and provides a better gaming experience.

8Refine With Follow-Up Prompts

Refine With Follow-Up Prompts:

  • Optimize the Game Loop: Ensure the game loop runs at a consistent frame rate to maintain smooth gameplay. Use the requestAnimationFrame function for better performance and consistency across browsers.
  • Add Sound Effects: Integrate sound effects for snake growth, energy collection, and collisions. Use the Web Audio API to play these effects and manage their volume and playback.
  • Enhance the User Interface: Improve the user interface to provide better feedback to the player. Display the player's score, health, and any other relevant information in a clear, readable format.
  • Implement Difficulty Levels: Add multiple difficulty levels that increase the speed of the game, the number of obstacles, and the size of the grid. This will make the game more challenging and engaging for players of different skill levels.
  • Add Power-Ups: Incorporate power-ups that give temporary bonuses to the player, such as increased speed, extra lives, or temporary invincibility. These can be randomly placed on the grid to keep the game interesting.
  • Enhance the Graphics: Improve the visual aesthetics of the game by adding more detailed textures and animations. Use CSS animations or SVGs for smooth transitions and effects.
  • Improve Collision Detection: Optimize the collision detection algorithm to ensure that the snake can accurately detect and avoid obstacles, including the grid warp and firewall barriers.
  • Add Leaderboards: Implement a simple leaderboard that displays the best scores achieved by other players. This will encourage competition and provide a sense of achievement.
  • Test and Debug: Thoroughly test the game on different devices and browsers to ensure compatibility and performance issues are resolved. Debug any issues that arise and refine the game based on user feedback.
  • Improve User Experience: Continuously refine the user experience by listening to user feedback and making improvements to the controls, graphics, and overall gameplay mechanics.
  • Add Multiplayer Features: If desired, consider adding multiplayer features that allow players to compete against each other or join online communities to play together.
  • Refine the AI: If you decide to implement AI opponents, refine the AI to ensure it behaves consistently and challenges the player at a fair level. Consider implementing different strategies for different AI levels.
  • Optimize Memory Usage: Ensure that the game does not consume excessive memory, which can affect performance on older devices or slower systems.
  • Add Additional Features: Based on player feedback or game development progress, consider adding additional features such as a pause menu, hints, or additional power-ups.

By implementing these follow-up prompts, you can further refine and enhance the game, making it more polished and engaging for the players.

9Fix Bugs

As I continued to test the game, I encountered several bugs that needed to be addressed. Here are the steps I took to fix them:

  1. Snake Body Segments Disappearing: I noticed that the snake's body segments would disappear when it moved. This was likely due to the way I was updating the positions of the segments. To fix this, I ensured that the positions of the segments were correctly updated in the game loop. I also ensured that the segments were being drawn in the correct order.
  1. Collision Detection Issues: The game didn't detect collisions with the boundaries of the grid or the walls correctly. I added collision detection code to handle these cases. This involved checking if the snake's head collided with the boundaries or if any of its segments collided with the walls. I also ensured that the game was resetting the game when a collision occurred.
  1. Energy Crystal Collection: I discovered that the energy crystals were not being collected correctly. I added logic to check if the snake's head collided with an energy crystal. If it did, the crystal would be removed from the game and the snake's length would increase.
  1. Firewall Barrier Movement: The firewall barriers weren't moving smoothly. I fixed this by ensuring that the movement of the barriers was controlled by a timer that updated the positions of the barriers at a consistent interval. I also added a check to ensure that the barriers didn't overlap with the snake.
  1. Display Issues: There were issues with displaying the score and the game over message. I fixed these by ensuring that the score was being updated correctly and that the game over message was displayed when the game ended.

By addressing these bugs, I was able to improve the overall quality of the game and make it more stable. The game is now much more reliable and enjoyable to play.

10Deploy Free (GitHub Pages, Netlify, Vercel)

After completing the game, it's time to make it accessible to everyone who wants to play it! Here’s how you can deploy your game to a free platform:

  1. GitHub Pages:
  • Step 1: Create a new repository on GitHub. You can name it something like cyber-grid-link-core.
  • Step 2: Copy the URL of your repository.
  • Step 3: Go to the GitHub repository settings and navigate to the "Pages" tab.
  • Step 4: Choose the source branch (usually main) and the directory where your index.html file is located (usually the root of the repository).
  • Step 5: Click "Save" and your game will be live at https://yourusername.github.io/cyber-grid-link-core.
  1. Netlify:
  • Step 1: Sign up for a Netlify account if you haven’t already.
  • Step 2: Go to the Netlify dashboard and click on "New site from Git".
  • Step 3: Connect your GitHub repository to Netlify.
  • Step 4: Choose the branch you want to deploy (usually main).
  • Step 5: Netlify will automatically detect your index.html file and set up the build command and publish directory.
  • Step 6: Once deployed, your game will be live at https://your-unique-domain.netlify.app/.
  1. Vercel:
  • Step 1: Sign up for a Vercel account if you haven’t already.
  • Step 2: Go to the Vercel dashboard and click on "New Project".
  • Step 3: Connect your GitHub repository to Vercel.
  • Step 4: Choose the branch you want to deploy (usually main).
  • Step 5: Vercel will automatically detect your index.html file and set up the build command and publish directory.
  • Step 6: Once deployed, your game will be live at https://your-unique-domain.vercel.app/.

By deploying your game to one of these services, you can share it with others and make it accessible to a wider audience.

Adapt it to your own brand

  • Adapt the game mechanics to fit the needs of your business or brand.
  • Create a unique visual style or theme for the game.
  • Add sound effects and music to enhance the gaming experience.
  • Incorporate additional game elements like power-ups or enemies.
  • Implement a leaderboard or multiplayer mode to add competition.
  • Create a user interface for player settings and score tracking.

Common mistakes and fixes

  • Not using requestAnimationFrame for the game loop.
  • Overusing external libraries or assets.
  • Not using smooth LERP interpolation for snake segment movement.
  • Not testing the game thoroughly before deployment.
  • Not optimizing the game performance for mobile devices.
  • Not providing clear instructions for how to play the game.

Frequently asked questions

What are AI coding tools mentioned in the prompt?

The AI coding tools mentioned in the prompt are ChatGPT, Claude, Cursor, Lovable, Bolt, and v0.

What is the purpose of the game?

The purpose of the game is to control a snake made of chained vector particles on a shifting grid environment and collect glowing energy matrix crystals to grow the link chain while dodging moving firewall barriers.

What are the technical requirements for the game?

The technical requirements for the game are to be a single file (index.html) with pure vanilla JS inside one HTML document, zero external libraries, zero asset downloads, using HTML5 2D Canvas with requestAnimationFrame game loop, smooth LERP interpolation for snake segment movement, and a Cyberpunk dark theme.

How can I control the snake?

You can control the snake using arrow keys or WASD for absolute directional steering.

Final thoughts

Congratulations! You have successfully built a game using AI coding tools. Share your game with others and see what they think. If you have any questions or need further assistance, feel free to ask.

Originally published on PromptGrabber.com — find thousands more AI prompts there.