2004. január 20., kedd

How to save multiple records and an integer into one file


Problem/Question/Abstract:

I am writing an adventure game and need to store information in a save game. The game requires data from 3 different records and one variable

record1 = hotspot scene information(50 recs),
record2 = conversation information (60 recs),
record3 = hypertext information(50 recs)
variable = integer - # of scene currently on.

My problem is that I need to seek for a particular record of particular type in the file (I do not want to have to keep huge arrays of records in memory). I know how to do this with a file containing records of only one record type but have no clue how to combine all three records and one integer into a single random access file.

Answer:

I generally use a file with a header, then just keep the header in memory and use it to seek to the records I need.

type
  TSaveHeader = record
    scene: Integer;
    hotspots: LongInt;
    talk: LongInt;
    hype: LongInt;
  end;

var
  SaveHeader: TSaveHeader;

procedure OpenSaveFile(fname: string);
var
  f: file;
  i: Integer;
begin
  AssignFile(f, fname);
  Reset(f, 1);
  BlockRead(f, SaveHeader, Sizeof(TSaveHeader));
  { get one set of records }
  Seek(f, SaveHeader.hotspots);
  for i := 1 to 50 do
    BlockRead(f, somevar, sizeof_hotspotrec);
  { and so on }
  CloseFile(f);
end;

{ assuming the file is open }

procedure GetHotspotRec(index: LongInt; var hotspotrec: THotspot);
var
  offset: LongInt;
begin
  offset := SaveHeader.hotspots + index * Sizeof(THotSpot);
  Seek(f, offset);
  BlockRead(f, hotspotrec, Sizeof(THotspot));
end;

Nincsenek megjegyzések:

Megjegyzés küldése