Why it's not working? JS...

Hell-o~! So, me is... well I have multiple names yus~!
Anywaa, I downloaded RPG Maker MZ... or MV... well... and I tried to run a challenge of "20 days game" lol...
I went into SUPER COOL idea... of making big RPG Game with combat, building, farming and all~!

I'm a WebDev, and I have my own Game Engine on C++... but I simply wanted to see what I could do in 20 days trial of RPG Maker... and well... I kinda wasted 2 of 20 of my days on doing nothing just because RPG Maker refuses to work as expected and it simply giving me headache so big that well... I dropped the project...

So... I did farming and mining, player can mine ores such as Copper, Iron, Silver, Gold and Adamantium, he can also get Wood and Stone for building... however... right when I wanted to make Plugin for building I run into problem where RPG Maker simply refuses to do what I'm telling him to do...

I did debug everything and...
1) I console log the entire data of the map and it looks correctly...
2) I console log the entire data of the current map and it also look correctly...
3) I run my loop to replace tiles and the data inside the console log looks 100% correct...

The world looks completly Fked up...
Some rows of the world copy properly while some other are garbage, there are random holes and all...

Here is the relevent JS:
JavaScript:
    function qCopyTiles(_Map,_Sx,_Sy,_Tx,_Ty,w,h){
        var _MapData=qLoadMapString(_Map); // returns a promise
        
        _MapData.then(function(_FileData){ // When mapData is fetched
        console.log( _MapData);
            if(_FileData==="failed"){console.log("Map Loading Failed");return;}
            try{
                console.log("Map Loaded Successfully");
                
                var _Lines = _FileData.split('\n');
                var _Line3 = _Lines[2];
                var _MapData = _Line3.slice(8, _Line3.length - 2);
                var _Array = _MapData.split(',');
                _Array = _Array.map(value => parseInt(value.trim(), 10));
                
                console.log(_Array);
                console.log($gameMap.data());
                
                // Loaded Map Data
                // var _Data        = "fu JSon";
                // var _Height        = 30;
                // var _Width        = 25;
                
                // Current Map that player is on
                var _CMap        = $gameMap;
                var _CWidth        = _CMap.width();
                var _CHeight    = _CMap.height();
                var _CData        = _CMap.data();
                
                var _Source =  (_Sy *  _Width)+_Sx; // Get start index of Source Map
                var _Target =  (_Ty * _CWidth)+_Tx; // Get start index of Target Map
                
                // replace entire map with other map... how is it still not working...
                // ChatGPT could not figure it out either xDD
                // O1 either... GG WP I quit...
                for(var c=0;c<h;c++){
                    for(var q=0;q<w;q++){
                        _CData[_Target++] = _Array[_Source++];
                    }
                    _Target+=_CWidth; // move to the next line of target
                    _Source+= _Width; // move to the next line of source by moving by it's width
                }
                // Force the game to update the map
                // $gamePlayer.requestMapReload();    - apparently those are not needed...
                // $gameMap.refresh(); it works same way regardless....
            }catch(e){console.error("Error parsing map data:",e);}
            console.log($gameMap.data());
        });
    }

    function qLoadMapString(_Map){
        const _File=`data/Map${_Map}.json`;
        try{
            const MapData = fetch(_File)
                .then((Response)=>{
                    if (!Response.ok){
                        throw new Error(`Failed to load map file: ${_File}`);}
                    return Response.text();
                })
                .catch((e)=>{
                    console.error(e.message);
                    return "failed";
                });
            return MapData; // This will return the Promise, not the actual data
        }catch(e){
            console.error(`Unexpected error while loading map: ${e.message}`);
            return "failed";}}
Anywaa... I have 0 idea why it's not working...
I really tried everything... promise ~! ( returned )

Here is the YT vid of what I got so far ( keep in mind it could get deleted later cuz I always delete my stuff hyhyhy xD )
One of the problems I can see is the data contains multiple layers (length = width*height*number_of_layers) so you cant just copy them in one loop like you are doing.
Your code mentioned ChatGPT. Can you quickly tell us how much of your code is AI-generated and which is your work?

RPG maker's code isn't really flexible regarding map manipulation during runtime. I recommend looking into this plugin because it's free and simple to use, and I think you can learn a bit about how it works just by looking into the code directly.


