Reputation: 4492
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?
Upvotes: 0
Views: 880
Reputation: 288290
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;
Upvotes: 2
Reputation: 62676
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...
Upvotes: 2