【问题标题】:Read Coordinates from file in javascript在javascript中从文件中读取坐标
【发布时间】:2018-01-28 03:26:17
【问题描述】:

我在 javascript 中有文件,我正在使用

打开
fs.readFileSync(fileName)

在我将它返回给客户端后,它的存储方式如下:

[G]Hey, where did [C]we go, da[G]ys when the ra[D]ins came
[G]Down in the holl[C]ow, [G]playin' a ne[D]w game

但是,我需要 x 和 y 坐标才能更新画布。

有什么办法吗?

【问题讨论】:

  • X y 坐标是什么?
  • 文件中的单词
  • 文件没有 xy 坐标。
  • 在读取文件时可以添加 x 和 y 坐标吗?
  • 提供样本输入和样本预期输出。请参阅创建minimal reproducible example

标签: javascript string file coordinates


【解决方案1】:

如果我们假设第一个字符的位置为{x: 0, y: 0},并且下一行将 y 位置加一,那么我们可以使用类似的方法来计算字符的位置:

/**
 * Find the XY positions of this string
 *
 * @type {string}
 */
const given = `[G]Hey, where did [C]we go, da[G]ys when the ra[D]ins came
[G]Down in the holl[C]ow, [G]playing a ne[D]w game`;

/**
 * Return the coordinates of the characters in a string
 *
 * @param {string} string
 * @returns {Array}
 */
const calculateXY = (string) => {
    const positions = [];
    let yIndex = 0;
    let xIndex = 0;

    string.split('').forEach(character => {
        if(/\n/g.test(character)) {
            yIndex++;
            xIndex = 0;
        } else {
            positions.push({ [character]: { x: xIndex, y: yIndex}});
        }

        xIndex++;
    });

    return positions;
};

const result = calculateXY(given);
console.log(result);

您可以修改上面的块并传递一个乘数,以便 x 和 y 增加到下一个字符的距离(以像素为单位)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多