Search code examples
pythonvariables

How to reset/reinitalize variables?


I've ran into an problem with variables. First see this code then I will explain my problem:

if pygame.Rect.colliderect(hammer_rect, mole_rect):
    random_locations = [(100, 440), (350, 440), (600, 440), (100, 260), (350, 260), (600, 260), (100, 80),
                        (350, 80), (600, 80)]

    randomsucks = random.choice(random_locations)
    test_sucks = randomsucks
    mole_spawn_new(randomsucks[0], randomsucks[1])
    randomsucks = 0
    score += 1
    print('Score was increased by one ') 

I want that when it runs again, the random numbers can't be same again. This is the related to the spawn of the enemy in my game and it is spawning at the same location after dying. I don't wanted it to go that way, so I tried to do this:

if pygame.Rect.colliderect(hammer_rect, mole_rect):
    random_locations = [(100, 440), (350, 440), (600, 440), (100, 260), (350, 260), (600, 260), (100, 80),
                        (350, 80), (600, 80)]

    randomsucks = random.choice(random_locations)
    while randomsucks == test_sucks:
        if test_sucks == randomsucks:
            randomsucks = random.choice(random_locations)
    test_sucks = randomsucks
    mole_spawn_new(randomsucks[0], randomsucks[1])
    randomsucks = 0
    score += 1
    print('Score was increased by one ') 

Nut that didn't work because I was using the variable before defining it.


Solution

  • well I think I get the problem here.

    One approach would be to remove the item from the list each time you generate a random item.

    Another way you can do this is by using 2 random items: x and y, this way the probability that you will get the same point is not very likely.

    But If you can't use these solutions then you can change the random seed: https://www.w3schools.com/python/ref_random_seed.asp