0
\$\begingroup\$

I'd like to create a Snake game, and for that, I'd like to position the sweet which makes the snake bigger in a random position.

For that, I use this code in the create event of the object bonbon :

position_x = round(random(10));
position_y = round(random(10));

x = position_x*16;
y = position_y*16;

But the sprite of this object is always in the same position of the room.

I tried changing the argument to the function random(), and then it changed the position of the sweet once, but after a rerun, the position doesn't change from that new location.

I think the position of the sweet is set using the argument to the random() function.

How can the position of the sweet be randomized? Why does the random function return the same values every time I run the game?

Thanks to DMGregory, I changed the code and this code works :

randomize();
position_x = irandom(10);
position_y = irandom(10);

x = position_x*16;
y = position_y*16;
\$\endgroup\$
1
\$\begingroup\$

I've changed the 'random()' function by the 'irandom()', and add the 'randomize()' function, in order to reset the value which are going to be randomized.

randomize();
position_x = irandom(10);
position_y = irandom(10);

x = position_x*16;
y = position_y*16;

Sorry for the spelling's mistakes, I'm French.

\$\endgroup\$
  • \$\begingroup\$ Note: you souldn't to do randomize() each time before get a random value. You should do it only once, when game starts. If you do randomize() multiple times, the result will be worst. \$\endgroup\$ – Dmi7ry Jun 10 '17 at 13:42
  • \$\begingroup\$ I use randomize() only in the create event because if I don't do this, the value will not be randomizing. \$\endgroup\$ – leris Jun 10 '17 at 14:09
  • \$\begingroup\$ If there is only one instance of the object (and created only once) then Create event is ok. Otherwise it's not good (for example, then you can place randomize at first room's creation code). \$\endgroup\$ – Dmi7ry Jun 11 '17 at 4:37
  • \$\begingroup\$ There is only one object with the randomize function. After that, I will change the position of the object with the collision event. \$\endgroup\$ – leris Jun 11 '17 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.