mercredi 4 janvier 2017

How do you return a different index position in an if/else or switch statement?

I am checking to see what direction I am facing in my program: 'N', 'E', 'S', W'. I want to create a switch statement that checks my current direction, and depending on whether the command is to turn right ('r') or left ('l), change the direction and return the new direction to the user. I am trying to do that by calling the array and then subtracting the index position so that it lands on the right direction according to the last direction and command. I'm quite certain I'm not doing it right. Here's my code so far (with object included for context). I'm new to Javascript.

var myRover = {
  position: [0,0],
  direction: 'N',
  roverDirections = ['N', 'E', 'S', 'W'],
  marsGrid: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
  obstacles: []
};

function turn(command){

  if (command === 'l') {

      switch (myRover.direction) {
        case 'N':
        myRover.direction = (myRover.roverDirections.length - 1)
        break;
        case 'E':
        myRover.direction = (myRover.roverDirections.length - 4)
        break;
        case 'S':
        myRover.direction = (myRover.roverDirections.length - 3)
        break;
        case 'W':
        myRover.direction = (myRover.roverDirections.length - 2)
        break;
      }

    if (command === "r") {
      switch (myRover.direction) {
        case 'N':
        myRover.direction = (myRover.roverDirections.length - 3)
        break;
        case 'E':
        myRover.direction = (myRover.roverDirections.length - 2)
        break;
        case 'S':
        myRover.direction = (myRover.roverDirections.length - 1)
        break;
        case 'W':
        myRover.direction = (myRover.roverDirections.length - 4)
        break;
    }

It's also occurred to me that looping this might be much more efficient. But it's hard for me to conceptualize it without understanding the index positioning.

Aucun commentaire:

Enregistrer un commentaire