Einzelnen Beitrag anzeigen

zeras

Registriert seit: 11. Mär 2007
Ort: Saalkreis
1.643 Beiträge
 
Delphi 12 Athens
 
#4

AW: Tic Tac Toe - Scorekeeper in Datenbank oder Text File speichern

  Alt 12. Mär 2023, 17:30
Ich habe mal OpenAI gefragt. Darf man das überhaupt dann hier posten?
Hier die Antwort. Vielleicht hilft das dir.

Delphi-Quellcode:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    lblScore: TLabel;
    btnAddPoint: TButton;
    btnSave: TButton;
    edtName: TEdit;
    Label1: TLabel;
    procedure btnAddPointClick(Sender: TObject);
    procedure btnSaveClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    FScore: Integer;
    FUserName: string;
    FFileName: string;
    procedure UpdateScoreLabel;
    procedure SaveScore;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.UpdateScoreLabel;
begin
  lblScore.Caption := IntToStr(FScore);
end;

procedure TForm1.btnAddPointClick(Sender: TObject);
begin
  Inc(FScore);
  UpdateScoreLabel;
end;

procedure TForm1.btnSaveClick(Sender: TObject);
begin
  FUserName := edtName.Text;
  SaveScore;
end;

procedure TForm1.SaveScore;
var
  FileStream: TFileStream;
  Writer: TBinaryWriter;
begin
  FileStream := TFileStream.Create(FFileName, fmCreate);
  try
    Writer := TBinaryWriter.Create(FileStream);
    try
      Writer.Write(FUserName);
      Writer.Write(FScore);
    finally
      Writer.Free;
    end;
  finally
    FileStream.Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FFileName := ExtractFilePath(Application.ExeName) + 'scores.dat';
  if FileExists(FFileName) then
  begin
    var FileStream := TFileStream.Create(FFileName, fmOpenRead);
    try
      var Reader := TBinaryReader.Create(FileStream);
      try
        FUserName := Reader.ReadString;
        FScore := Reader.ReadInteger;
        UpdateScoreLabel;
      finally
        Reader.Free;
      end;
    finally
      FileStream.Free;
    end;
  end;
end;

end.
Matthias
Es ist nie falsch das Richtige zu tun!
- Mark Twain
  Mit Zitat antworten Zitat