简体   繁体   English

Javascript 平铺地图。 (带有表情符号)

[英]Javascript tile map. (With emojis)

I want to make a code that can generate maps.我想做一个可以生成地图的代码。 I tried this:我试过这个:

      var mapArray = [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1, 1, 1, 1],
    ];
    
    function drawMap() {  
        let map = "";
        for (var y = 0; y < mapArray.length; y++) {
            for (var x = 0; x < mapArray[y].length; x++) {
                if (parseInt(mapArray[y][x]) == 0) {
                  var title = map.concat("⬛");
                }
                if (parseInt(mapArray[y][x]) == 1) {
                  var title = map.concat("⬜");
                }
                if (parseInt(mapArray[y][x]) == 2) {
                  var title = map.concat("🔴");
                }
                if (parseInt(mapArray[y][x]) == 3) {
                  var title = map.concat("🔵");
                }
                title.x = x * 28;
                title.y = y * 28;
                console.log(map)
                return map;
            }
        }
    }   
    drawMap()

I tried this code but it logged empty.我试过这段代码,但它记录为空。 Then I tried to move console.log(map) to end of the function and it logged empty again.然后我尝试将console.log(map)移动到函数的末尾,它再次记录为空。

first, you can iterate through array with .map() function, my guess you trying to do so首先,您可以使用.map()函数遍历数组,我猜您正在尝试这样做

Second, your if approach is not really scalable you will need to write more if statements when new numbers goona be in your map (4, 5, 6 for example)其次,您的if方法并不是真正可扩展的,当您的地图中出现新数字时,您将需要编写更多if语句(例如 4、5、6)

Combination of these two:这两者的结合:

// dictionary for storing number:image pair
const dictionary = {
  0: "⬛",
  1: "⬜",
  2: "🔴",
  3: "🔵"
}

// function arguments is array and tictionary
function transformArray(arr, dict) {
  // iterating through every `insideArray` in `arr`
  return arr.map(insideArray => {
    // iterating through every `item` in `insideArray`
    return insideArray.map(item => {
      // trying to lookup image in dictionary
      // if there is no `item` key - return default value ""
      return dict[item] || ""
    })
  })
}

const tranfsormedArray = transformArray(mapArray, dictionary)

console.log(transformedArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM