python - 确定循环中的第一次出现

标签 python python-3.x pygame

我是 Python 的新手,但我环顾四周,没有看到任何与我正在尝试做的事情相匹配的东西。

我正在使用 PyGame 检测三个对象(球、方 block A、方 block B)之间的碰撞。我想要做的是,如果球击中方 block B,则 X 发生,但前提是它之前击中过方 block A。因为这是在一个连续发生的循环中,我不能简单地将 ballAcollide 设置为 true,因为它会立即重置。

我目前有一些可行的方法,但我确信这是一个丑陋的解决方法,并且有更好的方法来实现它。这是有问题的代码片段:

def fastball(ball, squareA, squareB):
    # This needs to be improved
    if ball.rect.colliderect(squareA.rect):
        # do unrelated
        global firsthit
        firsthit = False
    elif ball.rect.colliderect(squareB.rect):
        try:
            if not firsthit:
                # do X
        except NameError:
            # do nothing

最佳答案

根据PatrickArtner的建议回答:

def fastball2(ball, squareA, squareB, list):
    if ball.rect.colliderect(squareA.rect):
        if len(list) == 0:
            list.append('A')
        # do unrelated
    elif ball.rect.colliderect(squareB.rect) and len(list) > 0:
        # do x

如果满足某些条件,列表将在循环中的不同点刷新。感谢您的帮助!

关于python - 确定循环中的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260349/

相关文章:

python - 如何在多行 if 语句中注释每个条件?

python - 当 wtforms 中发生另一个验证错误时,文件字段无法保存文件

python - 如何告诉 Python 将整数转换为单词

python - 如何将 Julian 日期转换为标准日期?

python - Pygame:赋值解包抛出 SystemError

python - 当玩家未击中目标超过 3 次时结束 pygame

python - 哪个 python 包为 statsmodels 实现 _representation 和 _kalman_filter?

python - Pip Install 抛出错误代码 1

Python 3 导入错误 : cannot import name 'model selection' OS X 10. 11.3, python

python - pygame加载更改文件名的图像