【问题标题】:How to select a value from array randomly for a 2d game (not min, max)如何从数组中为 2d 游戏随机选择一个值(不是最小值,最大值)
【发布时间】:2018-12-22 19:19:07
【问题描述】:

我正在做一个蛇游戏:如果蛇吃了苹果,它会在其中一个角落随机生成。

我尝试了getRandomInt(0, 25) 之类的代码,但生成的范围是 0 到 25: (0,1,2,3,4,5,6,7,8,9,10, ...25)

我使用的代码:

var grid = 16;

if (cell.x === apple.x && cell.y === apple.y) {
    snake.maxCells++;        
    apple.x = getRandomInt(0, 25) * grid;
    apple.y = getRandomInt(0, 25) * grid;

我希望苹果在地图的 4 个角落之一随机生成 (2d)

在 x = 25 或 0

    或

在 y=25 或 0

not: x,y at 1 or 2 or 3 or 4 or.. 24

【问题讨论】:

  • 请正确格式化代码!
  • grid是什么意思,为什么是16?

标签: javascript select random 2d


【解决方案1】:

如果您的网格大小为 grid,则不要在代码中硬编码 25,而是使用该变量。

您只需要在两个值之间进行选择,因此:

apple.x = getRandomInt(0, 1) * grid;

假设getRandomInt 是这样工作的。当然,你也可以使用原生的Math.random 函数来做到这一点:

apple.x = (Math.random() >= 0.5) * grid;

【讨论】:

    【解决方案2】:

    Math.random() 给你 0-0.99999999(不确定精度),然后你可以乘以你想要的数字。

    Math.random() * 2 为您提供 0-2 的数字(不包括 2), Math.random() * 100 为您提供 0-99.999999 之间的数字..(不是 100)

    您可以使用 Math.floor() 将此浮点数设为 int ...Math.floor(Math.random() * 100) ... 所以你得到从 0 到 99 的数字

    尝试在你的文件中使用它,以获得线索^^

    <script>
    for (let i = 0; i < 100; i++)
    {
        console.log(Math.floor(Math.random() * 100))
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2015-05-07
      • 2019-07-31
      • 2016-06-27
      • 2018-04-09
      • 1970-01-01
      • 2011-12-14
      • 2013-04-01
      • 2018-08-01
      • 1970-01-01
      相关资源
      最近更新 更多