0

I'm currently using an array to store position data for a text based game I'm creating.

I'm trying to edit each string in the array accordingly, for example, if my array was ['___','_1_','___'] with 1 being the character and _ being a blank space; also keeping my character position in another array ([1,1]); if I were to try and move the character up 1 and replace his position with a hash (#) it wouldn't work. I can edit the position array just fine but nothing else.

map[pos[1] - 1][pos[0]] = '1';
map[pos[1]][pos[0]] = '#';
pos[1] = pos[1] - 1;

That is what I'm using right now however only the third line actually works. If I ran this once, the map array would still be ['___','_1_','___'] but my position array would change to [1,0].

What is the best way to change the map value to fit my needs?

Spedwards
  • 4,167
  • 16
  • 49
  • 106

2 Answers2

2

The problem is that strings can't be modified. You must create a new string instead.

The array notation may be misleading, the charAt notation is clearly read-only.

Then, if you want to change a given character of a string, you may use

function changeStr(str, pos, newChar) {
    return str.substring(0, pos) + newChar + str.substring(pos+1);
}

Use it like this:

var map = ['___','_1_','___'], pos = [1,1,];
map[pos[1] - 1] = changeStr(map[pos[1] - 1], pos[0], '1');
map[pos[1]]     = changeStr(map[pos[1]],     pos[0], '#');
pos[1] = pos[1] - 1;

In your case, since you want to modify strings in arrays, you can simplify the above to

function changeArrStr(arr, key, pos, newChar) {
    arr[key] = arr[key].substring(0, pos) + newChar + arr[key].substring(pos+1);
}
var map = ['___','_1_','___'], pos = [1,1,];
changeArrStr(map, pos[1] - 1, pos[0], '1');
changeArrStr(map, pos[1],     pos[0], '#');
pos[1] = pos[1] - 1;
Oriol
  • 274,082
  • 63
  • 437
  • 513
2

The best way is separation of concerns, to keep from getting confused. First, the ability to replace a char in a string at a given position. (from elsewhere on so)

String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}

Next, the ability to do that in a particular ascii array.

replaceInAsciiMap = function(array, row, index, character) {
    array[row] = array[row].replaceAt(index, character);
}

Now you can add functions that update both the integer array and the ascii array, take old and new positions, and so on. To sum up: atoms first, then molecules, then proteins, then cells, then organisms...

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136