如何重置/重新激活变量?



我遇到了一个变量问题。首先看看这段代码,然后我将解释我的问题:

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 ') 

我希望当它再次运行时,随机数不能再次相同。这与我的游戏中的敌人刷出有关,它在死亡后会在同一位置刷出。我不想让它变成那样,所以我试着这样做:

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 ') 

没有工作,因为我在定义变量之前使用了它。

我想我明白问题了。

一种方法是每次生成随机项时从列表中删除该项。

另一种方法是使用两个随机项目:x和y,这样你得到相同点的概率就不太可能了。

但是如果你不能使用这些解决方案,那么你可以改变随机种子:https://www.w3schools.com/python/ref_random_seed.asp

防止重复使用相同的号码:

from random import choice
blacklisted_numbers = [] #this might need to be global if you want to use this function multiple times
random_locations = [(100, 440), (350, 440), (600, 440), (100, 260), (350,260), (600, 260), (100, 80),(350, 80), (600, 80)]
number = choice(random_locations)
while number in blacklisted_numbers:
number = choice(random_locations)
#now its out of the loop so its not blacklisted
#Code all of your stuff
blacklisted_numbers.append(number)

总结一下,我的想法是,如果你创建一个空数组,你可以在那里附加所有使用的random_locations,并为数字分配一个随机选择,当它到达while循环时,如果第一个分配的值不在那里,循环将不会运行,它将运行你的代码,然后在所有这些之后,你将元组列入黑名单。如果这不是你所要求的,请澄清更多

我的做法是将这些位置移到程序的顶部:

random_locations = [(100, 440), (350, 440), (600, 440), (100, 260), (350, 260), (600, 260), (100, 80), (350, 80), (600, 80)]
test_sucks = None
if pygame.Rect.colliderect(hammer_rect, mole_rect):
randomsucks = random.choice(random_locations)
while randomsucks == test_sucks:
randomsucks = random.choice(random_locations)
test_sucks = randomsucks
...
# use randomsucks

最新更新