I must say first that everything, that I am a newbie , I am recycling myself on programming issues. Even being a programmer for more than 6 years I did not play anything. So I implore you patience.
I am practicing things with JavaScript
, it turns out that I want to make an image move with the arrow keys and when "encountering" another image, the latter flee.
The code to move the first image with the arrows is already working, what does not work for me is the "when they are found, the other one changes position".
function leftArrowPressed () {
var element = document.getElementById("pimientos");
element.style.left = parseInt(element.style.left) - 5 + 'px';
}
function rightArrowPressed () {
var element = document.getElementById("pimientos");
element.style.left = parseInt(element.style.left) + 5 + 'px';
}
function upArrowPressed () {
var element = document.getElementById("pimientos");
element.style.top = parseInt(element.style.top) - 5 + 'px';
}
function downArrowPressed () {
var element = document.getElementById("pimientos");
element.style.top = parseInt(element.style.top) + 5 + 'px';
}
function moveSelection (evt) {
switch (evt.keyCode) {
case 37:
leftArrowPressed();
break;
case 39:
rightArrowPressed();
break;
case 38:
upArrowPressed();
break;
case 40:
downArrowPressed();
break;
}
};
function docReady () {
window.addEventListener('keydown', moveSelection, quemepilla);
}
function quemepilla (evt) {
var elementPimi = document.getElementById("pimientos");
var elementPC = document.getElementById("pc");
if (elementPC.style.top || elementPC.style.left === elementPimi.style.top || elementPimi.style.left) {
elementPC.style.top = parseInt(elementPC.style.top) + 5 + 'px';
elementPC.style.top = parseInt(elementPC.style.top) - 5 + 'px';
elementPC.style.left = parseInt(elementPC.style.left) + 5 + 'px';
elementPC.style.left = parseInt(elementPC.style.left) - 5 + 'px';
}
}
document.addEventListener("DOMContentLoaded", docReady);
<img src="carapimi.png" alt="" id="pimientos" style="position:absolute;left:0; top:0;" height="45" width="45">
<img src="pc.svg" alt="" id="pc" style="position:absolute;left:100px; top:100px;" height="45" width="45">