Randomization / Randomization C #

1

Good. 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 gets some fruit.     

asked by anonymous 07.09.2015 / 00:03

1 answer

2

Using an example that the game area is 100 x 100 units (pixels, cm, mm, qq thing), can be easily created using the 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 have to take into account if this random point coincides with any existing object in the game area, if so, find a new position again.

example, using LinqPad

SincetheRandomobjectusesthetimetogeneraterandomnumbers,itisnormal,ifitisnotforveryimportanttasks,touseadelayafteranumberhasbeengenerated.Forexample:

Using a simple quick stop, it turns out that the numbers cover much more of the total limits.

    
07.09.2015 / 00:12