At first sight, I think the problem is that your code does not update the graphic layer. So the game map holds the new tiles, but the graphic layer doesn't.

Alternatively, here's a list of plugins that I know that can manipulate the map (most/all of them commercially)
- https://drag-and-plug-in.itch.io/sandbox-map-for-mz
- https://aerosys.blog/sandbox-engine
- https://notritter.itch.io/ritter-map-transform-plugin-rpg-maker-mz
- https://visustellamz.itch.io/tile-grafter-system
At first sight, I think the problem is that your code does not update the graphic layer. So the game map holds the new tiles, but the graphic layer doesn't.
That was also suggested by ChatGPT that's why I added the:
JavaScript:
                // Force the game to update the map
                // $gamePlayer.requestMapReload();    - apparently those are not needed...
                // $gameMap.refresh(); it works same way regardless....
But it wasn't doing anything so I commented it out...
Also... goto _Label_01
Your code mentioned ChatGPT. Can you quickly tell us how much of your code is AI-generated and which is your work?
Not sure what difference it makes... I pretty much cut out 90% of the GPT code as he suggested using JSon - which I was doing anywaa and pretty much 90% of the code is mine but 90% of it is pretty much garbage as I was struggling to get it work...
One of the problems I can see is the data contains multiple layers (length = width*height*number_of_layers) so you cant just copy them in one loop like you are doing.
:_Label_01
Yes, that's what also ChatGPT suggested, but I looked into the map file, at least it's just plain text and not some compression / encoding, I can clearly see values... and like I said... let me run RPG Maker...

Ohh so sad, just 12 days left of free trial xD...
This is the Map I'm trying to replace and second map is which map is being the source:
1735748109204.png
1735748125604.png

Now after running the game and the code:
1735748272822.png

Now it's worth to note that stairs on top of the map, as You can see that chunk is perfectly copied, and You can also see in the console that the values that are stored in the world data ak:
console.log($gameMap.data());

Are correct values... but what game is rendering is NOT correct...
So at the end of the function the data of the $gameMap is correct...
Now correct me if I'm wrong... but if You look directly into indexes of the array and into what You see in the game... it does not look same as the console is suggesting...
1735748463788.png



@Aerosys thank ya for the suggestions of the similar plugins...
If not the fact that I have just 12 days left I would probably look into the plugins...
But now as I learned that I have just 12 days left of free trial... I kinda think to drop this project completly... Well it was more of a fun project anywaa but well...
//Edit:
@utunnels
Reason why I started to do it in one loop is because I simply decided to stop copying specific chunk of the map and simply try to copy paste ENTIRE map... just to maybe see where the issue is...
But in the return I was getting... well exact mess You can see on pic. 3 and 4.

I know about the layers... tho it's funny because they are just bilions of Zeros as I don't use anything except the two main layers ( A and the B Decos ) but ohh well... RPG Maker filling the map just for good measure with bilions of zeros...

Also the fact that I used:
JavaScript:
                var _Lines = _FileData.split('\n');
                var _Line3 = _Lines[2];
                var _MapData = _Line3.slice(8, _Line3.length - 2);
                var _Array = _MapData.split(',');
                _Array = _Array.map(value => parseInt(value.trim(), 10));
And the comment: " // var _Data = "fu JSon"; "
Was because for while I was thinking that it may be JSon corrupting the data...
at first I tried straight going thru JSon... but then I simply set the one by one line by line approach to exclude as many errors as possible...

That's why I'm doing stupid thing like "Line3 = Lines[2]" xDDD
But I simply decided to do that manual processing to find out where the errors is...

