I\'m trying to make a simple life simulator, and I need the \"cells\" to move almost randomly (with a few rules) across the screen. But the problem is, after a while they tend t
The reason your cells are bunching up to the top-left is because of random.randrange()
.
The randrange()
part handles the range, as per the python range()
function. Looking at the range()
function, range( A, B )
returns a list A
-> B-1
:
>>> for i in range( 1,10 ): print( i, end = ", " )
...
1, 2, 3, 4, 5, 6, 7, 8, 9,
So when your code is doing random.randrange(directions[self.direction][0][0],directions[self.direction][0][1])
, it's excluding the last item in the range, which looks to be "SE". Hence they're a little more likely to head in the other directions, and after thousands of iterations, that moves them to the top-left corner.
A lot of random number generators tend to favour smaller numbers. You may need to offset the random values by some other tiny random number, or look into more sophisticated generators.
I looked around quickly, and I couldn't find any "truly" random generators.
Try adding a tiny number to the other random numbers and see start happens.
Just to clarify what I meant:
#Instead of:
self.move[0] = random.randrange(directions[self.direction][0][0],directions[self.direction][0][1])
self.move[1] = random.randrange(directions[self.direction][1][0],directions[self.direction][1][1])
#Try something like:
smallOffset = random.random() #Random floating-point number between 0 and 1 ("Tiny number")
self.move[0] = random.randrange(directions[self.direction][0][0],directions[self.direction][0][1]) + smallOffset
self.move[1] = random.randrange(directions[self.direction][1][0],directions[self.direction][1][1]) + smallOffset
You may have to adjust smallOffset
to limit how large it can get (because, it can be a value up to almost 1, which isn't really small anymore)