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\$
2
  • \$\begingroup\$ You might find answers to previous GameMaker questions on randomizing useful here. \$\endgroup\$
    – DMGregory
    Commented Jun 10, 2017 at 12:10
  • \$\begingroup\$ Don't edit your answer to the question body. Instead, post it as an answer at the bottom of the site. \$\endgroup\$
    – user35344
    Commented Jun 10, 2017 at 13:22

1 Answer 1

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\$
4
  • \$\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
    Commented Jun 10, 2017 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
    Commented Jun 10, 2017 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
    Commented Jun 11, 2017 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
    Commented Jun 11, 2017 at 12:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .