8.豌豆绘制以及发射、撞击的判定
豌豆发射的判定
首先是豌豆发射的判定,这个的方法有很多,这里介绍我的方法。
首先遍历场上所有植物,如果当前植物是豌豆射手且僵尸在当前行且僵尸位于豌豆射手前面则发射豌豆。
1 2 3 4 5 6 7 8 9
| void toShoot() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { if (zb[i][j] == 2 && zombielist->gy==j+1 && zombielist->gx > i) { insertPea(peaslist, Pea_offset + cur_Width * i, Pea_offset + cur_Height * j, i + 1, j + 1); } } } }
|
需要注意这里的i和j都是从0开始的,所以说加1才是行列数。
插入豌豆节点的函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| void insertPea(peas* head, int x, int y, int gx, int gy) { peas* nowpea = (peas*)malloc(sizeof(peas)); nowpea->x = x; nowpea->y = y; nowpea->gx = gx; nowpea->gy = gy; nowpea->status = 1; nowpea->next = NULL; if (head->status == -100) { head->x = x; head->y = y; head->gx = gx; head->gy = gy; head->status = 1; head->next = NULL; return; } else { peas* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = nowpea; } }
|
因为在前面创建豌豆链表时我们说过,status为-100表示为头节点并且无数据,所以这里判断若是头节点且无数据则插入数据到头节点。
豌豆撞击的判定
在这里,我们需要遍历所有豌豆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void peaHitZombie() { for (peas* pea = peaslist; pea != NULL && pea->status !=-100; pea = pea->next) { if (pea->x >= zombielist->x + zombiepngedge+30 && pea->x <= zombielist->x+ zombiepngedge+ zombiewidth && pea->gy == zombielist->gy && zombielist->hp > 0 && pea->status == 1 ) { pea->status = 0; putimagePNG(pea->x, pea->y, &picgroup[7]); zombielist->hp -= peashooterattack; credit -= 5; break; } if (pea->x > 810 || pea->x < -10) { pea->status = 0; } } }
|
这里遍历豌豆链表所有节点,若豌豆的位置与僵尸位置相等,则产生碰撞,将豌豆的状态设置为0,并绘制豌豆爆炸的图片,僵尸减少相应血量,减少积分。此时break跳出循环,因为一个豌豆只能击中一个僵尸。
(这里的
pea->x >= headZombie->x + zombiepngedge+30 && pea->x <= headZombie->x+ zombiepngedge+ zombiewidth
表示判断豌豆是否在僵尸位置的一定范围内)
另外,若豌豆没有击中僵尸(玩家操纵僵尸躲避了豌豆),那么在豌豆超出场景也将豌豆状态设置为0。
豌豆的绘制
1 2 3 4 5 6 7 8 9 10
| void drawPeas() { peas* temp = peaslist; while (temp != NULL && temp->status != -100) { if (temp->status == 1) { putimagePNG(temp->x, temp->y, &picgroup[6]); temp->x = temp->x + 10; } temp = temp->next; } }
|
非常简单,遍历豌豆链表,如果豌豆状态为1则绘制豌豆,并改变豌豆坐标,实现豌豆的移动。