作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了变量问题。首先看到这段代码,然后我会解释我的问题:
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 ')
这不起作用,因为我在定义变量之前使用了该变量。
最佳答案
好吧,我想我在这里遇到了问题。
一种方法是每次生成随机项目时从列表中删除该项目。
实现此目的的另一种方法是使用 2 个随机项:x 和 y,这样您获得相同点的可能性就不太可能。
但是如果您不能使用这些解决方案,那么您可以更改随机种子: https://www.w3schools.com/python/ref_random_seed.asp
关于python - 如何重置/重新初始化变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72078717/
我是一名优秀的程序员,十分优秀!