Sharing is caring!

JavaScript project: maze game


JavaScript project for beginners: In this code, the maze is represented as a 2D array, where 0 represents an empty space, and 1 represents a wall.

The player’s starting position is set to (1, 1) and the goal position is set to (3, 3). The displayMaze function is used to print the current state of the maze, with the player represented by ‘P’ and the goal represented by ‘G’.


Maze Game JavaScript Code

// Define the maze grid
const maze = [
  [1, 1, 1, 1, 1],
  [1, 0, 0, 0, 1],
  [1, 1, 1, 0, 1],
  [1, 0, 0, 0, 1],
  [1, 1, 1, 1, 1]
];

// Define the player's starting position
let playerPosition = {
  x: 1,
  y: 1
};

// Define the goal position
const goalPosition = {
  x: 3,
  y: 3
};

// Function to display the maze
function displayMaze() {
  for (let i = 0; i < maze.length; i++) {
    let row = '';
    for (let j = 0; j < maze[i].length; j++) {
      if (i === playerPosition.y && j === playerPosition.x) {
        row += 'P '; // Display the player
      } else if (i === goalPosition.y && j === goalPosition.x) {
        row += 'G '; // Display the goal
      } else if (maze[i][j] === 1) {
        row += '# '; // Display walls
      } else {
        row += '  '; // Display empty spaces
      }
    }
    console.log(row);
  }
}

// Function to move the player
function movePlayer(direction) {
  let newPosition = {
    x: playerPosition.x,
    y: playerPosition.y
  };

  switch (direction) {
    case 'up':
      newPosition.y -= 1;
      break;
    case 'down':
      newPosition.y += 1;
      break;
    case 'left':
      newPosition.x -= 1;
      break;
    case 'right':
      newPosition.x += 1;
      break;
  }

//Check if the new position is within the maze boundaries and not a wall
  if (
    newPosition.x >= 0 &&
    newPosition.x < maze[0].length &&
    newPosition.y >= 0 &&
    newPosition.y < maze.length &&
    maze[newPosition.y][newPosition.x] === 0
  ) {
    playerPosition = newPosition;
    displayMaze();

    // Check if the player reached the goal
    if (
      playerPosition.x === goalPosition.x &&
      playerPosition.y === goalPosition.y
    ) {
      console.log('Congratulations! You reached the goal!');
    }
  } else {
    console.log('Invalid move!');
  }
}

The movePlayer function is responsible for handling the player’s movement. It calculates the new position based on the player’s current position and accepts a direction parameter (up, down, left, or right).

If the new position is not a wall but rather is inside the maze’s boundaries, it is checked. If the move is legitimate, the player’s position is updated, the maze is shown once more, and it is determined whether the player has reached the target.

The keydown event listener is used to handle user input in the final section of the code. It monitors the arrow keys and calls the movePlayer function when necessary.

// Display the initial maze
displayMaze();

// Handle user input
document.addEventListener('keydown', function(event) {
  switch (event.key) {
    case 'ArrowUp':
      movePlayer('up');
      break;
    case 'ArrowDown':
      movePlayer('down');
      break;
    case 'ArrowLeft':
      movePlayer('left');
      break;
    case 'ArrowRight':
      movePlayer('right');
      break;
  }
});

Maze Game HTML Code + JavaScript

This code can be executed in a web browser console or in an HTML file that also contains JavaScript. The maze will be visible, and you can use the arrow keys to find your way out of it and accomplish your goal.

<!DOCTYPE html>
<html>
<head>
  <title>Maze Game</title>
  <style>
    pre {
      font-family: monospace;
    }
  </style>
</head>
<body>
  <pre id="maze"></pre>

  <script>
    // Define the maze grid
    const maze = [
      [1, 1, 1, 1, 1],
      [1, 0, 0, 0, 1],
      [1, 1, 1, 0, 1],
      [1, 0, 0, 0, 1],
      [1, 1, 1, 1, 1]
    ];

    // Define the player's starting position
    let playerPosition = {
      x: 1,
      y: 1
    };

    // Define the goal position
    const goalPosition = {
      x: 3,
      y: 3
    };

    // Function to display the maze
    function displayMaze() {
      let mazeHTML = '';
      for (let i = 0; i < maze.length; i++) {
        let row = '';
        for (let j = 0; j < maze[i].length; j++) {
          if (i === playerPosition.y && j === playerPosition.x) {
            row += 'P '; // Display the player
          } else if (i === goalPosition.y && j === goalPosition.x) {
            row += 'G '; // Display the goal
          } else if (maze[i][j] === 1) {
            row += '# '; // Display walls
          } else {
            row += '  '; // Display empty spaces
          }
        }
        mazeHTML += row + '\n';
      }
      document.getElementById('maze').textContent = mazeHTML;
    }

    // Function to move the player
    function movePlayer(direction) {
      let newPosition = {
        x: playerPosition.x,
        y: playerPosition.y
      };

      switch (direction) {
        case 'up':
          newPosition.y -= 1;
          break;
        case 'down':
          newPosition.y += 1;
          break;
        case 'left':
          newPosition.x -= 1;
          break;
        case 'right':
          newPosition.x += 1;
          break;
      }

      // Check if the new position is within the maze boundaries and not a wall
      if (
        newPosition.x >= 0 &&
        newPosition.x < maze[0].length &&
        newPosition.y >= 0 &&
        newPosition.y < maze.length &&
        maze[newPosition.y][newPosition.x] === 0
      ) {
        playerPosition = newPosition;
        displayMaze();

        // Check if the player reached the goal
        if (
          playerPosition.x === goalPosition.x &&
          playerPosition.y === goalPosition.y
        ) {
          alert('Congratulations! You reached the goal!');
        }
      } else {
        alert('Invalid move!');
      }
    }

    // Display the initial maze
    displayMaze();

    // Handle user input
    document.addEventListener('keydown', function(event) {
      switch (event.key) {
        case 'ArrowUp':
          movePlayer('up');
          break;
        case 'ArrowDown':
          movePlayer('down');
          break;
        case 'ArrowLeft':
          movePlayer('left');
          break;
        case 'ArrowRight':
          movePlayer('right');
          break;
      }
    });
  </script>