Looks like I failed... and everything I tried too xD...
//Edit2: - ohh well xD
You could simply look at the header of the function as:
JavaScript:
function qCopyTiles(_Map,_Sx,_Sy,_Tx,_Ty,w,h){
Where the "_Map" is string with the name of the Map ( ideally I was planning to not use RPG Maker maps to hold the data of the buildings to build but temporarly xD )
_Sx / _Sy are ofc. starting coords of the thing to copy
_Tx / _Ty are coords of where in the current map to place the new world data
w and h are just width and height of the copied region

Believe me I have slight idea of what I was doing 😛
That's just a slice of funny code: ( rendering raw bitmap - via the CPU ofc. )
C++:
        int _t = (_x + clipX) + ((_y + clipY) * qData.RenderXSize);
        int _s = clipX + (clipY * _Surface.RenderXSize);

        for(int c=0;c<yToRender;++c){
            for(int i=0;i<xToRender;++i){
                if(_Surface.qPixel[_s]!=0){
                    qData.qPixel[_t]=_Surface.qPixel[_s];}
                ++_t;
                ++_s;}
            _t+=_jT;
            _s+=_jX;
        }
Not sure what difference it makes... I pretty much cut out 90% of the GPT code as he suggested using JSon - which I was doing anywaa and pretty much 90% of the code is mine but 90% of it is pretty much garbage as I was struggling to get it work...
It makes a huge difference. I don't have anything against AI code, per se, as long as the user still understands what it does or, at least, can tell what the exact problem is.

Just use Shaz Tilechanger, I think that's the best fit for you. Why invent something that already exists?
that chunk of code is too much padding "for the sake of it not blowing up" basically, when the important instruction to look at is one, and one alone.

who wrote that?
because if you know how to pad on that much, you sure know where it will go wrong.
that chunk of code is too much padding "for the sake of it not blowing up" basically, when the important instruction to look at is one, and one alone.

who wrote that?
because if you know how to pad on that much, you sure know where it will go wrong.
You know what... @gstv87


I'm so sorry...


I actually don't know what to say...

1735752393048.png

JavaScript:
    function qCopyTiles(_Map,_Sx,_Sy,_Tx,_Ty,w,h){
        var _MapData=qLoadMapString(_Map); // returns a promise
      
        _MapData.then(function(_FileData){ // When mapData is fetched
        console.log( _MapData);
            if(_FileData==="failed"){console.log("Map Loading Failed");return;}
            try{
                console.log("Well... I'm just stupid? :D");
              
                var _Lines = _FileData.split('\n');
                var _Line3 = _Lines[2];
                var _MapData = _Line3.slice(8, _Line3.length - 2);
                var _Array = _MapData.split(',');
                _Array = _Array.map(value => parseInt(value.trim(), 10));
              
              
                var _CMap        = $gameMap;
                var _CWidth        = _CMap.width();
                var _CHeight    = _CMap.height();
                var _CData        = _CMap.data();
              
                var i=0;
                var c=0;
              
                for(var x=0;x<w;x++){
                    for(var y=0;y<h;y++){
                        _CData[c++]=_Array[i++];
                    }
                  
                }
              
                // Force the game to update the map
                // $gamePlayer.requestMapReload();    - apparently those are not needed...
                // $gameMap.refresh(); it works same way regardless....
            }catch(e){console.error("Error parsing map data:",e);}
            console.log($gameMap.data());
        });
    }

I think... I was just working too hard recently...
Because... well the issue was on my side and I was struggling like stupid all around trying to fix the code... and unable...


Well... the problem was me...

And believe me or not but I just wanted to go like "F You"
But then my other side was like... "wait a minute, when I was doing a rendering engine I made a mistake of thinking that Index starts from 1... Maybe I'm actually brain damaged"

I rewrote the code completly from scratch...
And well... it works...

It just ing works...
I was trying to find solution of a problem that didnt even existed...

I mean... it did, I was the problem...



I'm really sorry for being a problem...

//Edit:
I don't really know what was causing problems...
But at this point I don't really care... I'm just a fail of a programmer xDDDD


Fixed version: ( without layers )
I really kinda hate myself rn...

well...
JavaScript:
    function qCopyTiles(_Map,_Sx,_Sy,_Tx,_Ty,w,h){
        var _MapData=qLoadMapString(_Map); // returns a promise
       
        _MapData.then(function(_FileData){ // When mapData is fetched
        console.log( _MapData);
            if(_FileData==="failed"){console.log("Map Loading Failed");return;}
            try{
                console.log("qMapManip:: Map: "+_Map+" Loaded!...");
                var _JSonMap = JSON.parse(_FileData);
               
                // Map loaded from the file
                var _SWidth    = _JSonMap.width;
                var _SHeight   = _JSonMap.height;
                var _SData     = _JSonMap.data;
               
                // Current map loaded in the game
                var _CMap        = $gameMap;
                var _CWidth        = _CMap.width();
                var _CHeight    = _CMap.height();
                var _CData        = _CMap.data();
               
                var _Source=_Sx+(_Sy*_SWidth); // Index of Loaded map tile from where to take tile value
                var _Target=_Tx+(_Ty*_CWidth); // Index of Current map tile where to put new value
               
                // for() - need to do other layers too, currently copy only first one...
                for(var y=0;y<h;y++){
                    for(var x=0;x<w;x++){
                        _CData[_Target++]=_SData[_Source++];
                    }
                    _Target+=_CWidth-w; // Jump to next line
                    _Source+=_SWidth-w;
                }
            }catch(e){console.error("qMapManip:: Could not load "+_Map+" Error:",e);}
        });
    }


//Edit 2 or 3...:

Use however You like, I probably not gonna continue doing it because I have 12 days left of free trial so my challenge failed anywaa... no credit or anything needed but You need to add additional layers

Simply do width * hegiht respectively for each map and when finish one layer do same as the part where "jump to next line" but instead jump by layer length - what jumped already in previous layer ( to get exacly in same spot but on the another layer )

usage: ( but ofc. change it however You like )
Arguments of the function are ofc. respectively:
Map name / XSource / YSource / XTarget / YTarget / Width / Height
Claim it even as Your own if You wish
1735754666847.png


JavaScript:
    function qCopyTiles(_Map,_Sx,_Sy,_Tx,_Ty,w,h){
        var _MapData=qLoadMapString(_Map); // returns a promise
        
        _MapData.then(function(_FileData){ // When mapData is fetched
        console.log( _MapData);
            if(_FileData==="failed"){console.log("Map Loading Failed");return;}
            try{
                console.log("qMapManip:: Map: "+_Map+" Loaded!...");
                var _JSonMap = JSON.parse(_FileData);
                
                // Map loaded from the file
                var _SWidth    = _JSonMap.width;
                var _SHeight   = _JSonMap.height;
                var _SData     = _JSonMap.data;
                
                // Current map loaded in the game
                var _CMap        = $gameMap;
                var _CWidth        = _CMap.width();
                var _CHeight    = _CMap.height();
                var _CData        = _CMap.data();
                
                var _Source=_Sx+(_Sy*_SWidth); // Index of Loaded map tile from where to take tile value
                var _Target=_Tx+(_Ty*_CWidth); // Index of Current map tile where to put new value
                
                // for() - need to do other layers too, currently copy only first one...
                for(var y=0;y<h;y++){
                    for(var x=0;x<w;x++){
                        _CData[_Target++]=_SData[_Source++];
                    }
                    _Target+=_CWidth-w; // Jump to next line
                    _Source+=_SWidth-w;
                }
            }catch(e){console.error("qMapManip:: Could not load "+_Map+" Error:",e);}
        });
    }

    function qLoadMapString(_Map){
        const _File=`data/Map${_Map}.json`;
        try{
            const MapData = fetch(_File)
                .then((Response)=>{
                    if (!Response.ok){
                        throw new Error(`Failed to load map file: ${_File}`);}
                    return Response.text();
                })
                .catch((e)=>{
                    console.error(e.message);
                    return "failed";
                });
            return MapData; // This will return the Promise, not the actual data
        }catch(e){
            console.error(`Unexpected error while loading map: ${e.message}`);
            return "failed";}}
well, the thing with maps is that they're just a bunch of numbers, not the bitmap you see.

the map data is what you should be looking at, so when rendering a map (on it's own, or on top of another) you just have to *render whatever that chunk of numbers says*
"that chunk of numbers", is the map table, brought from the other map.
the "building", you make with the same code from the same map you're in.... you just swap the thing it'll be looking at.
and when it comes to loading another map on top of yours, you just duplicate the destination object (the layers), so as to not overwrite yours.
*all* of that, is code that already exists... you just have to redirect it correctly.
writing all of that spaghetti as it was, is something AI would do... because >*AI DOESN'T KNOW OF CONTEXT*<
it doesn't know that you already HAVE the code but don't know where to look.

all of this, I figured out on my own, in Ace, six months ago.
you can look in my profile, that I rewrote the Tilemap object, for this very purpose 😀

Original thread: https://forums.rpgmakerweb.com/threads/why-its-not-working-js.174338/