Randomization/Randomization C#

Asked

Viewed 320 times

1

Boas. I’m trying to create a Snake game in c# and I have no idea how I can make a new fruit appear in a random place when the snake picks some fruit.

1 answer

1


using an example that the game area is 100 x 100 units (pixels, cm, mm, qq thing), can be created easily using the object Random

Random random = new Random();
int positionX = random.Next(0, 100),
    positionY = random.Next(0, 100);

the fruit would then be placed in:

addFruit(positionX, positionY);

Now, you only need to take into account if this random point matches any existing object in the game area, if so, find a new position.

example, using the Linqpad

inserir a descrição da imagem aqui


As the object Random use the time to generate random numbers, it is normal, if not for very important tasks, to use a delay after a number has been generated. For example:

inserir a descrição da imagem aqui

using a simple quick stop, it turns out that the numbers cover much more the entire limits.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.