【发布时间】:2021-08-30 06:33:11
【问题描述】:
我正在开发一款终端游戏。游戏场被fieldCharacters (░) 和holes (O) 占据
该字段是随机生成的,但我还想确保 pathCharacter (*) 始终位于该字段的左上角(由一组数组组成)
为此,我将第一个数组的第一个索引分配给 pathCharacter (*)。见以下代码:
String.prototype.replaceAt = function(index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}
hat = '^';
hole = 'O';
fieldCharacter = '░';
pathCharacter = '*';
class Field {
constructor(field) {
this._field = field;
}
print() {
this._field = field.join('\n');
console.log(this._field.replace(/,/g, ''))
}
static generateField(height, width) {
let finalArray = []
for (let i = 0; i < height; i++) {
finalArray.push(fieldCharacter.repeat(width));
}
for (let i = 0; i < finalArray.length; i++) {
let randomHoleX = Math.floor(Math.random() * width);
let randomHoleY = Math.floor(Math.random() * height);
finalArray[randomHoleY] = finalArray[randomHoleY].replaceAt(randomHoleX, hole);
}
// what I tried to do
finalArray[0][0] = pathCharacter;
return finalArray.join('\n').replace(/,/g, '');
}
}
console.log(Field.generateField(5, 10));
输出内容:TypeError: Cannot assign to read only property '0' of string '░░O░░░░░░O'
我想要的示例:
*░░O░░░░░O
░░░░░░░░░░
░░░░O░░░░░
░░░░░░░░░░
░░░O░O░░░░
【问题讨论】:
标签: javascript arrays loops typeerror