gpt4 book ai didi

javascript - 我随机生成的图 block 集未按预期工作。我怎样才能解决这个问题?

转载 作者:行者123 更新时间:2023-12-03 02:11:30 25 4
gpt4 key购买 nike

所以我尝试从数组生成随机图 block 集。我想创建除“湖”图 block (代码中的 4 和最终图形中的蓝色)之外的所有内容都同样随机。在下面的代码中,我尝试对其进行计算,以便计算生成过程沿行的距离以及该行中是否已生成湖泊。如果该行中已经生成了一个湖泊,则该过程会尝试创建一个除湖泊之外的图 block 。最后,我也不想在集合中制作超过五个湖泊。

这就是问题所在。当我运行程序时,它完全创建了图 block 集,但湖泊却很不稳定。湖泊的数量是随机的,每行有多个。我显然不想要这个。如果有人可以帮助我指出解决此问题的正确方向,我将不胜感激。如果你完全重写它我很好。我只是想弄清楚这一点。

如果代码草率且制作不当,也深表歉意。几个月前我刚刚开始编程。始终感谢反馈!

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var t = Math.round(Math.random()*10/2);
var lakecount = 0;
var arr = [];
var ln = row = 0;
//create initial array
for(let i = 0; i < 10; i++) {
arr.push([]);
};
//create second part of 2d array
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < 10; j++) {
//check if there are more then five lakes.
if(lakecount > 5) {
//if there is, reset until the new tile generated isn't a lake.
while(t == 4) {
t = Math.round(Math.random()*10/2);
}
//create new tile
arr[i].push([t,0,0,0]);
t = Math.round(Math.random()*10/2);
}
else {
if(t == 4 && ln == 1) {
//check if the program generated a lake and there is one already in the row, regenerate tile until a lake hasn't been generated for the tile
while(t == 4) {
t = Math.round(Math.random()*10/2);
}
console.log("one per row");
}
//create tile
arr[i].push([t,0,0,0]);
t = Math.round(Math.random()*10/2);
console.log(arr[i][j]);
if(t == 4) {
//if there is a lake generated, add to the amount of overall lakes, then say there is a lake in the row.
lakecount++
ln++;
console.log("add");
}
if(row < 10) {
//add for each tile, until you reach end of row.
row++
console.log("row add");
}
else {
//reset row, reset if lakes are in that row.
row = 0;
ln = 0;
console.log("row reset");
}
}
}
};
//color everything
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < 10; j++) {
switch(arr[i][j][0]) {
case 0:
ctx.fillStyle = "lime"
ctx.fillRect(j*48,i*48,48,48);
break;
case 1:
ctx.fillStyle = "black"
ctx.fillRect(j*48,i*48,48,48);
break;
case 2:
ctx.fillStyle = "green"
ctx.fillRect(j*48,i*48,48,48);
break;
case 3:
ctx.fillStyle = "gray"
ctx.fillRect(j*48,i*48,48,48);
break;
case 4:
ctx.fillStyle = "blue"
ctx.fillRect(j*48,i*48,48,48);
break;
case 5:
ctx.fillStyle = "bisque"
ctx.fillRect(j*48,i*48,48,48);
break;
}
}
}
<canvas id="canvas" height="480" width="480"></canvas>

最佳答案

//check if there are more then five lakes
//regen if more than 5 lakes or we already have a lake for this row.
if(lakecount > 5 || ln > 1)

你的逻辑也可以更简单,而不是在 for 循环之前然后在 for 循环结束之前进行随机生成(这很难阅读和遵循逻辑),尝试将随机生成作为第一行执行在进行任何检查之前在 for 循环中。如果简化逻辑,您的代码将更容易调试。

关于javascript - 我随机生成的图 block 集未按预期工作。我怎样才能解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49547100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com