Hướng dẫn snake game html, css js source code - html trò chơi rắn, mã nguồn css js

Trò chơi javascriptsnake được tạo trong JavaScript bằng nền tảng HTML và CSS. Trò chơi rắn này trong JavaScript là một ứng dụng web máy tính để bàn. Về cơ bản, các hướng dẫn và hướng dẫn để tạo mã được bao gồm trong dự án. Ngoài ra, dự án cung cấp hướng dẫn và hướng dẫn tạo mã. Dự án cũng là nguồn mở, nơi người dùng có thể tải xuống và chỉnh sửa ZIP theo yêu cầu.JavaScript Snake Game is created in JavaScript using html and css platform. This Snake Game in JavaScript is a desktop web application. Basically, tutorials and guides for creating code are included in the project. Also, the project provides code creation tutorials and guides. The project is also open source, where users can download and edit zips as required.

Dự án mini đơn giản này cho mã trò chơi javascriptsnake hoàn chỉnh và hoàn toàn không có lỗi và & nbsp; cũng bao gồm mã nguồn có thể tải xuống & nbsp; miễn phí, chỉ cần tìm mã nguồn có thể tải xuống bên dưới và nhấp để bắt đầu tải xuống. Trước khi bạn bắt đầu nhấp vào bản tải xuống ngay trước tiên, bạn phải nhấp vào quá trình quét nhanh để tải xuống an toàn.JavaScript snake game code is complete and totally error free and  also includes a downloadable Source Code for free, just find the downloadable source code below and click to start downloading. Before you start to click the download now first you must click the Run Quick Scan for secure Download.

Ngoài ra, trò chơi rắn này sử dụng JavaScript là một trò chơi rắn cơ bản như trò chơi điển hình mà chúng ta thường chơi. Người dùng có thể chuyển các điều khiển từ máy tính để bàn của họ sang phím mũi tên trái, phím mũi tên phải, phím mũi tên lên và phím mũi tên xuống. Nếu không, bạn có thể thua trận đấu cho đến khi con rắn đạt đến ranh giới. snake game using JavaScript is a basic snake game like the typical one that we normally play. Users can switch the controls from their desktop to the left arrow key, right right arrow key, up arrow key and down arrow key. Otherwise, you can lose the match until the snake reaches the boundary.

Tôi có ở đây một danh sách & nbsp; các dự án javascript tốt nhất với mã nguồn & nbsp; miễn phí để tải xuống và tôi chắc chắn điều này có thể giúp bạn cải thiện các kỹ năng của mình trong toàn bộ lập trình JavaScript và phát triển web.Best JavaScript Projects with Source Code Free to download and I’m sure this can help you to improve your skills in JavaScript programming and web development as a whole.

Dù sao, nếu bạn muốn tăng cấp kiến ​​thức của mình trong lập trình đặc biệt & NBSP; Lập trình JavaScript, hãy thử bài viết mới này mà tôi đã thực hiện cho bạn & NBSP; Các dự án JavaScript tốt nhất có mã nguồn cho người mới bắt đầu 2021.JavaScript Programming, try this new article I’ve made for you Best JavaScript Projects With Source Code For Beginners 2021.

Để bắt đầu tạo một trò chơi rắn JavaScript với mã nguồn, hãy đảm bảo rằng bạn có bất kỳ nền tảng nào trong việc tạo A & NBSP; JavaScript, & NBSP; Bootstrap và & NBSP;Javascript Snake Game with Source Code, make sure that you have any platform in creating a JavaScriptbootstrap, and HTML installed in your computer, in my case I will use Sublime Text.

Trò chơi javascriptsnake với mã nguồn Snake Game with Source Code

Thời gian cần thiết: & nbsp; 5 phút.5 minutes.