</body>
</html>

Conclusion

So, you’ve conquered the maze and emerged victorious (or maybe you enjoyed a scenic detour through every dead end).

Congratulations! This JavaScript project has not only provided a fun and engaging challenge, but also honed your web development skills in building a classic game.

Remember, this is just the first step in your JavaScript maze mastery. You can now leverage the provided source code (best in 2024, no less!) as a launchpad for further exploration. Think about adding features like multiple difficulty levels, collectibles within the maze, or even a timer to create a fast-paced experience.

The possibilities are endless! So keep coding, keep experimenting, and most importantly, keep having fun. Happy maze-ing!


How to create a maze in js?

There are two main approaches to creating a maze in JavaScript:

  1. Grid-based approach: This method represents the maze as a 2D grid of cells. Each cell can be a wall or a passage. You can use algorithms like Depth-First Search to randomly carve paths through the grid, creating the maze.
  2. Raycasting approach: This method simulates light rays traveling through the maze. By strategically placing walls and checking for collisions with the “rays,” you can create a 3D-like perspective of the maze.

Libraries like p5.js: https://p5js.org/libraries/ or Three.js: https://threejs.org/ can be helpful for building mazes in JavaScript, especially for the 3D effect. You can find tutorials online that delve deeper into these approaches with code examples.


Can you make a 3D game in JavaScript?

Yes, you can make a 3D game in JavaScript!

While JavaScript itself isn’t the most traditional language for high-performance 3D games, powerful libraries like Three.js: [https://threejs.org/] make it possible. Three.js handles complex 3D math and rendering, allowing you to build games with:

  • 3D models
  • Lighting effects
  • Camera movement

This opens the door to creating immersive 3D experiences entirely within a web browser. However, keep in mind that 3D game development can be complex, so it requires some additional learning:

  • Understanding 3D concepts: Grasping concepts like 3D space, vectors, and rotations is crucial for building and manipulating 3D objects.
  • Learning Three.js: While Three.js offers a powerful API, it has its own learning curve. Many tutorials and resources are available online to get you started.
  • Game development principles: Regardless of the language or technology, core game development principles like game design, physics simulation, and user interaction remain essential.

If you’re interested in creating 3D games with JavaScript, Three.js is a great starting point. There’s a vibrant community and plenty of learning resources to guide you on your 3D game development journey!


Can you code a game in JavaScript?

Absolutely! JavaScript is a fantastic language for building a wide variety of games. Here’s why:

  • Versatility: JavaScript can be used to create games ranging from simple text adventures to complex, interactive experiences.
  • Accessibility: Since JavaScript runs within web browsers, your games are playable by anyone with an internet connection and a web browser, making them highly accessible.
  • Game Engines: Popular game engines like Phaser (https://phaser.io/) or Babylon.js (https://www.babylonjs.com/games/) leverage JavaScript as their core scripting language. These engines provide tools for handling:
    • Graphics
    • Physics
    • Audio
    • Other game mechanics
  • Large Community: JavaScript boasts a massive and active developer community. This means you’ll find a wealth of tutorials, resources, and forums to help you on your game development journey.

Whether you’re a beginner or a seasoned programmer, there’s a JavaScript game development path for you. Start by exploring the game engines mentioned above and dive into their tutorials. You’ll be surprised at how quickly you can bring your game ideas to life using JavaScript!


What is a maze code?

“Maze code” refers specifically to the JavaScript script that creates, displays, and allows interaction with a maze within your game. It’s essentially the programming language that brings the maze to life.

Here’s a breakdown of what maze code might typically involve:

  • Maze generation: This part of the code might use algorithms like Depth-First Search to create the maze structure, defining which parts are walls and which are passages.
  • Maze representation: The code would store this maze structure in a way the computer understands, like a 2D array or a collection of objects.
  • Maze display: The code would translate the maze structure into visuals on the screen. This could involve drawing lines for walls, displaying images for different maze elements, or using 3D libraries for a more immersive perspective.
  • User interaction: The code would handle how the user interacts with the maze. This might involve capturing keyboard presses (up, down, left, right) to move a character through the maze or handling mouse clicks to interact with specific elements within the maze.

Overall, maze code is the bridge between the maze design concept and the interactive experience you see on the screen. By understanding the core functionalities, you can start building your own maze games in JavaScript!

JavaScript ile neler yapılabilir? JavaScript öğrenmek ne kadar sürer? JavaScript hangi program? JavaScript neden popüler?¿Qué proyectos se pueden hacer con JavaScript? ¿Qué es un proyecto en JavaScript? ¿Cómo empezar un proyecto de JavaScript? ¿Qué programas se han hecho con JavaScript? Wird JavaScript noch benötigt? Was kann man alles mit JavaScript machen? Ist JavaScript für Anfänger? Wie schwierig ist JavaScript? مشاريع جافا سكريبت للمبتدئين مشاريع جافا سكريبت جاهزة pdf مشروع جافا سكريبت javascript مشروع جافا سكريبت github تفعيل جافا سكريبت على الهاتف مشاريع جافا للمبتدئين جافا سكريبت تحميل تحميل جافا سكريبت للاندرويد


0 Comments

Leave a Reply

Avatar placeholder

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