如何检查蛇游戏中的蛇是否越过了食物?

2024-10-02 10:33:02 发布

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

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

我试着把食物的位置设为10的倍数,因为我的蛇的宽度和高度也是10,窗户(宽度和高度)也是10的倍数。你知道吗

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

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


Tags: 游戏编码宽度高度foodrandompygame食物
1条回答
网友
1楼 · 发布于 2024-10-02 10:33:02

因此,假设您的snake数据结构是一组矩形,并且snake只“吃”头部矩形,那么确定碰撞例程非常简单。你知道吗

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的库矩形重叠函数要比创建自己的库简单得多。你知道吗

相关问题 更多 >

    热门问题