Author: Jonas Bilinkevicius
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:
1 unit KeysForm;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 ExtCtrls;
8
9 type
10 TForm1 = class(TForm)
11 Timer1: TTimer;
12 procedure Timer1Timer(Sender: TObject);
13 procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
14 procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
15 procedure FormCreate(Sender: TObject);
16 procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
17 Shift: TShiftState; X, Y: Integer);
18 procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
19 Shift: TShiftState; X, Y: Integer);
20 private
21 { Private declarations }
22 public
23 { Public declarations }
24 end;
25
26 var
27 Form1: TForm1;
28 Keys: array[Byte] of Boolean;
29
30 implementation
31
32 {$R *.DFM}
33
34 procedure TForm1.Timer1Timer(Sender: TObject);
35 var
36 KeyNum, c: Integer;
37 begin
38 for KeyNum := 0 to 255 do
39 begin
40 c := Ord(Keys[KeyNum]) * 255;
41 Canvas.Pixels[KeyNum * 2, 10] := RGB(c, c, c);
42 Canvas.Pixels[KeyNum * 2 + 1, 10] := RGB(c, c, c);
43 Canvas.Pixels[KeyNum * 2 + 1, 11] := RGB(c, c, c);
44 Canvas.Pixels[KeyNum * 2, 11] := RGB(c, c, c);
45 end;
46 end;
47
48 procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
49 begin
50 Keys[Key] := True;
51 Key := 0;
52 end;
53
54 procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
55 begin
56 Keys[Key] := False;
57 Key := 0;
58 end;
59
60 procedure TForm1.FormCreate(Sender: TObject);
61 var
62 KeyNum: Integer;
63 begin
64 for KeyNum := 0 to 255 do
65 Keys[KeyNum] := False;
66 end;
67
68 procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
69 Shift: TShiftState; X, Y: Integer);
70 begin
71 if (Button = mbLeft) then
72 Keys[VK_LBUTTON] := True
73 else if (Button = mbMiddle) then
74 Keys[VK_MBUTTON] := True
75 else if (Button = mbRight) then
76 Keys[VK_RBUTTON] := True;
77 end;
78
79 procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
80 Shift: TShiftState; X, Y: Integer);
81 begin
82 if (Button = mbLeft) then
83 Keys[VK_LBUTTON] := False
84 else if (Button = mbMiddle) then
85 Keys[VK_MBUTTON] := False
86 else if (Button = mbRight) then
87 Keys[VK_RBUTTON] := False;
88 end;
89
90 end.
|