社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

我被python中的变量困住了

chutiya • 3 年前 • 1211 次点击  

我是python的初学者,因此对它了解不多,遇到了一个问题。首先看一下这段代码,然后我将解释我的问题

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

但这不起作用,因为我在定义变量之前使用了它

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133414
 
1211 次点击  
文章 [ 3 ]  |  最新文章 3 年前
quamrana
Reply   •   1 楼
quamrana    3 年前

我的方法是将位置移动到程序的顶部:

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
MATOS
Reply   •   2 楼
MATOS    3 年前

要阻止再次使用同一号码,请执行以下操作:

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)

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

Nir Yossef
Reply   •   3 楼
Nir Yossef    3 年前

我想我明白了问题所在。

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

另一种方法是使用两个随机项:x和y,这样你得到相同点的可能性不大。

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