mooc自学网址:
https://www.icourse163.org/learn/CUC-1450328379?tid=1450742649#/learn/content?type=detail&id=1216695336&sm=1(源自中国传媒大学韩红雷老师的课程和他出版的书籍《《游戏开发程序设计基础》》)
第十一章(1)
十一章中的第一个应用程序是指针的高级应用,利用链表建立一个玩家的信息管理系统,里面用到了关于链表最常见的增删改查操作。具体的内容是创建一个玩家结构体,并建立相应的链表。玩家结构体的信息包括名字、生命值、魔法值,这些值都采用随机生成。然后是将增删改查操作在链表中一一进行应用。
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<time.h>
typedef struct P{ //创建玩家结构体,包括生命值、魔法值、名字和指向下一个节点的指针
float hp;
float mp;
char name[16];
struct P*next;
}Player;
typedef struct //创建链表头节点,包括玩家数、指向第一个玩家节点的指针
{
int num;
Player* next;
}PlayerLinkedList;
void AddNewPlayer(PlayerLinkedList* head,Player* newPlayer){ //利用头插法插入新节点
newPlayer->next=head->next;
head->next=newPlayer;
head->num++;
}
void RemovePlayer(PlayerLinkedList* head,Player* player){ //移除节点(r)
Player* p=head->next;
if(p==player){ //若删除的节点是第一个,直接进行移除
head->next=p->next;
free(p);
head->num--;
return;
}
while(p->next!=player&&p->next!=NULL) //否则进行遍历,记录要删除节点的前一节点和后一节点进行移除
p=p->next;
if(p->next==player){
Player* tmp=p->next->next;
free(p->next);
p->next=tmp;
head->num--;
}
}
Player* FindByName(PlayerLinkedList* head,char* name){ //按名字查找节点
Player* p=head->next;
while(p!=NULL&&strcmp(p->name,name)!=0)
p=p->next;
return p;
}
Player* SortByHP(Player* first){ //按生命值由小到大进行排序
if(first==NULL || first->next==NULL) //如果只有一个节点直接返回
return first;
Player* minPre=first;
Player* p=first->next;
while(p->next!=NULL){ //找到生命值最少的节点,minPre为该节点的前一节点
if(p->next->hp<minPre->next->hp)
minPre=p;
p=p->next;
}
if(minPre->next->hp<first->hp){ //插入到前面
p=minPre->next;
minPre->next=p->next;
p->next=first;
first=p;
}
first->next=SortByHP(first->next); //进行递归
return first;
}
void Print(PlayerLinkedList* head){ //输出所有的节点信息
Player* p=head->next;
while(p!=NULL)
{
printf("%s,%.2f,%.2f\t",p->name,p->hp,p->mp);
p=p->next;
}
printf("\n");
}
void Destroy(PlayerLinkedList* head){ //删除链表
Player* p=head->next;
player* q=p->next;
while(q!=NULL){
q=p->next;
free(p);
p=q;
}
free(head);
}
int main()
{
srand(time(NULL)); //设置随机种子
PlayerLinkedList* head=(PlayLinkedList*)malloc(sizeof(PlayerLinkedList)); //动态创建头结点
head->next=NULL;
head->num=0;
int nCand=rand()%20; //生成20以内的随机数并建立指向要找的节点的指针
char*find=NULL;
for(int i=0;i<20;i++) //随机生成20个节点及相关信息,并插入到链表中
{
Player* p=(Player*)malloc(sizeof(Player));
p->hp=(rand()%101)/100.0f;
p->mp=(rand()%101)/100.0f;
p->name[0]='A'+rand()%26;
p->name[1]='A'+rand()%26;
p->name[2]='A'+rand()%26;
p->name[3]='\0';
AddNewPlayer(head,p);
if(nCand==i) //记录下第随机个节点的名字
find=p->name;
}
Print(head); //输出所有节点信息
Player* p=FindByName(head,find); //按名查找记录的节点,并输出,再移除
printf("The player found:name:%s,hp:%.2f,mp:%.2f\n",p->name,p->hp,p->mp);
RemovePlayer(head,p);
printf("Remove it from the list\n");
head->next=SortByHP(head->next); //对链表进行排序后输出
Print(head);
Destroy(head); //删除与链表
return 0;
}