贪吃蛇项目实践!(下)

2024-05-08 08:38:27 浏览数 (2)

NextIsFood

比较蛇指向的节点和食物指向的节点是否相同

代码语言:javascript复制
//pSnakeNode psn 是下⼀个节点的地址
//pSnake ps 维护蛇的指针
int NextIsFood(pSnakeNode psn, pSnake ps)
{
      return (psn->x == ps->_pFood->x) && (psn->y == ps->_pFood->y);
}

EatFood

代码语言:javascript复制
//pSnakeNode psn 是下⼀个节点的地址
//pSnake ps 维护蛇的指针
void EatFood(pSnakeNode psn, pSnake ps)
{
      //头插法
    psn->next = ps->_pSnake;
    ps->_pSnake = psn;
     //打印蛇
    pSnakeNode cur = ps->_pSnake;
    while (cur)
    {
        SetPos(cur->x, cur->y);
        wprintf(L"%c", BODY);
        cur = cur->next;
     }
    ps->_Socre  = ps->_foodWeight;
    //释放⻝物节点
    free(ps->_pFood);
    //创建新的⻝物
    CreateFood(ps);
}

NoFood

将下⼀个节点头插⼊蛇的⾝体,并将之前蛇⾝最后⼀个节点打印为空格,释放掉蛇⾝的最后⼀个节 点。

易错点:这⾥最容易错误的是,释放最后⼀个结点后,还得将指向在最后⼀个结点的指针改为NULL,保证蛇尾打印可以正常结束,不会越界访问。

代码语言:javascript复制
//pSnakeNode psn 是下⼀个节点的地址
//pSnake ps 维护蛇的指针
void NoFood(pSnakeNode psn, pSnake ps)
{
   //头插法
   psn->next = ps->_pSnake;
   ps->_pSnake = psn;
   //打印蛇
   pSnakeNode cur = ps->_pSnake;
   while (cur->next->next)
   {
       SetPos(cur->x, cur->y);
       wprintf(L"%c", BODY);
       cur = cur->next;
    }
//最后⼀个位置打印空格,然后释放节点
   SetPos(cur->next->x, cur->next->y);
   printf(" ");
   free(cur->next);
   cur->next = NULL;
}

KillByWall

代码语言:javascript复制
//pSnake ps 维护蛇的指针
int KillByWall(pSnake ps)
{
    if ((ps->_pSnake->x == 0)
    || (ps->_pSnake->x == 56)
    || (ps->_pSnake->y == 0)
    || (ps->_pSnake->y == 26))
   {
      ps->_Status = KILL_BY_WALL;
      return 1;
    }
return 0;
}

KillBySelf

判断蛇头的坐标是否和蛇⾝体的坐标冲突

代码语言:javascript复制
//pSnake ps 维护蛇的指针
int KillBySelf(pSnake ps)
{
    pSnakeNode cur = ps->_pSnake->next;
    while (cur)
    {
      if ((ps->_pSnake->x == cur->x)&& (ps->_pSnake->y == cur->y))
      {
          ps->_Status = KILL_BY_SELF;
          return 1;
       }
      cur = cur->next;
    }
    return 0;
}

游戏结束

代码语言:javascript复制
void GameEnd(pSnake ps)
{
    pSnakeNode cur = ps->_pSnake;
    SetPos(24, 12);
    switch (ps->_Status)
    {
       case END_NOMAL:
          printf("您主动退出游戏n");
          break;
       case KILL_BY_SELF:
          printf("您撞上⾃⼰了 ,游戏结束!n");
          break;
       case KILL_BY_WALL:
          printf("您撞墙了,游戏结束!n");
          break;
     }
     //释放蛇⾝的节点
    while (cur)
    {
       pSnakeNode del = cur;
       cur = cur->next;
       free(del);
     }
}

至此,我们的贪吃蛇项目就完结啦,我们下一个栏目见!

0 人点赞