【问题标题】:How to check if the Snake in a snake game has crossed the food?如何检查蛇游戏中的蛇是否穿过食物?
【发布时间】:2019-03-26 05:06:33
【问题描述】:

我正在使用 python 和 pygame 开发一个蛇游戏,但在检查蛇是否穿过食物时遇到问题。这里有人可以帮我吗?

我尝试将食物的位置设为 10 的倍数,因为我的蛇的宽度和高度也是 10,而窗口(宽度和高度)也是 10 的倍数。

food_x = random.randrange(0, displayWidth-foodWidth, 10)
food_y = random.randrange(0, displayHeight-foodHeight, 10)

我希望这样做会使食物的位置不会发生碰撞,而是蛇和食物直接重叠,这将使编码更容易。但是,也有碰撞。

【问题讨论】:

  • 你如何定义你的“蛇”——一堆矩形?它只从头端吃吗?
  • 是的,我也做过同样的事情。你能帮我进行碰撞检测吗? @金斯利

标签: python pygame collision-detection collision


【解决方案1】:

因此,鉴于您的蛇数据结构是一组矩形,而蛇只“吃”头部矩形,确定碰撞例程非常简单。

PyGame rect library 在矩形之间具有checking collisions 的函数。

所以假设head_rect 是一个rect 与你的蛇头的坐标和大小,food_rect 是一个要检查的项目:

if ( head_rect.colliderect( food_rect ) ):
    # TODO - consume food

或者如果food_list中有food_rect的列表:

def hitFood( head_rect, food_list ):
    """ Given a head rectangle, and a list of food rectangles, return 
        the first item in the list that overlaps the list items.  
        Return None for a no-hit """
    food_hit = None
    collide_index = head_rect.collidelist( food_list )
    if ( collide_index != -1 ):
        # snake hit something
        food_hit = food_list.pop( collide_index )
    return food_hit

使用 PyGame 的库矩形重叠函数要容易得多,而不是自己制作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 2020-12-31
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多