skip to Main Content

How can I make the green square always land on the center of the blue square; it works when I first hit the up key but after that it lands in different positions.

Also, I want to be able to keep the green square from going outside the grid; as you can see, I’m really green when it comes to coding and maybe this takes more complex coding than I realized. But the most common advice has been to try, Google, and ask on forums.

const mun = document.querySelector('.mun')

let xAxis = 0
let yAxis = 0


function control(e) {
  switch (e.key) {
    case 'ArrowLeft':
      xAxis -= 80;
      mun.style.left = xAxis + 'px';
      break;

    case 'ArrowRight':
      xAxis += 80;
      mun.style.left = xAxis + 'px';
      break;

    case 'ArrowUp':
      yAxis -= 80;
      mun.style.top = yAxis + 'px';
      console.log(yAxis)
      break;

    case 'ArrowDown':
      yAxis += 80;
      mun.style.top = yAxis + 'px';
      break;
  }
};

document.addEventListener('keydown', control)
.wrapper {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  border: 2px solid black;
}

.one,
.two,
.three,
.four,
.six,
.seven,
.eight,
.nine {
  background-color: blue;
  border: 1px solid black;
}

#five {
  background-color: blue;
  border: 1px solid black;
  position: relative;
}

.mun {
  background-color: green;
  width: 35px;
  height: 35px;
  position: center;
  position: absolute;
  top: 31%;
  left: 32%;
}
<div class="wrapper">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
  <div id="five">Five
    <div class="mun"></div>
  </div>
  <div class="six">Six</div>
  <div class="seven">Seven</div>
  <div class="eight">Eight</div>
  <div class="nine">Nine</div>
</div>

2

Answers


  1. There you go. You should be able to improve this by finding an algorithm that can find the neighboring elements. Here is the jsfiddle as well: https://jsfiddle.net/28dzk1e7/25/

        const mun = document.querySelector('.mun')
    
            let matrixSize = 3
        let currentPos = 5
        let positions = [1,2,3,4,5,6,7,8,9]
        let neighbours = {
          1:[2,4],
          2:[1,3,5],
          3:[2,6],
          4:[1,5,7],
          5:[2,4,6,8],
          6:[3,5,9],
          7:[4,8],
          8:[7,5,9],
          9:[6,8],
        }
        
        
        
        
        let goTo = (targetPos)=>{
          if(neighbours[currentPos].includes(targetPos)){
             let targetContainer = document.querySelector(`[data-num="${targetPos}"]`);
             targetContainer.appendChild(mun)
             currentPos=targetPos
            }
        }
        
    
        function control(e) {
            switch (e.key) {
                case 'ArrowLeft':
                      goTo(currentPos - 1)
                    break;
         
                case 'ArrowRight':
                            goTo(currentPos + 1)
                    break;
            
                case 'ArrowUp':
                                 goTo(currentPos - matrixSize)
                    break;
             
                case 'ArrowDown':
                            goTo(currentPos + matrixSize)
                    break;    
           }
         };
         
          document.addEventListener('keydown', control)
        .wrapper {
            display: inline-grid;
            grid-template-rows: 100px 100px 100px;
            grid-template-columns: 100px 100px 100px;
            border: 2px solid black;
        }
    
        .one, .two, .three,
        .four, .six, .seven, .eight, .nine ,.five {
            background-color: blue;
            border: 1px solid black;
            position:relative;
            height:100px;
            width:100px;
    
        }
    
        .mun {
            background-color: green;
            width: 35px;
            height: 35px;
            position:absolute;
            top:50%;
            left:50%;
            transform: translate(-50%,-50%);
    
        }
      <div class="wrapper">
        <div class="one" data-num="1">One</div>
        <div class="two" data-num="2">Two</div>
        <div class="three" data-num="3">Three</div>
        <div class="four" data-num="4">Four</div>
        <div class="five" data-num="5">Five
            <div class="mun"></div> 
        </div>
        <div class="six" data-num="6">Six</div>
        <div class="seven" data-num="7">Seven</div>
        <div class="eight" data-num="8">Eight</div>
        <div class="nine" data-num="9">Nine</div>
    </div> 
    Login or Signup to reply.
  2. Another approach is to not hardcoding based on rows and columns count. Instead, rows/columns count could be retrieved from css code.

    Also, the mun div could be created at page load ant put in the div marked by an attribute (selected="true" in this example).
    The grid is not necessarily square or even complete.

    var rows;
    var cols;
    var initial_index;
    var index;
    var boxes;
    var mun;
    
    function onload() {
        var wrapper = document.querySelector('.wrapper');
        var rows_template = window.getComputedStyle(wrapper).getPropertyValue('grid-template-rows');
        rows = rows_template.split(' ').length;
        var cols_template = window.getComputedStyle(wrapper).getPropertyValue('grid-template-columns');
        cols = cols_template.split(' ').length;
        boxes = document.querySelectorAll('.box');
        for (i = 0; i < boxes.length; i++) {
            if (boxes[i].attributes.getNamedItem('selected') != null) {
                initial_index = i;
                index = i;
                mun = document.createElement("div");
                mun.className = 'mun';
                SetPosition();
                break;
            } 
        }
    }
    
    function cursor_keys(event) {
        switch (event.code) {
            case 'ArrowUp':
                if (index - cols >= 0) { index -= cols; SetPosition(); }
                    break;
            case 'ArrowDown':
                if (index + cols < boxes.length) { index += cols; SetPosition(); }
                    break;
            case 'ArrowLeft':
                if (index % cols > 0) { index--; SetPosition(); }
                    break;
            case 'ArrowRight':
                if (index + 1 < boxes.length && (index % cols) != cols - 1) { index++; SetPosition(); }
                    break;
            case 'Home':
                index = initial_index;
                SetPosition();
                break;
            case 'PageUp':
                index = 0;
                SetPosition();
                break;
            case 'PageDown':
                index = boxes.length - 1;
                SetPosition();
                break;
        }
    }
    
    function SetPosition() {
        boxes[index].appendChild(mun);
    }
    
    document.addEventListener('DOMContentLoaded', onload);
    document.addEventListener('keydown', cursor_keys);
    .wrapper {
            display: inline-grid;
            grid-template-columns: 100px 100px 100px 100px 100px 100px;
            grid-template-rows: 100px 100px 100px 100px;
        }
    
        .box {
            background-color: antiquewhite;
            color: black;
            border: 1px solid black;
            height: 100px;
            width: 100px;
            position: relative;
        }
    
        .mun {
            background-color: green;
            width: 35px;
            height: 35px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    <div class="wrapper">
            <div class="box">1</div>
            <div class="box">2</div>
            <div class="box">3</div>
            <div class="box">4</div>
            <div class="box">5</div>
            <div class="box">6</div>
            <div class="box">7</div>
            <div class="box">8</div>
            <div class="box">9</div>
            <div class="box">10</div>
            <div class="box" selected="true">11</div>
            <div class="box">12</div>
            <div class="box">13</div>
            <div class="box">14</div>
            <div class="box">15</div>
            <div class="box">16</div>
            <div class="box">17</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search