Python-snake-gam的碰撞问题

2024-10-03 02:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的碰撞检查不起作用的Python im中的蛇游戏有问题。我写了一个函数来检查蛇和食物本身的碰撞。当它发生碰撞时它什么也不做,我已经把它写到undraw如果它使用函数碰撞,我还放了一个print函数,看看如果我使用它时没有看到打印,这个函数是否正常工作。在

def collide(block1,block2):
     if math.sqrt(((block2.getCenterX() - block1.getCenterX()) **2)+ ((block2.getCenterY() - block1.getCenterY())**2)) < BLOCK_SIZE:
         print("true")
         return True
     else:
         return False
 ------------------------------------------------------- not part of functiom
    if collide(theSnake[0],food) == True:
    food.undraw()
    foodX = random.randint(BLOCK_SIZE, WIN_WIDTH-BLOCK_SIZE)
    foodY = random.randint(BLOCK_SIZE, WIN_HEIGHT-BLOCK_SIZE)
    food.draw()
    theSnake.append(block)

    else:
    foodX = foodX
    foodY = foodY

Tags: 函数sizereturniffoodblockprintblock1
1条回答
网友
1楼 · 发布于 2024-10-03 02:38:19

我建议您修改碰撞函数以提供更多信息。例如

def collide(block1,block2):
    dx = block2.getCenterX() - block1.getCenterX()
    dy = block2.getCenterY() - block1.getCenterY()
    dist = math.sqrt(dx ** 2 + dy ** 2) # equivalent to math.hypot(dx, dy)
    if dist < BLOCK_SIZE:
        print("true")
        return True
    else:
        print("false", dx, dy, dist)
        return False

相关问题 更多 >