Os exemplos deste artigo compartilham com você a demonstração do JS Snake Game, que é concluído apenas por JS e CSS para sua referência. O conteúdo específico é o seguinte
<! doctype html> <html> <meta charset = "utf-8"> <head> <style>*{margin: 0; preenchimento: 0;} .Content {Posição: Absolute; Largura: 500px; Altura: 500px; Background-Color: #212121; } .colo {width: 48px; Altura: 48px; Background-Color: #e6e6e6; borda: 1px Solid #466F85; flutuar: esquerda; } .head {/*Background-Color: #49DF85;*/Background-Image: url (./ img/22.jpg); Radio de fronteira: 10px; tamanho de fundo: 100%; Posição: Absoluto; Altura: 48px; Largura: 48px; } .Fruit {/*Background-Color: #49DF85;*/Imagem de fundo: url (./ img/fruit.jpg); tamanho de fundo: 100%; Posição: Absoluto; Altura: 48px; Largura: 48px; } .Score {Font-Family: 'Bold'; Esquerda: 600px; Posição: Absoluto; Altura: 50px; Largura: 200px; Background-Color: #212121; Cor: #FFF; } .Newbody {Position: Absolute; Largura: 48px; Altura: 48px; imagem de fundo: URL (./ img/33.jpg); tamanho de fundo: 100%; } .btn {font-family: 'Bold'; Esquerda: 600px; topo: 100px; Posição: Absoluto; Altura: 50px; Largura: 100px; Background-Color: #1193FF; Cor: #FFF; Alinhamento de texto: centro; altura da linha: 50px; Size da fonte: 20px; Cursor: Ponteiro; Radio de fronteira: 15px; } </style> </ad head> <body> <div id = "content"> </div> <div id = "stop"> pare o jogo </div> <div style = "top: 180px" id = "start"> iniciar o jogo </div </div style = "top: 380px" id = "> </p. type = "text/javascript"> // Adicione status var stop = document.getElementById ('stop'); var start = document.getElementById ("start"); var gameway = document.getElementById ('gameway'); start.oClick = function () {head.value = '2'; Incident = setInterval (move, 200);} stop.oClick = function () {clearInterval (incidente);} // var content = document.getElementById ("content"); for (var i = 0; i <100; i ++) {var div = document.createElement ("div"); div.className = "Colo"; content.appendChild (div); } var scoreID = document.getElementById ("score"); var scorenum = 0; var scoreCon = document.createElement ("p"); // var scoretext = document.createTextNode (scorenum); // scoreCon.appendChild (scoretext); scored.appendChild (scoreCon); var cabeça = null; // salve a cabeça da cobra var frut = null; // salve a fruta var dir = null; // salve a direção do corpo de cobra var = new Array (); // salve a parte adicionada do corpo da cobra var corponum = 0; // Registre quantos corpos são criados // Crie aleatoriamente cabeça e fruta na função de conteúdo createType (type) {if (type == 1) {// crie número aleatório var row = parseint (math.random () * 6 +2); var col = parseint (math.random () * 6 +2); cabeça = document.createElement ("div"); head.className = "Head"; head.style.top = linha*50+"px"; head.style.left = col*50+"px"; content.appendChild (cabeça); // head.style.top =; // head.style.left =; } if (type == 2) {// Crie um número aleatório var linha = parseint (math.random () * 6 +2); var col = parseint (math.random () * 6 +2); frut = document.createElement ("div"); fruit.className = "Fruit"; fruit.style.width = "50"; fruit.style.Height = "50"; fruit.style.backgroundColor = "#eA2000"; fruit.style.top = linha*50+"px"; fruit.style.left = col*50+"px"; content.appendChild (frutas); }} // Ligue para o método de suporte criado CreateType (1); createType (2); // função de movimento da cabeça da cobra var direção = nova matriz; // salve a direção de cada corpo recém-criado // Número de conversão var numsS = 0; // função de evento deslizante automático Move () {if (head.value! = "") {Switch (head.value) {case '1': head.style.top = head.top.offsetTop-50+"px"; quebrar; case '2': head.style.top = head.offsettop+50+"px"; quebrar; case '3': head.style.left = head.offsetleft-50+"px"; quebrar; case '4': head.style.left = head.offsetleft+50+"px"; quebrar; }} console.log (head.offsettop); if (head.offsetTop> 500) {alert ("excede o limite! Por favor, reproduza"); } // if (head == null) {// if (head.style.top <0 || head.style.top> 500 || head.style.left <0 || head.style.left> 500) {// alert ("Excede o limite! //} if (body.length! = 0) {for (var i = body.length-1; i> = 0; i-) {if (i == 0) {body [0] .Value = head.value; } else {body [i] .Value = corpo [i-1] .Value; }}} // converte a direção // se o evento após a fruta for consumido com sucesso se (head.style.top == fruit.style.top && head.style.left == fruit.style.left) {var row = parseint (math.random () * 6 +2); var col = parseint (math.random () * 6 +2); fruit.style.top = linha*50+"px"; fruit.style.left = col*50+"px"; // registro scorenum = scorenum+1; document.getElementsByTagName ('P') [0] .innerText = ""; document.getElementsByTagName ('P') [0] .innerText = scorenum; // Crie parte do corpo BodyAdd (head.style.top, head.style.left, head.value); } // Controle o corpo para seguir a parte do movimento da cabeça // Quando você tiver um corpo, você deve alterar dinamicamente o valor do corpo se (corpo.length> 0) {var Body01 = document.getElementById ('Body01'); body01.style.top = head.offsettop+"px"; body01.style.left = head.offsetleft+"px"; switch (head.value) {case '1': body01.style.top = head.offSettop+50+"px"; body01.style.left = head.offsetleft+"px"; quebrar; case '2': body01.style.top = head.offsetTop-50+"px"; body01.style.left = head.offsetleft+"px"; quebrar; case '3': body01.style.left = head.offsetleft+50+"px"; body01.style.top = head.offsettop+"px"; quebrar; case '4': body01.style.left = head.offsetleft-50+"px"; body01.style.top = head.offsettop+"px"; quebrar; }} if (body.length> 1) {body [bodynum-1] .Value = body [bodynum-2] .Value; for (var i = 1; i <corpo.length; i ++) {var nu = i+1; var BodyId = document.getElementById ('Body0'+Nu); var Body_id = document.getElementById ('Body0'+i); bodyId.style.top = body_id.offsettop+"px"; bodyId.style.left = body_id.offsetleft+"px"; switch (corpo [bodynum- (body.length-i)]. bodyId.style.left = body_id.offsetleft+"px"; quebrar; case '2': BodyId.style.top = body_id.offsettop-50+"px"; bodyId.style.left = body_id.offsetleft+"px"; quebrar; case '3': BodyId.style.left = body_id.offsetleft+50+"px"; bodyId.style.top = body_id.offsettop+"px"; quebrar; case '4': BodyId.style.left = body_id.offsetleft-50+"px"; bodyId.style.top = body_id.offsettop+"px"; quebrar; }}}} // Crie o botão Time Document.onKeydown = function () {var code = event.KeyCode; switch (código) {// Caso 38: head.value = '1'; quebrar; // Caso 40 down 40: head.value = '2'; quebrar; // Caso esquerdo 37: head.value = '3'; quebrar; // Caso 39 à direita: head.value = '4'; quebrar; console.log (head.value); }} // Aumentar o corpo Função de eventos BodyAdd (topo, esquerda, dir) {if (dir! = "") {Dir = dir; } else {dir = head.value; } // Crie corpo pela primeira vez se (BodyNum == 0) {var newbody = document.createElement ('div'); newbody.className = "Newbody"; newbody.id = "Body01"; switch (dir) {case '1': newbody.style.top = head.offsettop-50+'px'; newbody.style.left = head.offsetleft+"px"; quebrar; case '2': newbody.style.top = head.offsettop+50+'px'; newbody.style.left = head.offsetleft+"px"; quebrar; case '3': newbody.style.left = head.offsetleft-50+'px'; newbody.style.top = head.offsettop+"px"; quebrar; case '4': newbody.style.left = head.offsetleft+50+'px'; newbody.style.top = head.offsettop+"px"; quebrar; } content.appendChild (newbody); bodynum = bodynum+1; body.push (newbody); } else {// crie var newbody = document.createElement ('div'); newbody.className = "Newbody"; newBody.id = "Body0"+(Body.Length+1); switch (dir) {case '1': newbody.style.top = body [body.length-1] .offSettop-50+'px'; newbody.style.left = body [body.length-1] .offsetleft+"px"; quebrar; case '2': newbody.style.top = body [body.Length-1] .OffSettop+50+'PX'; newbody.style.left = body [body.length-1] .offsetleft+"px"; quebrar; case '3': newbody.style.left = corpo [body.length-1] .offsetleft-50+'px'; newbody.style.top = corpo [body.length-1] .offsettop+"px"; quebrar; case '4': newbody.style.left = corpo [body.length-1] .offsetleft+50+'px'; newbody.style.top = corpo [body.length-1] .offsettop+"px"; quebrar; } content.appendChild (newbody); bodynum = bodynum+1; body.push (newbody); } // body.push (content);} // excede o limite, redefina a função do evento de informação inicialize () {// redefinir a fruta var row = parseint (math.random () * 6 +2); var col = parseint (math.random () * 6 +2); fruit.style.top = linha*50+"px"; fruit.style.left = col*50+"px"; // registro de pontuação document.getElementsByTagName ('P') [0] .innerText = ""; // redefinir cobra gulosa} var incidente; incidente = setInterval (move, 200); // Adicionar operações // var btn = document.getElementById ('btn'); // btn.onclick = function () {// clearInterval (incidente); //} // </sCript> </body </tml>Ainda está sendo melhorado, e espero que seja útil para o aprendizado de todos.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.