2016-12-23 3 views
-3

В настоящее время я создаю игру с HTML/SCSS и jQuery/JavaScript.JavaScript «если» условия не работают

У меня есть символ div, который перемещается при нажатии стрелок клавиатуры с помощью jQuery. Это работает с оператором if, который определяет, где игрок может перемещаться, поэтому он не может выбраться из более крупного div.

Я хотел создать чистую версию JavaScript игры, и игрок может перемещаться и все, кроме случаев, когда я помещаю операторы if, чтобы он не вышел из границы.

Вот мой CodePen

Вот моя игра (до сих пор) с JQuery:

var jQueryVersion = function() { 
 
    var game_anim = function() { 
 

 
    var level = [ 
 
     [0, 1, "l", 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, "l", "l", 1], 
 
     [0, 0, 0, 0, 2, 2, 2, 2, 2, 2], 
 
     [0, 0, 0, 0, 0, 3, 3, 0, 3], 
 
    ]; 
 

 
    var $player = $("#player"); 
 
    var $game = $("#game"); 
 

 
    for (var i = 0; i < level.length; i++) { 
 
     for (var j = 0; j < level[i].length; j++) { 
 

 
     var n = level[i][j]; 
 

 
     if (n === 1) { 
 
      $("<div>", { 
 
      "class": "block stone ypos-0 xpos-" + [j] 
 
      }).appendTo("#game"); 
 

 
     } 
 

 
     if (n === 2) { 
 
      $("<div>", { 
 
      "class": "block stone ypos-1 xpos-" + [j] 
 
      }).appendTo("#game"); 
 
     } 
 
     if (n === 3) { 
 
      $("<div>", { 
 
      "class": "block stone ypos-2 xpos-" + [j] 
 
      }).appendTo("#game"); 
 

 
     } 
 

 
     if (n === 4) { 
 
      $("<div>", { 
 
      "class": "block stone ypos-3 xpos-" + [j] 
 
      }).appendTo("#game"); 
 
     } 
 

 
     if (n === "l") { 
 
      $("<div>", { 
 
      "class": "block lava ypos-" + [i] + " xpos-" + [j] 
 
      }).appendTo("#game"); 
 
     } 
 

 
     } 
 
    } 
 

 
    $(document).keydown(function(event) { // keycodes: left = 37, right = 39 
 
     if (event.which == 39 || event.which == 68) { // right arrow or D 
 
     if ($player.position().left < $game.width() - $player.width()) { 
 
      $player.css("left", "+=10"); 
 
     } 
 
     } 
 
     if (event.which == 37 || event.which == 81 || event.which == 65) { // left arrow or Q on AZERTY or A on QWERTY 
 
     if ($player.position().left > 0) { 
 
      $player.css("left", "-=10"); 
 
     } 
 
     } 
 

 
     if (event.which == 38) { 
 
     if ($player.position().top > 0) { 
 
      $player.css("top", "-=10"); 
 
     } 
 
     } 
 
     if (event.which == 40) { 
 
     if ($player.position().top < 500 - $player.height()) { 
 
      $player.css("top", "+=10"); 
 
     } 
 
     } 
 

 
    }); 
 

 

 
    } 
 

 
    $(document).ready(function() { 
 

 
    game_anim(); 
 

 
    }); 
 
} 
 
jQueryVersion();
#game { 
 
    position: absolute; 
 
    left: calc((100% - 800px)/2); 
 
    height: 500px; 
 
    width: 800px; 
 
    border: 2px solid black; 
 
} 
 
.block { 
 
    height: 50px; 
 
    width: 50px; 
 
    position: absolute; 
 
} 
 
.stone { 
 
    background-color: black; 
 
} 
 
.lava { 
 
    background-color: red; 
 
} 
 
#player { 
 
    height: 50px; 
 
    width: 50px; 
 
    background-color: #3747C0; 
 
    bottom: 0; 
 
    position: absolute; 
 
} 
 
#player .eyes { 
 
    border-radius: 50%; 
 
    background-color: white; 
 
    position: absolute; 
 
    height: 10px; 
 
    width: 10px; 
 
} 
 
#player .eye_R { 
 
    left: 7px; 
 
    top: 10px; 
 
} 
 
#player .eye_L { 
 
    left: 32px; 
 
    top: 10px; 
 
} 
 
#player .mouth { 
 
    height: 8.5px; 
 
    width: 32px; 
 
    background-color: white; 
 
    border-radius: 5px; 
 
    left: calc((50px - 32px)/2); 
 
    bottom: 10px; 
 
    position: absolute; 
 
} 
 
.ypos-0 { 
 
    bottom: 0px; 
 
    position: absolute; 
 
} 
 
.ypos-1 { 
 
    bottom: 50px; 
 
    position: absolute; 
 
} 
 
.ypos-2 { 
 
    bottom: 100px; 
 
    position: absolute; 
 
} 
 
.ypos-3 { 
 
    bottom: 150px; 
 
    position: absolute; 
 
} 
 
.ypos-4 { 
 
    bottom: 200px; 
 
    position: absolute; 
 
} 
 
.ypos-5 { 
 
    bottom: 250px; 
 
    position: absolute; 
 
} 
 
.ypos-6 { 
 
    bottom: 300px; 
 
    position: absolute; 
 
} 
 
.ypos-7 { 
 
    bottom: 350px; 
 
    position: absolute; 
 
} 
 
.ypos-8 { 
 
    bottom: 400px; 
 
    position: absolute; 
 
} 
 
