0

I'm making a snake game and have hit a stop when generating the food coordinates.

I want a random number that is divisible by 10. By that I mean that it has to be a number mod(10) == 0. The snake is of width 10 so in order for the coordinates to match, I need numbers like 80, 130, 10, 40, 200

Only even numbers without singulars are allowed. This is my current code:

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);
crazyloonybin
  • 935
  • 3
  • 18
  • 36
  • 6
    generate a random integer e.g. between 0 and whatever and multiply it by 10. – luk2302 Aug 12 '20 at 07:35
  • Does this answer your question? [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – luk2302 Aug 12 '20 at 07:35
  • 21%10 gives you 1. you can add 10-1 to 21 it becomes 30 for example. `Math.random()` gives a random number between (0-1] so you need to multiply that with your range for example 200 – Alim Öncül Aug 12 '20 at 07:35
  • n with n = 0 (mod 10) has the shape n = 10k with k being some integer. So generate a random integer and multiply it by 10. – Ingo Bürk Aug 12 '20 at 07:35

2 Answers2

2

Use 10 in your snippet then (instead of 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);
  • added 10 to avoid 0, I guess that's what you mean on singular. If not, please clarify in the question
  • this way code generates 10 <= x <= width and 10 <= y <= height, where both x and y are integer multiples of 10.
tevemadar
  • 12,389
  • 3
  • 21
  • 49
1

You can generate a random multiple of 10 between 10 and 150 by first generating a random number between 1 and 15 and then multiplying it by 10. You can do this in plain JavaScript as follows:

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

Or, you can do it in a cryptographically secure way with rando.js like this:

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