DELPHI中指针和类TLIST结合

在DELPHI中指针最常见的就是和类TLIST结合起来使用。下面是一个很简单的例子,希望对这个例子的分析能让大家对使用TLIST类有一个简单的认识。

代码的功能是使用指针和Tlist来生成一个牌串,并将牌串保存在t_CardInfo中。

ContractedBlock.gifCode

 分析:
1:我们首先创建一个Tlist类的对象t_List。
2:将52张牌按照相应的格式保存在这个t_List中。注意,这里t_List中保存的是每个牌的指针。
3:随机从这个链表中取出4个指针,并将指针对应的牌信息保存在变量t_CardInfo。因为在将指针插入到t_List中的时候,我们使用了New函数来申请内存,所以当从链表中删除这个指针的时候,一定要使用Dispose函数来释放,否则会形成内存泄露。
4:将t_List中剩余的指针释放。 [Page]
5:释放对象t_List对象。
 
 
使用类Tlist在开发游戏中有很重要的位置,使用方法大多如我上面所写的这样。

ExpandedBlockStart.gif
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; 

 

转载于:https://www.cnblogs.com/wxf82610/archive/2009/02/25/1398003.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值