Tại đây, các bước về cách tạo trò chơi A & nbsp; javascriptsnake với mã nguồnSteps on how to create a JavaScript Snake Game with Source Code

  • Bước 1: Mở văn bản siêu phàm.

    Đầu tiên, sau khi cài đặt IDE văn bản siêu phàm, nhấp vào Mở Mở để bắt đầu.open” to start.

    Hướng dẫn snake game html, css js source code - html trò chơi rắn, mã nguồn css js

  • Bước 2: Tạo tệp HTML.

    Tiếp theo, nhấp vào Tệp tệp và chọn Save Save As và đặt tên là Chỉ mục.htmlfile” and select “save as” and named it “index.html

    Hướng dẫn snake game html, css js source code - html trò chơi rắn, mã nguồn css js

  • Bước 3: Tạo tệp JavaScript.

    Sau đó, nhấp vào tập tin trực tuyến và chọn Save Save As và đặt tên nó là Sn Snake.jsfile” and select “save as” and named it “snake.js

    Hướng dẫn snake game html, css js source code - html trò chơi rắn, mã nguồn css js

  • Bước 4: Tạo tệp CSS.

    Cuối cùng, nhấp vào tệp tệp và chọn Save Save As và đặt tên là STYLE.CSS.file” and select “save as” and named it “style.css

    Hướng dẫn snake game html, css js source code - html trò chơi rắn, mã nguồn css js

  • Bước 5: Mã thực tế.

    Cuối cùng, bạn có thể tự do sao chép mã được đưa ra dưới đây và dán vào tệp khác nhau của bạn được tạo.

Mã cho chỉ mục.html trong trò chơi rắn trong JavaScript

Trong mã được đưa ra dưới đây, mã chứa giao diện của ứng dụng. Mã này sẽ hiển thị biểu mẫu sẽ được sử dụng trong HTML.




  
  
  
  
  Itsourcecode Snake Game
  
  
  


  

Itsourcecode Snake Game

Choose Difficulty

0

Sau khi thêm mã, bạn có thể kiểm tra mã. Đầu ra sẽ trông giống như dưới đây. (Trò chơi rắn trong JavaScript)

Hướng dẫn snake game html, css js source code - html trò chơi rắn, mã nguồn css js

Mã cho trò chơi Snake của Style.CSS trong JavaScript

Trong mã được đưa ra dưới đây, mã chứa thiết kế giao diện của ứng dụng. Mã này sẽ hiển thị biểu mẫu sẽ được sử dụng để thiết kế.

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  font: normal 15px 'Press Start 2P', cursive;
  overflow: hidden;
  color: red;
  background: black;
  user-select: none;
}

a {
  text-decoration: none;
}

.app {
  text-align: center;
}

.app .score {
  display: none;
  position: fixed;
  bottom: 0;
  right: 0;
  font-size: 65px;
  padding: 20px;
}

.app .start-screen {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 600px;
  height: 350px;
  margin: -175px 0 0 -300px;
  padding: 25px;
  background: blue;
  color: white;
  border: 5px solid #2B331B;
  z-index: 1;

}

.app .start-screen h2 {
  font-size: 50px;
  margin: 0;
}

.app .start-screen button {
  border: 3px solid #2B331B;
  background: none;
  cursor: pointer;
  color: inherit;
  outline: 0;
}

.app .start-screen button:hover,
.app .start-screen button.active {
  background: green;
  color: #728744;
}

.app .start-screen .options {
  margin-bottom: 40px;
}

.app .start-screen .options h3 {
  margin-bottom: 25px;
}

.app .start-screen .play-btn {
  font-size: 40px;
  padding: 5px 20px;
  text-transform: uppercase
}

/* Game In Progress */
.app.game-in-progress .score {
  display: block;
}

.app.game-in-progress .start-screen {
  display: none;
}

/* Game Over */
.app.game-over canvas {
  opacity: 0.3;
}

/* @Credit: https://github.com/daneden/animate.css/ */
.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes bounceIn {
  from,
  20%,
  40%,
  60%,
  80%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }

  0% {
    opacity: 0;
    -webkit-transform: scale3d(0.3, 0.3, 0.3);
    transform: scale3d(0.3, 0.3, 0.3);
  }

  20% {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    -webkit-transform: scale3d(0.9, 0.9, 0.9);
    transform: scale3d(0.9, 0.9, 0.9);
  }

  60% {
    opacity: 1;
    -webkit-transform: scale3d(1.03, 1.03, 1.03);
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    -webkit-transform: scale3d(0.97, 0.97, 0.97);
    transform: scale3d(0.97, 0.97, 0.97);
  }

  to {
    opacity: 1;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
  }
}

@keyframes bounceIn {
  from,
  20%,
  40%,
  60%,
  80%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }

  0% {
    opacity: 0;
    -webkit-transform: scale3d(0.3, 0.3, 0.3);
    transform: scale3d(0.3, 0.3, 0.3);
  }

  20% {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    -webkit-transform: scale3d(0.9, 0.9, 0.9);
    transform: scale3d(0.9, 0.9, 0.9);
  }

  60% {
    opacity: 1;
    -webkit-transform: scale3d(1.03, 1.03, 1.03);
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    -webkit-transform: scale3d(0.97, 0.97, 0.97);
    transform: scale3d(0.97, 0.97, 0.97);
  }

  to {
    opacity: 1;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
  }
}

.bounceIn {
  -webkit-animation-duration: 0.75s;
  animation-duration: 0.75s;
  -webkit-animation-name: bounceIn;
  animation-name: bounceIn;
}

Mã cho trò chơi rắn Snake.js trong JavaScript

Trong mã được đưa ra dưới đây, mã chứa chức năng giao diện của ứng dụng. Mã này sẽ hiển thị biểu mẫu sẽ được sử dụng trong HTML.

class SnakeGame {
  constructor() {
    this.$app = document.querySelector('#app');
    this.$canvas = this.$app.querySelector('canvas');
    this.ctx = this.$canvas.getContext('2d');
    this.$startScreen = this.$app.querySelector('.start-screen');
    this.$score = this.$app.querySelector('.score');

    this.settings = {
      canvas: {
        width: window.innerWidth,
        height: window.innerHeight,
        background: '#000000',
        border: '#000'
      },
      snake: {
        size: 30,
        background: '#FF0000',
        border: '#000'
      }
    };

    this.game = {
      // "direction" (set in setUpGame())
      // "nextDirection" (set in setUpGame())
      // "score" (set in setUpGame())
      speed: 100,
      keyCodes: {
        38: 'up',
        40: 'down',
        39: 'right',
        37: 'left'
      }  
    };

    this.soundEffects = {
      score: new Audio('./sounds/score.mp3'),
      gameOver: new Audio('./sounds/game-over.mp3')
    };

    this.setUpGame();
    this.init();
  }

  init() {
    // Choose difficulty
    // Rather than using "this.$startScreen.querySelectorAll('button')" and looping over the node list
    // and attaching seperate event listeners on each item, it's more efficient to just listen in on the container and run a check at runtime
    this.$startScreen.querySelector('.options').addEventListener('click', event => {
      this.chooseDifficulty(event.target.dataset.difficulty);
    });

    // Play
    this.$startScreen.querySelector('.play-btn').addEventListener('click', () => {
      this.startGame();
    });
  }

  chooseDifficulty(difficulty) {
    if(difficulty) {
      this.game.speed = difficulty;
      this.$startScreen.querySelectorAll('.options button').forEach(btn => btn.classList.remove('active'));
      event.target.classList.add('active');
    }
  }

  setUpGame() {
    // The snake starts off with 5 pieces
    // Each piece is 30x30 pixels
    // Each following piece must be n times as far from the first piece
    const x = 300;
    const y = 300;

    this.snake = [
      { x: x, y: y },
      { x: x - this.settings.snake.size, y: y },
      { x: x - (this.settings.snake.size * 2), y: y },
      { x: x - (this.settings.snake.size * 3), y: y },
      { x: x - (this.settings.snake.size * 4), y: y }
    ];

    this.food = {
      active: false,
      background: '#FFFF00',
      border: '#73AA24',
      coordinates: {
        x: 0,
        y: 0  
      }
    };

    this.game.score = 0;
    this.game.direction = 'right';
    this.game.nextDirection = 'right';
  }

  startGame() {
    // Stop the game over sound effect if a new game was restarted quickly before it could end
    this.soundEffects.gameOver.pause();
    this.soundEffects.gameOver.currentTime = 0;

    // Reset a few things from the prior game
    this.$app.classList.add('game-in-progress');
    this.$app.classList.remove('game-over');
    this.$score.innerText = 0;

    this.generateSnake();

    this.startGameInterval = setInterval(() => {
      if(!this.detectCollision()) {
        this.generateSnake();
      } else {
        this.endGame();
      }
    }, this.game.speed);

    // Change direction
    document.addEventListener('keydown', event => {
      this.changeDirection(event.keyCode);
    });
  }

  changeDirection(keyCode) {
    const validKeyPress = Object.keys(this.game.keyCodes).includes(keyCode.toString()); // Only allow (up|down|left|right)

    if(validKeyPress && this.validateDirectionChange(this.game.keyCodes[keyCode], this.game.direction)) {
      this.game.nextDirection = this.game.keyCodes[keyCode];
    }
  }

  // When already moving in one direction snake shouldn't be allowed to move in the opposite direction
  validateDirectionChange(keyPress, currentDirection) {
    return (keyPress === 'left' && currentDirection !== 'right') || 
      (keyPress === 'right' && currentDirection !== 'left') ||
      (keyPress === 'up' && currentDirection !== 'down') ||
      (keyPress === 'down' && currentDirection !== 'up');
  }

  resetCanvas() {
    // Full screen size
    this.$canvas.width = this.settings.canvas.width;
    this.$canvas.height = this.settings.canvas.height;

    // Background
    this.ctx.fillStyle = this.settings.canvas.background;
    this.ctx.fillRect(0, 0, this.$canvas.width, this.$canvas.height);
  }

  generateSnake() {
    let coordinate;

    switch(this.game.direction) {
      case 'right':
        coordinate = {
          x: this.snake[0].x + this.settings.snake.size,
          y: this.snake[0].y
        };
      break;
      case 'up':
        coordinate = {
          x: this.snake[0].x,
          y: this.snake[0].y - this.settings.snake.size
        };
      break;
      case 'left':
        coordinate = {
          x: this.snake[0].x - this.settings.snake.size,
          y: this.snake[0].y
        };
      break;
      case 'down':
        coordinate = {
          x: this.snake[0].x,
          y: this.snake[0].y + this.settings.snake.size
        };
    }

    // The snake moves by adding a piece to the beginning "this.snake.unshift(coordinate)" and removing the last piece "this.snake.pop()"
    // Except when it eats the food in which case there is no need to remove a piece and the added piece will make it grow
    this.snake.unshift(coordinate);
    this.resetCanvas();

    const ateFood = this.snake[0].x === this.food.coordinates.x && this.snake[0].y === this.food.coordinates.y;

    if(ateFood) {
      this.food.active = false;
      this.game.score += 10;
      this.$score.innerText = this.game.score;
      this.soundEffects.score.play();
    } else {
      this.snake.pop();
    }

    this.generateFood();
    this.drawSnake();
  }

  drawSnake() {
    const size = this.settings.snake.size;

    this.ctx.fillStyle = this.settings.snake.background;
    this.ctx.strokestyle = this.settings.snake.border;

    // Draw each piece
    this.snake.forEach(coordinate => {
      this.ctx.fillRect(coordinate.x, coordinate.y, size, size);
      this.ctx.strokeRect(coordinate.x, coordinate.y, size, size);
    });

    this.game.direction = this.game.nextDirection;
  }

  generateFood() {
    // If there is uneaten food on the canvas there's no need to regenerate it
    if(this.food.active) {
      this.drawFood(this.food.coordinates.x, this.food.coordinates.y);
      return;
    }

    const gridSize = this.settings.snake.size;
    const xMax = this.settings.canvas.width - gridSize;
    const yMax = this.settings.canvas.height - gridSize;

    const x = Math.round((Math.random() * xMax) / gridSize) * gridSize;
    const y = Math.round((Math.random() * yMax) / gridSize) * gridSize;

    // Make sure the generated coordinates do not conflict with the snake's present location
    // If so recall this method recursively to try again
    this.snake.forEach(coordinate => {
      const foodSnakeConflict = coordinate.x == x && coordinate.y == y;

      if(foodSnakeConflict) {
        this.generateFood();
      } else {
        this.drawFood(x, y);
      }
    });
  }

  drawFood(x, y) {
    const size = this.settings.snake.size;

    this.ctx.fillStyle = this.food.background;
    this.ctx.strokestyle = this.food.border;

    this.ctx.fillRect(x, y, size, size);
    this.ctx.strokeRect(x, y, size, size);

    this.food.active = true;
    this.food.coordinates.x = x;
    this.food.coordinates.y = y;
  }

  detectCollision() {
    // Self collison
    // It's impossible for the first 3 pieces of the snake to self collide so the loop starts at 4
    for(let i = 4; i < this.snake.length; i++) {
      const selfCollison = this.snake[i].x === this.snake[0].x && this.snake[i].y === this.snake[0].y;

      if(selfCollison) {
        return true;
      }
    }

    // Wall collison
    const leftCollison = this.snake[0].x < 0;
    const topCollison = this.snake[0].y < 0;
    const rightCollison = this.snake[0].x > this.$canvas.width - this.settings.snake.size;
    const bottomCollison = this.snake[0].y > this.$canvas.height - this.settings.snake.size;

    return leftCollison || topCollison || rightCollison || bottomCollison;
  }

  endGame() {
    this.soundEffects.gameOver.play();

    clearInterval(this.startGameInterval);

    this.$app.classList.remove('game-in-progress');
    this.$app.classList.add('game-over');
    this.$startScreen.querySelector('.options h3').innerText = 'Game Over';
    this.$startScreen.querySelector('.options .end-score').innerText = `Score: ${this.game.score}`;

    this.setUpGame();
  }
}

const snakeGame = new SnakeGame();
Về dự ánChi tiết dự án
Tên dự án : Trò chơi rắn JavaScript
Nền tảng dự án: JavaScript
Ngôn ngữ lập trình được sử dụng: PHP, JavaScript, HTML, CSS
Tên nhà phát triển: ITSOURCECODE.com
Công cụ IDE (được đề xuất): Tuyệt vời
Loại dự án : Ứng dụng web
Database: Không có
Ngày tải lên: Ngày 16 tháng 2 năm 2021

Mã nguồn có thể tải xuống

Bản tóm tắt

Tóm lại, trò chơi rắn JavaScript năm 2022 & NBSP này có mã nguồn có thể hữu ích cho sinh viên hoặc chuyên gia muốn học phát triển web bằng các công nghệ như HTML, CSS và JavaScript. Dự án này cũng có thể được sửa đổi để phù hợp với yêu cầu cá nhân của bạn. Hy vọng dự án này sẽ giúp bạn cải thiện kỹ năng của mình. Mã hóa hạnh phúc!

Những bài viết liên quan

  • Để làm danh sách & nbsp; dự án trong python với mã nguồn | Video | 2020
  • Bộ chuyển đổi tiền tệ trong Python với mã nguồn
  • Trình phát nhạc trong JavaScript với mã nguồn
  • Hoạt động CRUD trong JavaScript với mã nguồn
  • Sê -ri Fibonacci trong JavaScript với mã nguồn
  • Máy tính trong mã nguồn JavaScript
  • Hệ thống thư viện trong JavaScript với mã nguồn
  • Trình tạo mật khẩu ngẫu nhiên trong JavaScript với mã nguồn
  • Thương mại điện tử trong khung JavaScript với mã nguồn

Thắc mắc

Nếu bạn có bất kỳ câu hỏi hoặc đề xuất nào về & nbsp; trò chơi javascriptsnake với mã nguồn, xin vui lòng để lại nhận xét bên dưới.JavaScript Snake Game with Source Code, please feel free to leave a comment below.

Làm thế nào để bạn viết mã trong trò chơi rắn?

Làm thế nào để thực hiện trò chơi rắn trong Python ?..
Cài đặt pygame ..
Tạo màn hình ..
Tạo con rắn ..
Di chuyển con rắn ..
Trò chơi kết thúc khi rắn chạm vào ranh giới ..
Thêm thức ăn ..
Tăng chiều dài của con rắn ..
Hiển thị điểm số ..

Bạn có thể viết mã một trò chơi trong HTML không?

Yếu tố này là hoàn hảo để tạo ra các trò chơi trong HTML.Phần tử cung cấp tất cả các chức năng bạn cần để làm trò chơi.Sử dụng JavaScript để vẽ, viết, chèn hình ảnh, và nhiều hơn nữa, vào.. The element offers all the functionality you need for making games. Use JavaScript to draw, write, insert images, and more, onto the .

Tôi có thể tạo trò chơi với JavaScript không?

Có! JavaScript là một ngôn ngữ tuyệt vời để phát triển trò chơi, tùy thuộc vào loại trò chơi bạn muốn tạo.JavaScript là tốt nhất cho các trò chơi dựa trên web và di động.Đó cũng là một ngôn ngữ tuyệt vời cho trẻ em học vì nó thường dễ hiểu và có nhiều tài nguyên cho các lập trình viên có sẵn trực tuyến. JavaScript is a great language for game development, depending on the type of game you want to create. JavaScript is best for web-based and mobile games. It's also a great language for kids to learn because it's generally easy to understand and has plenty of resources for coders readily available online.

Bạn có thể tạo một trò chơi trình duyệt với HTML không?

Trên thực tế, các kỹ năng phát triển web hiện tại của bạn trong HTML, JavaScript, CSS, v.v. rất tốt cho một loạt các trò chơi.Khi bạn xây dựng một trò chơi với các công nghệ web, nó sẽ chạy trên hầu hết mọi thiết bị có trình duyệt.your current Web development skills in HTML, JavaScript, CSS and so on are just fine for a wide range of games. When you build a game with Web technologies, it will run on pretty much any device with a browser.