`
woxiaoe
  • 浏览: 276897 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

DELPHI中使用Tlist类的简单分析

阅读更多

我在上面的BLOG中写到了使用指针的方法。在DELPHI中指针最常见的就是和类TLIST结合起来使用。下面是一个很简单的例子,希望对这个例子的分析能让大家对使用TLIST类有一个简单的认识。
代码的功能是使用指针和Tlist来生成一个牌串,并将牌串保存在t_CardInfo中。
 
procedure TForm1.Button1Click(Sender: TObject);
const
  //黑桃,红桃,方块,草花
  CardType:array[0..3] of String = ('S','H','D','C');
const
  //取出的牌数
  CardNums = 4;
type
  //保存牌的指针信息
  RCardrecord = record
    CardInfo:String[2];
  end;
  PCard = ^RCardrecord;
var
  t_List:TList;
  I:Integer;
  t_Sub,t_Spare:Integer;
  t_CardType,t_CardNum:String;
  p_Card:PCard;
  t_Random:Integer;
  t_CardInfo:String[8];
  Count:Integer;
begin
  //定义一个链表
  t_List:=TList.Create;
  //使用循环将52张牌放入链表中
  for I:=1 to 52 do
  begin
    t_Sub:=I div 14;
    t_Spare:=I mod 14;
    t_CardType:=CardType[t_Sub];
    t_CardNum:=IntToHex(t_Spare,1);
    New(p_Card);
    p_Card.CardInfo:=t_CardType+t_CardNum;
    t_List.Add(p_Card);
  end;
  //使用随机从52张牌中抽取4张牌,并保存在 t_CardInfo中
  Randomize;
  for I:=1 to CardNums do
  begin
    t_Random:=Random(t_List.Count);
    p_Card:=t_List.Items[t_Random];
    t_CardInfo:=t_CardInfo+p_Card^.CardInfo;
    t_List.Delete(t_Random);
    DisPose(p_Card);
  end;
  //清空链表中的指针
  Count:=t_List.Count;
  for I:=Count-1 downto 0 do
  begin
    p_Card:=t_List.Items[I];
    t_List.Delete(I);
    DisPose(p_Card);
  end;
  //释放链表
  t_List.Free;
end;
 
分析:
1:我们首先创建一个Tlist类的对象t_List。
2:将52张牌按照相应的格式保存在这个t_List中。注意,这里t_List中保存的是每个牌的指针。在Tlist中的保存格式类似于下图:
3:随机从这个链表中取出4个指针,并将指针对应的牌信息保存在变量t_CardInfo。因为在将指针插入到t_List中的时候,我们使用了New函数来申请内存,所以当从链表中删除这个指针的时候,一定要使用Dispose函数来释放,否则会形成内存泄露。
4:将t_List中剩余的指针释放。
5:释放对象t_List对象。
 
 
使用类Tlist在开发游戏中有很重要的位置,使用方法大多如我上面所写的这样。
本文出自 “狗窝” 博客,请务必保留此出处http://fxh7622.blog.51cto.com/63841/29548 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics