我遇到了變數問題。首先看這段代碼,然后我會解釋我的問題:
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 ')
螺母不起作用,因為我在定義變數之前就使用了它。
uj5u.com熱心網友回復:
好吧,我想我在這里遇到了問題。
一種方法是在每次生成隨機專案時從串列中洗掉該專案。
另一種方法是使用 2 個隨機專案:x 和 y,這樣你得到相同點的概率就不太可能了。
但如果您不能使用這些解決方案,那么您可以更改隨機種子: https ://www.w3schools.com/python/ref_random_seed.asp
uj5u.com熱心網友回復:
要阻止再次使用相同的號碼:
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 回圈時,如果第一個分配的值不在其中,則回圈將不會運行它將運行您的代碼,然后在您將元組列入黑名單之后。如果這不是您要問的,請澄清更多
uj5u.com熱心網友回復:
我這樣做的方法是將位置移動到程式的頂部:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472110.html
上一篇:在for回圈中獲取最后兩個變數