.xpos-0 { 
 
    left: 0px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-1 { 
 
    left: 50px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-2 { 
 
    left: 100px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-3 { 
 
    left: 150px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-4 { 
 
    left: 200px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-5 { 
 
    left: 250px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-6 { 
 
    left: 300px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-7 { 
 
    left: 350px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-8 { 
 
    left: 400px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-9 { 
 
    left: 450px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-10 { 
 
    left: 500px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-11 { 
 
    left: 550px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-12 { 
 
    left: 600px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-13 { 
 
    left: 650px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-14 { 
 
    left: 700px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-15 { 
 
    left: 750px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-16 { 
 
    left: 800px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-17 { 
 
    left: 850px; 
 
    /*position: absolute;*/ 
 
} 
 
.xpos-18 { 
 
    left: 900px; 
 
    /*position: absolute;*/ 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="game"> 
 
    <div id="player"> 
 
    <div class="eyes eye_R"></div> 
 
    <div class="eyes eye_L"></div> 
 
    <div class="mouth"></div> 
 
    </div> 
 
</div>



Как вы можете видеть, характер/игрок может передвигаться, не выходя из коробки.

Почему мой чистый JavaScript не работает?

Вот тот же проект с JavaScript:

var javascriptVersion = function() { 
 

 
\t var game_anim = function() { 
 

 
\t \t var level = [ 
 
\t \t \t [0, 1, "l", 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, "l", "l", 1], 
 
\t \t \t [0, 0, 0, 0, 2, 2, 2, 2, 2, 2], 
 
\t \t \t [0, 0, 0, 0, 0, 3, 3, 0, 3], 
 
\t \t ]; 
 

 
\t \t var player = document.getElementById('player'); 
 
\t \t var game = document.getElementById("game"); 
 

 
\t \t var left = 0; 
 
\t \t var top = 0; 
 

 
\t \t for (var i = 0; i < level.length; i++) { 
 
\t \t \t for (var j = 0; j < level[i].length; j++) { 
 

 
\t \t \t \t var n = level[i][j]; 
 

 
\t \t \t \t if (n === 1) { 
 

 
\t \t \t \t \t var blocks = document.createElement("div"); 
 
\t \t \t \t \t blocks.classList.add("block", "stone", "ypos-0", "xpos-" + j); 
 
\t \t \t \t \t game.appendChild(blocks); 
 

 
\t \t \t \t } 
 

 
\t \t \t \t if (n === 2) { 
 
\t \t \t \t \t var blocks = document.createElement("div"); 
 
\t \t \t \t \t blocks.classList.add("block", "stone", "ypos-1", "xpos-" + j); 
 
\t \t \t \t \t game.appendChild(blocks); 
 
\t \t \t \t } 
 
\t \t \t \t if (n === 3) { 
 
\t \t \t \t \t var blocks = document.createElement("div"); 
 
\t \t \t \t \t blocks.classList.add("block", "stone", "ypos-2", "xpos-" + j); 
 
\t \t \t \t \t game.appendChild(blocks); 
 
\t \t \t \t } 
 

 
\t \t \t \t if (n === 4) { 
 
\t \t \t \t \t var blocks = document.createElement("div"); 
 
\t \t \t \t \t blocks.classList.add("block", "stone", "ypos-3", "xpos-" + j); 
 
\t \t \t \t \t game.appendChild(blocks); 
 
\t \t \t \t } 
 

 
\t \t \t \t if (n === "l") { 
 
\t \t \t \t \t var blocks = document.createElement("div"); 
 
\t \t \t \t \t blocks.classList.add("block", "lava", "ypos-0", "xpos-" + j); 
 
\t \t \t \t \t game.appendChild(blocks); 
 
\t \t \t \t } 
 

 
\t \t \t } 
 
\t \t } 
 

 
\t \t document.addEventListener('keydown', function(event) { // keycodes: left = 37, right = 39 
 
\t \t \t if (event.keyCode == 39 || event.keyCode == 68) { // right arrow or D 
 
\t \t \t \t if (player.style.left < game.style.width - player.style.width) { 
 
\t \t \t \t \t left += 10; 
 
\t \t \t \t \t player.style.left = (parseInt(left) + left) + "px"; 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t \t if (event.keyCode == 37 || event.keyCode == 81 || event.keyCode == 65) { // left arrow or Q on AZERTY or A on QWERTY 
 
\t \t \t \t if (player.style.left > 0) { 
 
\t \t \t \t \t left -= 10; 
 
\t \t \t \t \t player.style.left = (parseInt(left) + left) + "px"; 
 
\t \t \t \t } 
 
\t \t \t } 
 

 
\t \t \t if (event.keyCode == 38) { 
 
\t \t \t \t if (player.style.top > 0) { 
 
\t \t \t \t \t top -= 10; 
 
\t \t \t \t \t player.style.left = (parseInt(top) + top) + "px"; 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t \t if (event.keyCode == 40) { 
 
\t \t \t \t if (player.style.top < (500 - player.style.height)) { 
 
\t \t \t \t \t top += 10; 
 
\t \t \t \t \t player.style.left = (parseInt(top) + top) + "px"; 
 
\t \t \t \t } 
 
\t \t \t } 
 

 
\t \t }); 
 

 
\t } 
 
\t game_anim(); 
 
} 
 

 
javascriptVersion();
#game { 
 
    position: absolute; 
 
    left: calc((100% - 800px)/2); 
 
    height: 500px; 
 
    width: 800px; 
 
    border: 2px solid black; 
 
} 
 

 
.block { 
 
    height: 50px; 
 
    width: 50px; 
 
    position: absolute; 
 
} 
 

 
.stone { 
 
    background-color: black; 
 
} 
 

 
.lava { 
 
    background-color: red; 
 
} 
 

 
#player { 
 
    height: 50px; 
 
    width: 50px; 
 
    background-color: #3747C0; 
 
    bottom: 0; 
 
    position: absolute; 
 
} 
 
#player .eyes { 
 
    border-radius: 50%; 
 
    background-color: white; 
 
    position: absolute; 
 
    height: 10px; 
 
    width: 10px; 
 
} 
 
#player .eye_R { 
 
    left: 7px; 
 
    top: 10px; 
 
} 
 
#player .eye_L { 
 
    left: 32px; 
 
    top: 10px; 
 
} 
 
#player .mouth { 
 
    height: 8.5px; 
 
    width: 32px; 
 
    background-color: white; 
 
    border-radius: 5px; 
 
    left: calc((50px - 32px)/2); 
 
    bottom: 10px; 
 
    position: absolute; 
 
} 
 

 
.ypos-0 { 
 
    bottom: 0px; 
 
    position: absolute; 
 
} 
 

 
.ypos-1 { 
 
    bottom: 50px; 
 
    position: absolute; 
 
} 
 

 
.ypos-2 { 
 
    bottom: 100px; 
 
    position: absolute; 
 
} 
 

 
.ypos-3 { 
 
    bottom: 150px; 
 
    position: absolute; 
 
} 
 

 
.ypos-4 { 
 
    bottom: 200px; 
 
    position: absolute; 
 
} 
 

 
.ypos-5 { 
 
    bottom: 250px; 
 
    position: absolute; 
 
} 
 

 
.ypos-6 { 
 
    bottom: 300px; 
 
    position: absolute; 
 
} 
 

 
.ypos-7 { 
 
    bottom: 350px; 
 
    position: absolute; 
 
} 
 

 
.ypos-8 { 
 
    bottom: 400px; 
 
    position: absolute; 
 
} 
 

 
.xpos-0 { 
 
    left: 0px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-1 { 
 
    left: 50px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-2 { 
 
    left: 100px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-3 { 
 
    left: 150px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-4 { 
 
    left: 200px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-5 { 
 
    left: 250px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-6 { 
 
    left: 300px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-7 { 
 
    left: 350px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-8 { 
 
    left: 400px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-9 { 
 
    left: 450px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-10 { 
 
    left: 500px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-11 { 
 
    left: 550px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-12 { 
 
    left: 600px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-13 { 
 
    left: 650px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-14 { 
 
    left: 700px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-15 { 
 
    left: 750px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-16 { 
 
    left: 800px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-17 { 
 
    left: 850px; 
 
    /*position: absolute;*/ 
 
} 
 

 
.xpos-18 { 
 
    left: 900px; 
 
    /*position: absolute;*/ 
 
}
<div id = "game"> 
 
\t <div id = "player"> 
 
\t \t <div class = "eyes eye_R"></div> 
 
\t \t <div class = "eyes eye_L"></div> 
 
\t \t <div class = "mouth"></div> 
 
\t </div> 
 
</div>

Спасибо за вашу помощь!

+2

какие условия не работают? есть много условий, поэтому. –

+0

@ RaghavRangani те, которые определяют, находится ли игрок в поле – FlipFloop

+0

С быстрым просмотром кода, похоже, вы извлекаете объект стиля элемента до того, как он имеет какое-либо значение. Обратите внимание, что значения из таблиц стилей не наследуются для встроенных стилей элемента. – Teemu

ответ

1

В ответ на вопрос Дэнни Дринкуотер указал, player.style.left - это не то же самое, что и $player.position().left. Эквивалент javascript будет element.offsetLeft. Есть еще пара дополнительных мест, где вы не получаете то же значение, что и в jquery.

Ниже приведен пример вашего обработчика keydown, реализованного в vanilla js.

document.addEventListener('keydown', function(event) { 
    event.preventDefault(); 
    if (event.keyCode == 39 || event.keyCode == 68) { // right arrow or D 
    if (player.offsetLeft < game.getBoundingClientRect().width - player.getBoundingClientRect().width) { 
     left = player.offsetLeft + 10; 
     player.style.left = left.toString() + "px"; 
    } 
    } 
    if (event.keyCode == 37 || event.keyCode == 81 || event.keyCode == 65) { // left arrow or Q on AZERTY or A on QWERTY 
    if (player.offsetLeft > 0) { 
     left = player.offsetLeft - 10; 
     player.style.left = left.toString() + "px"; 
    } 
    } 
    if (event.keyCode == 38) { 
    if (player.offsetTop > 0) { 
     top = player.offsetTop - 10; 
     player.style.top = top.toString() + "px"; 
    } 
    } 
    if (event.keyCode == 40) { 
    if (player.offsetTop < (500 - player.getBoundingClientRect().height)) { 
     top = player.offsetTop + 10; 
     player.style.top = top.toString() + "px"; 
    } 
    } 
}); 
+0

Могу ли я использовать этот точный код? – FlipFloop

+0

Его все твое. :) – rckrd

+0

СПАСИБО ВАМ ТАК МОЖНО – FlipFloop

0

Вы пробовали console.log на значениях Варса вы проверяете против в , если это заявления на каждый слушателя событий, чтобы убедиться, что значения совпадают между JQ и JS версии?

Например:

ли player.style.left в версии JS возвращают то же значение, как $ player.position() слева в версии JQ.?

Кроме того, делает event.which возвращают то же значение, как event.keyCode между двумя версиями, и тому подобное.

Смежные вопросы