-2

I've been trying to create a roguelike from scratch, and it was going well until I got to character movement. I know how to find the location of the @(player), but I don't know how to replace individual characters of the string. I have been searching for around 30 minutes now, and I still can't find anything that works. Help would be greatly appreciated.

document.onkeydown = function (event) {
    switch (event.keyCode) {
       case 37:
          var characterpos = line3.indexOf("@");
          // insert new code here
          break;

line3, # . . @ . . #, what I want it to look like after pressing left, # . @ . . . #

Mushroom
  • 3
  • 3
  • You mean like [string.replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)? – ray Jan 25 '22 at 03:18
  • Sorry, what I meant to say was how will I make sure that it only replaces the correct period? From what i've seen it replaces the first one or all of them, not just one specific one. – Mushroom Jan 25 '22 at 03:35

2 Answers2

-1

Tell me if I missunderstood the question, but you can use splice function, something like this:

var myString = "#..@..#";
var myArray = myString.split('');
var oldPosition = myArray.indexOf("@");
var newPosition = oldPosition+1;

myArray.splice(oldPosition,1,'.');
myArray.splice(newPosition,1,'@');

console.log(myArray);
-1

One note is that in your original post you included spaces between the periods (.). If that's not the case, simply replace the -2 with -1.

The -1 can also be changed to +1 to move it forward.

let string = '. . @ . .';
let stringArr = string.split('')

let currentPosition = string.split('').indexOf('@')

stringArr[currentPosition-2] = '@';
stringArr[currentPosition] = '.';

string = stringArr.join('')

console.log(string)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Joey
  • 613
  • 1
  • 6
  • 17
  • in the actual code I used the font monospace. I just used spaces here because it made it look like it did in my code. – Mushroom Jan 25 '22 at 14:26