unit uCard;
// 單元: 可視化組件 ——撲克牌組件
// 作者: 黃濤
// E_Mail: [email protected]
// 日期: 2004.12.7
// 修改日期: 2004.12.8interface
uses Windows,Messages,classes,Graphics,controls,dialogs;
type
//樸克的花色定義,分別是黑桃、紅心、方塊、梅花
TCardSuit=( CSSpade,csHeart,csClub,csDiamond);
TCard =class(TGraphicControl) //撲克的組件
private
FCardId:Cardinal ; //撲克的編號,0-51為各花色的1-K,52為大王,53小王
FFaceUp:bool; //是否正面朝上
procedure SetCardId(id:Cardinal);//設置撲克牌的編號
procedure SetFaceUp(Flag:Bool); //設置是否正面朝上
function GetValue:integer; //得到撲克牌的點數
function GetSuit:TCardSuit; //得到撲克牌的花色
protected
procedure Paint; override; //畫撲克牌的程序
public
constructor Create(AOwner:TComponent);overload;override; //構造函數
constructor Create(AOwner:TComponent;Id:Cardinal);overload;
procedure SetCard(Suit:TCardSuit;Value:Cardinal); //設置撲克牌的編號
published
property CardId:Cardinal read FCardId write SetCardId; //撲克牌編號
property FaceUp:bool read FFaceUp write SetFaceUp default False; //正面朝上
property Value:integer read GetValue; //撲克的點數,只讀
property Suit:TCardSuit read GetSuit; //撲克的花色,只讀
property OnClick; //單擊
property OnDblClick; //雙擊
end;
implementation
{$R Card.res}{ TCard }
var CardMap:TBitmap; //撲克牌的圖形,從Card.res中獲取
constructor TCard.Create(AOwner: TComponent);
begin
inherited; //如果父控件是WINDOWCONTROL的話,設置其Parent屬性
if Aowner is TWinControl then self.Parent := TWinControl(Aowner);
Width:=CardMap.Width div 14; //得到撲克牌的寬度
Height:=CardMap.Height div 4; //得到撲克牌的高度
FaceUp:=False; //默認撲克牌朝下
end;constructor TCard.Create(AOwner: TComponent;Id: Cardinal);
begin
Create(AOwner);
CardId:=Id; //設置撲克牌的編號
end;procedure TCard.SetCardId(id:Cardinal);
begin
if id<54 then FCardId:=id; //設置撲克牌的編號
Paint; //重新畫撲克牌
end;procedure TCard.SetCard(Suit:TCardSuit; Value: Cardinal);
begin
dec(Value);
CardId:=Value shl 2 + Cardinal(Suit) and 3;//設置撲克牌的編號並重畫
end;procedure TCard.Paint; //畫撲克牌
var x,y,tmp:integer;
begin
if not assigned(Parent) then exit;//如果沒有定義父控件,直接退出,以免報錯
inherited;
if FaceUp then tmp:=CardId //如果面朝上,則畫正面
else tmp:=54; //反之畫背面
x:=(tmp shr 2)*Width; //該撲克牌在位圖中橫坐標的位置
y:=(tmp and 3)*Height; //該撲克牌在位圖中縱坐標的位置
bitblt(Canvas.Handle,0,0,Width,Height, //畫圖
CardMap.Canvas.Handle ,x,y,SRCCOPY);
end;procedure TCard.SetFaceUp(Flag: Bool);//設置牌面朝上還是朝下
begin
FFaceUp:=Flag;
Paint; //重畫
end;function TCard.GetValue: integer;
begin
Result:=CardId shr 2; //得到該牌的值
inc(Result);
end;function TCard.GetSuit:TCardSuit;
begin
Result:=TCardSuit(CardId and 3); //得到該牌的花色
end;initialization //單元初始化
CardMap:=TBitmap.create ; //創建位圖
CardMap.LoadFromResourceName(HINSTANCE,'card');//從資源中導入
finalization
CardMap.Free ;//清除位圖
end.