unit TFMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TTiles = record
TType: Byte; //0=Traversable, 1=Wall
Image: Byte;
end;
type
TMap = class
AreaName: String;
Tiles: array[1..15, 1..15] of TTiles;
Screen: TBitmap;
Buffer: TBitmap;
{***
Innecesary
published
***}
public
constructor Create;
destructor Destroy; override;
end;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Map: TMap;
implementation
{$R *.dfm}
constructor TMap.Create;
var
i, j: Integer;
begin
inherited Create;
Screen := TBitmap.Create;
Buffer := TBitmap.Create;
AreaName := 'Map';
for i := 1 to 15 do
for j := 1 to 15 do
begin
Tiles[j, i].TType := 0;
Tiles[j, i].Image := 1;
end;
end;
destructor TMap.Destroy;
begin
Screen.Free;
Buffer.Free;
{***
FreeAndNil(self); <-- BAD, NEVER
***}
{"inherited" not really needed in a TObject (it does nothing),
but better making the discipline of calling it in every object.}
inherited;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i, j: Integer;
Tile, Dest, View: TRect;
Image: TBitmap;
begin
Map := TMap.Create;
Tile.Left := 0;
Tile.Top := 0;
Tile.Right := 40;
Tile.Bottom := 40;
View.Left := 0;
View.Top := 0;
View.Right := 40*15;
View.Bottom := 40*15;
{Quick and dirty: set the sizes.
Better doing this in Map.Create.}
Map.Screen.Width := View.Right;
Map.Screen.Height := View.Bottom;
Map.Buffer.Width := View.Right;
Map.Buffer.Height := View.Bottom;
Image := TBitmap.Create;
Image.LoadFromFile('TDirt.bmp');
for i := 1 to 15 do
begin
Dest.Top := 40 * (i - 1);
Dest.Bottom := 40 * i;
for j := 1 to 15 do
begin
{*** Old coordinates was mirrored left-right
Dest.Right := 40 * (j - 1);
Dest.Left := 40 * j;
***}
Dest.Left := 40 * (j - 1);
Dest.Right := 40 * j;
{***
From the manual: "Use CopyRect to transfer part of
the image on (FROM) ANOTHER canvas TO the image of
the TCanvas object."
IE: wrong copy.
Image.Canvas.CopyRect(Dest, Map.Buffer.Canvas, Tile);
***}
{Copy FROM Image TO Buffer}
{ .... DESTINATION .... SOURCE }
{ | | }
Map.Buffer.Canvas.CopyRect(Dest, Image.Canvas, Tile);
end;
end;
{*** Wrong copy
Map.Buffer.Canvas.CopyRect(View, Map.Screen.Canvas, View);
***}
{Copy FROM Buffer TO Screen}
Map.Screen.Canvas.CopyRect(View, Map.Buffer.Canvas, View);
{Quick and dirty: copy TO the form canvas.
NOTE: drawing lost if the windows is minimized, covered,
the debugger steps, etc.}
Canvas.CopyRect(View, Map.Screen.Canvas, View);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
{Lets know if the object is actually created.}
Map := nil;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
{***
Never call Destroy in an object.
Map.Destroy;
***}
{Call conditionally: only if user clicked the button.}
if Map <> nil
then Map.Free;
end;
end.