2005. április 23., szombat

How to handle multiple, simultaneous key presses


Problem/Question/Abstract:

If I want to write a simple game where you can move and shoot at the same time, what would be the best way of handling the multiple key presses?

Answer:

unit KeysForm;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls;

type
  TForm1 = class(TForm)
    Timer1: TTimer;
    procedure Timer1Timer(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormCreate(Sender: TObject);
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  Keys: array[Byte] of Boolean;

implementation

{$R *.DFM}

procedure TForm1.Timer1Timer(Sender: TObject);
var
  KeyNum, c: Integer;
begin
  for KeyNum := 0 to 255 do
  begin
    c := Ord(Keys[KeyNum]) * 255;
    Canvas.Pixels[KeyNum * 2, 10] := RGB(c, c, c);
    Canvas.Pixels[KeyNum * 2 + 1, 10] := RGB(c, c, c);
    Canvas.Pixels[KeyNum * 2 + 1, 11] := RGB(c, c, c);
    Canvas.Pixels[KeyNum * 2, 11] := RGB(c, c, c);
  end;
end;

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  Keys[Key] := True;
  Key := 0;
end;

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  Keys[Key] := False;
  Key := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  KeyNum: Integer;
begin
  for KeyNum := 0 to 255 do
    Keys[KeyNum] := False;
end;

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if (Button = mbLeft) then
    Keys[VK_LBUTTON] := True
  else if (Button = mbMiddle) then
    Keys[VK_MBUTTON] := True
  else if (Button = mbRight) then
    Keys[VK_RBUTTON] := True;
end;

procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if (Button = mbLeft) then
    Keys[VK_LBUTTON] := False
  else if (Button = mbMiddle) then
    Keys[VK_MBUTTON] := False
  else if (Button = mbRight) then
    Keys[VK_RBUTTON] := False;
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése