Home Web Front-end JS Tutorial js writing 'Snake' mini game_javascript skills

js writing 'Snake' mini game_javascript skills

May 16, 2016 pm 03:25 PM
js game Snake

Memories of Snake's childhood, I just learned this today, so I just made one, so I learned it too, the knowledge I need to master:

 1. Proficiency in JS functions,

2. Application of JS array,

3. Learning a small part of JS and AJAX

4. Application of splice, shift and other functions in JS,

That’s basically it. Here are the key points:
The front-end page can be laid out by itself. I provide my own layout here:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">                     
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <title>贪吃蛇</title>
  <link rel="stylesheet" type="text/css" href="./css.css">
  <script type="text/javascript" src="./jquery-1.7.2.min.js"></script>
  <script type="text/javascript" src="./js.js"></script>
</head>
<body>
  <div id="info">  
    <div id="score">0</div>
    <form action="" id="form" name="form">
      <input type="radio" name='time' value="500" checked='checked'/>简单
      <input type="radio" name='time' value="300"/>中等
      <input type="radio" name='time' value="150"/>高级
      <input type="radio" name='time' value="50"/>神速
      <input type="button" value="开始" class="button" id="start"/>
      <input type="button" value="重玩" class="button" id="res"/> 
    </form>
     
  </div>
  <div id="main">
    <div id="home">
      <!--<div style="background:url(./images/snake0.png) no-repeat;"></div>
      <div style="background:url(./images/snake1.png) no-repeat; left:20px;"></div>
      <div style="background:url(./images/snake2.png) no-repeat; left:40px;"></div>
      <div style="background:url(./images/snake3.png) no-repeat; left:60px;"></div>-->
    </div>
    <div class="wall left"></div>
    <div class="wall right"></div>
    <div class="wall top"></div>
    <div class="wall bottom"></div>
  </div>                            
</body> 
</html>
Copy after login

Here is the css code:

*{padding: 0px; margin: 0px;font-size: 12px}
body{background: #ccc}
input.button{
  width: 60px;
  cursor: pointer;
}
#info{
  width: 540px;
  height: 30px;
  margin: 30px auto 5px;
  line-height: 30px;
}
#score{
  width: 73px;
  height: 28px;
  padding-left: 64px;
  background: url(./images/score.png) no-repeat;
  float: left;
  font-size: 14px;
  font-weight: 700;
  font-style:italic;
  font-family: '微软雅黑';
}
#form{
  float: right;
}
#form input{
  vertical-align: middle;
  margin-right: 5px;
}
#main{
  width: 540px;
  height: 500px;
  margin: 0 auto;
  position: relative;
  /*background: #71a000*/
 
}
#main div{
  width: 20px;
  height: 20px;
  position: absolute;
}
#main #home{
  width: 500px;
  height: 460px;
  left: 20px;
  top: 20px;
  position: relative;
  background: url(./images/background.jpg) no-repeat;
}
#main #home div{
  position: absolute;
}
#main div.wall{
  width: 540px;
  height: 20px;
  background: url("./images/div.jpg") repeat-x;
  position: absolute;
}
#main div.top{
  left:0px;
  top:0px;
}
 
#main div.bottom{
  left:0px;
  top:480px;
}
#main div.left{
  width: 20px;
  height: 500px;
  background: url(./images/div.jpg) repeat-y;
  left:0px;
  top:0px;
}
#main div.right{
  width: 20px;
  height: 500px;
  background: url(./images/div.jpg) repeat-y;
  left:520px;
  top:0px;
}
 
.l{
  -moz-transform:rotate(0deg);  
  -o-transform:rotate(0deg);
  -webkit-transform:rotate(0deg);
  transform:rotate(0deg);
  /* IE8+ - must be on one line, unfortunately */  
  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1, M12=0, M21=0, M22=1, SizingMethod='auto expand')";   
  /* IE6 and 7 */ 
  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=1,      M12=0,      M21=0,      M22=1,      SizingMethod='auto expand');
}
.t{
  -moz-transform:  rotate(90deg);   -o-transform:   rotate(90deg);   -webkit-transform: rotate(90deg);   transform:     rotate(90deg);
  /* IE8+ - must be on one line, unfortunately */  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=-1.8369701987210297e-16, M12=-1, M21=1, M22=-1.8369701987210297e-16, SizingMethod='auto expand')";   /* IE6 and 7 */  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=-1.8369701987210297e-16,      M12=-1,      M21=1,      M22=-1.8369701987210297e-16,      SizingMethod='auto expand');
 
}
.r{
  -moz-transform:  rotate(180deg);   -o-transform:   rotate(180deg);   -webkit-transform: rotate(180deg);   transform:     rotate(180deg);
   /* IE8+ - must be on one line, unfortunately */  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=-1, M12=1.2246467991473532e-16, M21=-1.2246467991473532e-16, M22=-1, SizingMethod='auto expand')";   /* IE6 and 7 */  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=-1,      M12=1.2246467991473532e-16,      M21=-1.2246467991473532e-16,      M22=-1,      SizingMethod='auto expand');
 
}
.b{
  -moz-transform:  rotate(270deg);   -o-transform:   rotate(270deg);   -webkit-transform: rotate(270deg);   transform:     rotate(270deg);
  /* IE8+ - must be on one line, unfortunately */  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=1, M21=-1, M22=6.123233995736766e-17, SizingMethod='auto expand')";   /* IE6 and 7 */  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=6.123233995736766e-17,      M12=1,      M21=-1,      M22=6.123233995736766e-17,      SizingMethod='auto expand');
   
}
Copy after login

JS public files

var home = $('#home');
  var snakeArr = [];
  var direcation = 'l';
  var speed = 0;
  var timer = '';
  //460/20
  var rows = 23;
  var cols = 25;
  var die = false;      //用于判断是否game over
  var food = [];
  var sorce = 0;       //得分的显示
 
Copy after login

First of all, if you want to have a snake, you must create a snake,

for( var i=0; i<4; i++ ){
    //var snakeDiv = document.createElement("div");
    //snakeDiv.style = 'background:url(./images/snake' + i + '.png) no-repeat;';
    var snakeDiv = $('<div style="background:url(./images/snake' + i + '.png) no-repeat;z-index:999"></div>');
    home.append(snakeDiv);
    snakeArr[i] = {r : 10, c : 10 + i, div : snakeDiv, d : direcation};
    setPosition(snakeArr[i]); 
  }
Copy after login

After there is a snake, it is natural to move:

function move(){
    var timer = setInterval(function(){
    for( var i=snakeArr.length -1; i>0; i-- ){
      snakeArr[i].c = snakeArr[i-1].c;
      snakeArr[i].r = snakeArr[i-1].r;
      snakeArr[i].d = snakeArr[i-1].d;
      }
 
      switch(direcation){
      case 'l' :
        snakeArr[0].c--;
        snakeArr[0].d = 'l';
        break;
 
      case 'r' :
        snakeArr[0].c++;
        snakeArr[0].d = 'r';
        break;
 
      case 't' :
        snakeArr[0].r--;
        snakeArr[0].d = 't';
        break;
 
      case 'b' :
        snakeArr[0].r++;
        snakeArr[0].d = 'b';
        break;
    }
 
    //snake的方向控制
    $(window).keydown(function(event){
      switch(event.keyCode){
        case 37 :
          direcation = 'l';
          break;
 
        case 38 :
          direcation = 't';
          break;
 
        case 39 :
          direcation = 'r';
          break;
 
        case 40 :
          direcation = 'b';
          break;
      }
    });
 
      //snake事故
      //1. snake撞墙
      if( snakeArr[0].c < 0 || snakeArr[0].r < 0 || snakeArr[0].c >= cols || snakeArr[0].r >= rows ){
          clearInterval(timer);
          die = true;
          alert('GAME OVER');
      }
 
      //2. snake撞到自己
      for( var i=1; i<snakeArr.length; i++ ){
        if( snakeArr[0].c == snakeArr[i].c && snakeArr[0].r == snakeArr[i].r ){
           clearInterval(timer);
           die = true;
           alert('GAME OVER');
        }
      }
 
      //snake吃水果
      if( snakeArr[0].c == food[0].c && snakeArr[0].r == food[0].r ){
        food[0].div.css({background : 'url(./images/snake2.png) no-repeat'});
        snakeArr.splice(snakeArr.length - 1, 0, food[0]);
        food.shift();
        sorce += 10;
        $('#score').html(sorce);
      }
 
      //snake产生水果
      if( food.length == 0 ){
        createFood(); 
      }
 
 
      for(var i = 0; i < snakeArr.length; i++){
        setPosition(snakeArr[i]);
      }
    },speed);
 
}
Copy after login

Production of food:

function createFood(){
    var r = parseInt(rows * Math.random());
    var c = parseInt(cols * Math.random());
    var casrsh = false;
     
    //2个水果出现的位置不能一样
    while( food.length == 0 ){
      //判断snake的位置,不能与snake相撞
      for( var i = 0; i < snakeArr.length; i++ ){
        if( r == snakeArr[i].r && c == snakeArr[i].c ){
          casrsh = true;
        }
      }
      //当位置不重叠的时候,产生水果
      if( !casrsh ){
        var i = parseInt(4 * Math.random());
        var foodDiv = $('<div style="background:url(./images/fruit'+ i +'.png);"></div>');
        home.append(foodDiv);
        food.push({r : r, c : c, div : foodDiv});
        setPosition(food[0]);
      }
    }
     
  } 
Copy after login

Another important function is to reset the positioning:

function setPosition(obj){
    obj.div.css({left : obj.c * 20, top : obj.r * 20}); 
    obj.div.removeClass().addClass(obj.d);
  }
  createFood();  //那页面一被加载出来就显示出食物! 
Copy after login

I hope this article will be helpful to everyone in learning javascript programming.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should the CPU utilization be when gaming? What should the CPU utilization be when gaming? Feb 19, 2024 am 11:21 AM

It's common for games to slow down your computer because they consume a lot of resources. It's crucial to understand your CPU usage when gaming so you can avoid overloading it. Therefore, keeping track of appropriate CPU usage is key to keeping your gaming experience smooth. In this article, we'll look at the appropriate CPU usage you should achieve while your game is running. CPU utilization during gaming CPU utilization is an important indicator of processor workload and depends on the performance specifications of the CPU. More powerful CPUs generally have higher usage. A CPU with more cores and threads can improve the overall performance of your system. Multi-threading support helps unleash the full potential of your CPU. In games, CPU usage depends on processor utilization, which can affect the game

NAT Boost vs. Qos for games; which one is better? NAT Boost vs. Qos for games; which one is better? Feb 19, 2024 pm 07:00 PM

In today's situation where almost all games are online, it is not advisable to ignore the optimization of home network. Almost all routers are equipped with NATBoost and QoS features designed to enhance users' gaming experience. This article will explore the definition, advantages and disadvantages of NATBoost and QoS. NATBoost vs. Qos for games; which one is better? NATBoost, also known as Network Address Translation Boost, is a feature built into routers that improves their performance. It's especially important for gaming because it helps reduce network latency, which is the time it takes for data to be transferred between the gaming device and the server. By optimizing the data processing method within the router, NATBoost achieves faster data processing speed and lower latency, thus changing the

Nvgpucomp64.dll causes Windows PC games to crash; Nvgpucomp64.dll causes Windows PC games to crash; Mar 26, 2024 am 08:20 AM

If Nvgpucomp64.dll is causing your game to crash frequently, the solutions provided here may help you. This problem is usually caused by outdated or corrupted graphics card drivers, corrupted game files, etc. Fixing these issues can help you deal with game crashes. The Nvgpucomp64.dll file is associated with NVIDIA graphics cards. When this file crashes, your game will crash too. This usually happens in games like LordsoftheFallen, LiesofP, RocketLeague, and ApexLegends. Nvgpucomp64.dll crashes games on Windows PC if N

NVIDIA launches RTX HDR function: unsupported games use AI filters to achieve HDR gorgeous visual effects NVIDIA launches RTX HDR function: unsupported games use AI filters to achieve HDR gorgeous visual effects Feb 24, 2024 pm 06:37 PM

According to news from this website on February 23, NVIDIA updated and launched the NVIDIA‏‏ application last night, providing players with a new unified GPU control center, allowing players to capture wonderful moments through the powerful recording tool provided by the in-game floating window. In this update, NVIDIA also introduced the RTXHDR function. The official introduction is attached to this site: RTXHDR is a new AI-empowered Freestyle filter that can seamlessly introduce the gorgeous visual effects of high dynamic range (HDR) into In games that do not originally support HDR. All you need is an HDR-compatible monitor to use this feature with a wide range of DirectX and Vulkan-based games. After the player enables the RTXHDR function, the game will run even if it does not support HD

Introduction to how to download and install the superpeople game Introduction to how to download and install the superpeople game Mar 30, 2024 pm 04:01 PM

The superpeople game can be downloaded through the steam client. The size of this game is about 28G. It usually takes one and a half hours to download and install. Here is a specific download and installation tutorial for you! New method to apply for global closed testing 1) Search for "SUPERPEOPLE" in the Steam store (steam client download) 2) Click "Request access to SUPERPEOPLE closed testing" at the bottom of the "SUPERPEOPLE" store page 3) After clicking the request access button, The "SUPERPEOPLECBT" game can be confirmed in the Steam library 4) Click the install button in "SUPERPEOPLECBT" and download

Where is Spider Solitaire in win11 How to play Spider Solitaire game in win11 Where is Spider Solitaire in win11 How to play Spider Solitaire game in win11 Mar 01, 2024 am 11:37 AM

Friends who have played enough AAA masterpieces and mobile games, do you want to relive the computer games of your childhood? Then let’s look for Spider Solitaire in Windows 11 together! Click the Start menu on the interface, click the "All Apps" button; click "All Apps". Find and select "MicrosoftSolitaireCollection", which is Microsoft's Solitaire series game application; Solitaire series game selection. After loading is complete, enter the selection interface and find "Spider Solitaire"; select "Spider Solitaire". Although the interface has changed slightly, it is still the same as before

Thrustmaster control panel not working or displaying properly [Fixed] Thrustmaster control panel not working or displaying properly [Fixed] Feb 19, 2024 am 10:45 AM

Thrustmaster is a company that specializes in the production of gaming wheels and other gaming accessories. Its wheel products are very popular in the gaming community. Thrustmaster wheel settings can be installed and adjusted using the Thrustmaster control panel. If you encounter problems with the control panel not working or displaying, it may affect your gaming experience. Therefore, when this happens, you need to check whether the connection is normal and ensure that the software driver is installed correctly and updated to the latest version. In addition, you can also try to restart the device or reconnect the device to resolve possible failures. When you encounter problems, you can refer to Thrustmaster's official website or contact customer service for further help. How to access Thrustma

ASUS releases BIOS update to improve gaming stability on Intel's 13th/14th generation processors ASUS releases BIOS update to improve gaming stability on Intel's 13th/14th generation processors Apr 20, 2024 pm 05:01 PM

According to news from this site on April 20, ASUS recently released a BIOS update, which improves instability such as crashes when running games on Intel's 13th/14th generation processors. This site previously reported that players reported problems including that when running the PC demo version of Bandai Namco's fighting game "Tekken 8", even if the computer has sufficient memory and video memory, the system will crash and prompt an error message indicating insufficient memory. Similar crashing issues have also appeared in many games such as "Battlefield 2042", "Remnant 2", "Fortnite", "Lord of the Fallen", "Hogwarts Legacy" and "The Finals". RAD published a long article in February this year, explaining that the game crash problem is a combination of BIOS settings, high clock frequency and high power consumption of Intel processors.

See all articles