练习36 内存的动态分配实现雷霆战机小游戏
点击蓝字
关注我们
DRAGON BOAT FESTIVAL
练习36
01 要求:
使用内存的动态分配实现雷霆战机小游戏
02 程序示例如下:
所用到的知识点:
1.结构体 struct
2.动态链表
3.条件语句 if
1.循环语句 while
5.指针 *p
6.内存的动态分配
#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include <time.h>
#include <conio.h>
#pragma comment(lib,"winmm.lib")
//子弹 敌机
typedef struct Node
{
int x;
int y;
struct Node* pnext;
}ZiDan,DiJi;
ZiDan* pZidan = NULL; //pZidan 链表
DiJi* pDiJi = NULL; //pDiJi 链表
int xx = 100;
int yy = 500;
//创建链表
void CreateList()
{
//子弹
pZidan = (ZiDan*)malloc(sizeof(ZiDan));
pZidan->pnext = NULL; //防止野指针
//敌机
pDiJi = (DiJi*)malloc(sizeof(DiJi));
pDiJi->pnext = NULL; //防止野指针
}
//增加节点
void AddNode(Node* P,int a) //形参 接收实参 a 区分到底是子弹还是敌机
{
//定义一个新的节点
Node* pnew = NULL;
//为新的节点开辟空间
pnew = (Node*)malloc(sizeof(Node));
if (a == 1) //子弹
{
//填充节点的内容
pnew->x = xx;
pnew->y = yy;
}
else if (a == 2) //敌机
{
pnew->x = rand() % 450;
pnew->y = 0;
}
//把节点连接起来
pnew->pnext =P->pnext;
P->pnext = pnew;
}
//判断子弹打到敌机
void Shoot()
{
DiJi* pdr = pDiJi->pnext; //临时的敌人节点用来遍历
DiJi* pdrpre = pDiJi; //pdr前一个节点 删除掉pdr
ZiDan* pzd = pZidan->pnext; //临时的子弹节点 用来遍历子弹链表
ZiDan* pzdpre = pZidan;
while (pdr != NULL) //遍历所有的敌机
{
pzd = pZidan->pnext;
pzdpre = pZidan;
while (pzd != NULL)
{
if (pzd->x >= pdr->x - 10 && pzd->x <= pdr->x + 50 &&
pzd->y >= pdr->y - 20 && pzd->y <= pdr->y + 20)
{
pzdpre->pnext = pzd->pnext; //前一个和后一个连起来
free(pzd);
pdrpre->pnext = pdr->pnext;
free(pdr);
pdr = pDiJi->pnext;
pdrpre = pDiJi;
break;
}
else
{
pzd = pzd->pnext;
pzdpre = pzdpre->pnext;
}
}
pdr = pdr->pnext;
pdrpre = pdrpre->pnext;
}
}
int main()
{
initgraph(500, 600);
char ch;
PlaySound(L"./res/The Mass.wav", NULL, SND_LOOP | SND_FILENAME | SND_ASYNC);
srand((unsigned int)time(NULL));
//增加子弹的个数
//初始值位置 100 500
//创建链表
CreateList();
while (1)
{
//======================敌机================================================
//添加节点
AddNode(pDiJi, 2);
//显示节点的内容(数据用到绘制矩形上面去)
Node* ptemp1 = pDiJi->pnext;
while (ptemp1 != NULL)
{
//使用节点中的数据去绘制矩形
rectangle(ptemp1->x, ptemp1->y, ptemp1->x + 50, ptemp1->y + 20);
//控制这个矩形的移动
ptemp1->y += 20;
//指向下一个节点
ptemp1 = ptemp1->pnext;
}
//=======================子弹================================================
//添加节点
AddNode(pZidan,1);
Sleep(100);
cleardevice();
//显示节点的内容(数据用到绘制矩形上面去)
Node* ptemp = pZidan->pnext;
while (ptemp != NULL)
{
//使用节点中的数据去绘制矩形
rectangle(ptemp->x, ptemp->y, ptemp->x + 10, ptemp->y + 20);
//控制这个矩形的移动
ptemp->y -= 20;
//指向下一个节点
ptemp = ptemp->pnext;
}
Shoot();
if (kbhit())
{
ch = getch();
switch (ch)
{
case 75:
xx -= 10;
break;
case 77:
xx += 10;
break;
}
}
}
return 0;
}
03:输出:
球分享
球点赞
球在看
评论