生成一个随机数,该随机数在JavaScript中可以被10整除

问题描述

我正在做蛇游戏,并且在生成食物坐标时已经停下来。

我想要一个可以被10整除的随机数。这意味着它必须是一个数字mod(10)==0。蛇的宽度为10,因此为了匹配坐标,我需要数字,例如80、130、10、40、200

仅允许无奇数的偶数。这是我当前的代码

let width = 100;
let height = 100;
       
let x = Math.floor(Math.random()*width/2)*2;
let y = Math.floor(Math.random()*height/2)*2;

console.log(x + " : " + y);

解决方法

然后在代码段中使用10(而不是2):

let width = 100;
let height = 100;
       
let x = Math.floor(Math.random()*width/10)*10+10;
let y = Math.floor(Math.random()*height/10)*10+10;

console.log(x + " : " + y);

  • 加10可以避免0,我想这就是您的意思。如果没有,请在问题中进行澄清
  • 这样,代码将生成10 <= x <= width10 <= y <= height,其中x和y均为10的整数倍。
,

您可以生成10到150之间的10的随机倍数,方法是先生成1到15之间的随机数,然后乘以10。可以在普通JavaScript中按如下所示进行操作:

var min = 1;
var max = 15;
console.log(Math.floor(Math.random() * (max - min + 1) + min) * 10);

或者,您可以使用rando.js以加密安全的方式完成此操作:

console.log(rando(1,15) * 10);
<script src="https://randojs.com/2.0.0.js"></script>