Blade Nelson
Blade Nelson

Reputation: 41

Random Number Functions Python

I am making a little game where when events happen, rectangles get spawned at a random x and y point and I am having some trouble implementing functions into this. Here is some basic code:

xran = random.randint(5, 485)
yran = random.randint(5, 485)
xran1 = random.randint(5, 450)
yran1 = random.randint(5, 400)

def allRand():
     #This REGENERATES those randoms making it 'spawn' in a new location.
     xran = random.randint(0, 485)
     yran = random.randint(0, 485)
     xran1 = random.randint(5, 450)
     yran1 = random.randint(5, 400)

char = pygame.draw.rect(screen, black, (x,y,15,15), 0)
food = pygame.draw.rect(screen, green, (xran,yran,10,10), 0)
badGuy = pygame.draw.rect(screen, red, (xran1,yran1,50,100), 0)


if char.colliderect(food):
    score += 1
    print "Your score is:",score
    allRand()

Does calling a function that regenerates random numbers work for any of you? I know it regenerates them because I have had it print back the variables, for some reason my rects don't do there though.

Note: This is just snippet of my code it was just meant to give an idea of what I am trying to do.

Thanks!

Upvotes: 0

Views: 107

Answers (3)

The-IT
The-IT

Reputation: 728

To add to Lee Daniel Crocker's answer, when you create variables in a function they exist only in that function. If you want them to exist outside you can either make them global variables as he suggested, you are can return them and catch them:

>>> def square(number):
    squared = number*number
    return squared

>>> square(3)
9
>>> ninesquared = square(3)
>>> ninesquared
9
>>> 

Read more

It looks like you need to master your basics. I suggest doing that first before trying things in pygame.

EDIT:

If you define variables outside of the function, they will not effect any variables you define in the function either.

>>> x = 5
>>> def rais():
    x = 10


>>> x
5
>>> rais()
>>> x
5
>>> 

Notice how rais did nothing? If we change the line in rais to be x = x + 1 then python will give us back an error that x is not defined.

If you want you're variables to get into the function you need to pass them in as parameters, but once again, they won't effect anything outside of the function unless you return and capture them. And once again, you can declare them as global variables and that will also work.

Upvotes: 1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

You need to declare xran, etc. with global inside the allRand() function. Otherwise, it's just creating new variables inside function scope, assigning them random values, then throwing them away when the function returns.

Upvotes: 1

d1str0
d1str0

Reputation: 246

Your allRand() method doesn't have any code. You must indent the lines you want in that function.

It's kinda working because you still call those statements below your def. But it's not because you're calling the function.

Upvotes: 1

Related Questions