Debian Codegraph @

examples/tiled/strategy_game_demo/code/gameviewplay.pas

raw
1 {
2 Copyright 2018-2022 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Display the game map, play the game. }
17 unit GameViewPlay;
18
19 interface
20
21 uses Classes,
22 CastleControls, CastleTiledMap, CastleUIControls, CastleTransform,
23 CastleVectors, CastleKeysMouse, CastleScene, CastleViewport,
24 GameUnit;
25
26 type
27 TViewPlay = class(TCastleView)
28 published
29 { Components designed using CGE editor.
30 These fields will be automatically initialized at Start. }
31 Map: TCastleTiledMap;
32 ButtonQuit: TCastleButton;
33 ButtonInstructions, ButtonInstructions2: TCastleButton;
34 ButtonEndTurn: TCastleButton;
35 LabelStatus, LabelTurnStatus: TCastleLabel;
36 ViewportMap: TCastleViewport;
37 strict private
38 TileUnderMouseImage: TCastleImageTransform;
39 SelectedUnitVisualization: TCastleTransform;
40 TileUnderMouseExists: Boolean;
41 TileUnderMouse: TVector2Integer;
42 UnitsOnMap: TUnitsOnMap;
43 HumanTurn: Boolean;
44 SelectedUnit: TUnit;
45 procedure ClickQuit(Sender: TObject);
46 procedure ClickInstructions(Sender: TObject);
47 procedure ClickInstructions2(Sender: TObject);
48 procedure ClickEndTurn(Sender: TObject);
49 procedure UpdateTurnStatus;
50 public
51 { Set this before starting this view. }
52 MapName: String;
53 constructor Create(AOwner: TComponent); override;
54 procedure Start; override;
55 procedure Stop; override;
56 procedure Update(const SecondsPassed: Single;
57 var HandleInput: boolean); override;
58 function Press(const Event: TInputPressRelease): Boolean; override;
59 end;
60
61 var
62 ViewPlay: TViewPlay;
63
64 implementation
65
66 uses SysUtils,
67 CastleComponentSerialize, CastleUtils, CastleRectangles, CastleColors,
68 GameViewMainMenu, GameViewInstructions, GameViewInstructions2,
69 GameViewWin;
70
71 constructor TViewPlay.Create(AOwner: TComponent);
72 begin
73 inherited;
74 DesignUrl := 'castle-data:/gameviewplay.castle-user-interface';
75 end;
76
77 procedure TViewPlay.Start;
78
79 procedure PlaceInitialUnits;
80
81 procedure AddUnit(const Kind: TUnitKind; const XBegin, XEnd, YBegin, YEnd: Integer);
82 const
83 MaxTries = 50;
84 var
85 I: Integer;
86 Pos: TVector2Integer;
87 Un: TUnit;
88 begin
89 { Choose a random position, within given X and Y ranges.
90 Since we may play on various map sizes, with various rivers
91 --- prepare that the units may not fit, and resign after MaxTries
92 from adding a new unit. }
93 for I := 1 to MaxTries do
94 begin
95 Pos.X := RandomIntRangeInclusive(XBegin, XEnd);
96 Pos.Y := RandomIntRangeInclusive(YBegin, YEnd);
97 if (UnitsOnMap[Pos] = nil) and
98 (not UnitsOnMap.IsWater(Pos)) then
99 begin
100 Un := TUnit.Create(FreeAtStop);
101 Un.TilePosition := Pos;
102 Un.Initialize(UnitsOnMap, Kind);
103 Map.Add(Un.Transform);
104 Exit;
105 end;
106 end;
107 end;
108
109 var
110 I, W, H, YBegin, YEnd: Integer;
111 begin
112 W := Map.Data.Width;
113 H := Map.Data.Height;
114 YBegin := H div 3;
115 YEnd := H - 1 - H div 3;
116
117 for I := 0 to 2 do
118 AddUnit(ukAlienHeavy, W div 8 + 0, W div 8 + 0, YBegin, YEnd);
119 for I := 0 to 3 do
120 AddUnit(ukAlienLight, W div 8 + 2, W div 8 + 2, YBegin, YEnd);
121 for I := 0 to 2 do
122 AddUnit(ukHumanHeavy, W - 1 - W div 8 - 0, W - 1 - W div 8 - 0, YBegin, YEnd);
123 for I := 0 to 3 do
124 AddUnit(ukHumanLight, W - 1 - W div 8 - 2, W - 1 - W div 8 - 2, YBegin, YEnd);
125 end;
126
127 begin
128 inherited;
129
130 Map.URL := 'castle-data:/maps/' + MapName + '.tmx';
131 ButtonQuit.OnClick := {$ifdef FPC}@{$endif}ClickQuit;
132 ButtonInstructions.OnClick := {$ifdef FPC}@{$endif}ClickInstructions;
133 ButtonInstructions2.OnClick := {$ifdef FPC}@{$endif}ClickInstructions2;
134 ButtonEndTurn.OnClick := {$ifdef FPC}@{$endif}ClickEndTurn;
135
136 UnitsOnMap := TUnitsOnMap.Create(FreeAtStop, Map);
137
138 PlaceInitialUnits;
139
140 TileUnderMouseImage := TCastleImageTransform.Create(FreeAtStop);
141 case Map.Data.Orientation of
142 moOrthogonal: TileUnderMouseImage.URL := 'castle-data:/tile_hover/orthogonal.png';
143 moHexagonal : TileUnderMouseImage.URL := 'castle-data:/tile_hover/hexagonal.png';
144 else TileUnderMouseImage.URL := 'castle-data:/tile_hover/isometric.png';
145 end;
146 TileUnderMouseImage.Exists := false;
147 Map.Add(TileUnderMouseImage);
148
149 SelectedUnitVisualization := TransformLoad(
150 'castle-data:/unit_selected.castle-transform', FreeAtStop);
151 SelectedUnitVisualization.Exists := false;
152 Map.Add(SelectedUnitVisualization);
153
154 HumanTurn := true;
155 UpdateTurnStatus;
156 end;
157
158 procedure TViewPlay.Stop;
159 begin
160 { Make sure to clear fields, otherwise stopping + starting this view again
161 (when you exit the game and start a new game) could have non-nil but
162 invalid SelectedUnit reference. }
163 SelectedUnit := nil;
164 TileUnderMouseExists := false;
165 // set to nil, as it will be freed by FreeAtStop
166 SelectedUnitVisualization := nil;
167 inherited;
168 end;
169
170 procedure TViewPlay.ClickQuit(Sender: TObject);
171 begin
172 Container.View := ViewMainMenu;
173 end;
174
175 procedure TViewPlay.ClickInstructions(Sender: TObject);
176 begin
177 Container.PushView(ViewInstructions);
178 end;
179
180 procedure TViewPlay.ClickInstructions2(Sender: TObject);
181 begin
182 Container.PushView(ViewInstructions2);
183 end;
184
185 procedure TViewPlay.ClickEndTurn(Sender: TObject);
186
187 procedure ResetMovement;
188 var
189 I: Integer;
190 begin
191 for I := 0 to UnitsOnMap.UnitsCount - 1 do
192 UnitsOnMap.Units[I].Movement := UnitsOnMap.Units[I].InitialMovement;
193 end;
194
195 begin
196 HumanTurn := not HumanTurn;
197 SelectedUnit := nil;
198 SelectedUnitVisualization.Exists := false;
199 ResetMovement;
200 UpdateTurnStatus;
201 end;
202
203 function TViewPlay.Press(const Event: TInputPressRelease): Boolean;
204
205 procedure CheckWin;
206 var
207 FoundEnemy: Boolean;
208 I: Integer;
209 begin
210 FoundEnemy := false;
211 for I := 0 to UnitsOnMap.UnitsCount - 1 do
212 if UnitsOnMap.Units[I].Human <> HumanTurn then
213 begin
214 FoundEnemy := true;
215 Break;
216 end;
217
218 if not FoundEnemy then
219 begin
220 ViewWin.HumansWin := HumanTurn;
221 Container.PushView(ViewWin);
222 end;
223 end;
224
225 procedure ShowSelectedUnit;
226 begin
227 SelectedUnitVisualization.Exists := true;
228 SelectedUnitVisualization.Parent := SelectedUnit.Transform;
229 end;
230
231 var
232 UnitUnderMouse: TUnit;
233 begin
234 Result := inherited;
235 if Result then Exit;
236
237 if Event.IsMouseButton(buttonLeft) and TileUnderMouseExists then
238 begin
239 UnitUnderMouse := UnitsOnMap[TileUnderMouse];
240 if (UnitUnderMouse <> nil) and (UnitUnderMouse.Human = HumanTurn) then
241 begin
242 // select new unit
243 SelectedUnit := UnitUnderMouse;
244 ShowSelectedUnit;
245 UpdateTurnStatus; // SelectedUnit changed
246 Exit(true); // event handled
247 end else
248 if (SelectedUnit <> nil) and
249 // CanMove also checks that SelectedUnit.Movement > 0
250 (SelectedUnit.CanMove(TileUnderMouse)) then
251 begin
252 if UnitUnderMouse <> nil then
253 begin
254 // hurt enemy UnitUnderMouse.
255 UnitUnderMouse.Life := UnitUnderMouse.Life - SelectedUnit.Attack;
256 // Above operation *maybe* freed and removed enemy from the map,
257 // so UnitUnderMouse pointer afterwards is no longer valid.
258 UnitUnderMouse := nil;
259 SelectedUnit.Movement := 0;
260 UpdateTurnStatus; // SelectedUnit stats changed
261 CheckWin;
262 end else
263 begin
264 // move
265 SelectedUnit.TilePosition := TileUnderMouse;
266 SelectedUnit.Movement := SelectedUnit.Movement - 1;
267 UpdateTurnStatus; // SelectedUnit stats changed
268 end;
269 Exit(true); // event handled
270 end;
271
272 { When clicking on other map tile, do not mark event as handled
273 by Exit(true) here.
274 This allows TCastle2DNavigation to handle clicks to pan the map. }
275 end;
276 end;
277
278 procedure TViewPlay.UpdateTurnStatus;
279 var
280 SideName: String;
281 begin
282 if HumanTurn then
283 SideName := 'Human'
284 else
285 SideName := 'Alien';
286 LabelTurnStatus.Caption := SideName + ' Turn';
287 LabelTurnStatus.Text.Add(''); // newline
288
289 if SelectedUnit <> nil then
290 begin
291 LabelTurnStatus.Text.Add('Selected: ' + SelectedUnit.ToString);
292 LabelTurnStatus.Text.Add('Move or attack');
293 LabelTurnStatus.Text.Add(' or select another ' + SideName + ' unit');
294 LabelTurnStatus.Text.Add(' or press "End Turn".');
295 end else
296 begin
297 LabelTurnStatus.Text.Add('No unit selected.');
298 LabelTurnStatus.Text.Add('Select ' + SideName + ' unit');
299 LabelTurnStatus.Text.Add(' or press "End Turn".');
300 end;
301 end;
302
303 procedure TViewPlay.Update(const SecondsPassed: Single;
304 var HandleInput: boolean);
305 const
306 HoverAlpha = 0.75;
307 { When choosing colors, be sure to choose something clearly visible on our
308 tiles background. Light green, or yellow. or light blue -> not good,
309 as would mix with some map tiles. }
310 ColorNotAllowed: TCastleColor = (X: 1; Y: 0; Z: 0; W: HoverAlpha); // red
311 ColorAllowed: TCastleColor = (X: 0; Y: 1; Z: 0; W: HoverAlpha); // green
312 ColorMoveAllowed: TCastleColor = (X: 1; Y: 1; Z: 1; W: HoverAlpha); // white
313 var
314 TileStr: String;
315 TileRect: TFloatRectangle;
316 UnitUnderMouse: TUnit;
317 RayOrigin, RayDirection: TVector3;
318 //MapIndex: Integer;
319 begin
320 ViewportMap.PositionToRay(Container.MousePosition, true, RayOrigin, RayDirection);
321
322 { Update TileUnderMouseExists, TileUnderMouse.
323 See https://castle-engine.io/tiled_maps#tile_under_mouse for an explanation
324 how to query the map tile under mouse. }
325 TileUnderMouseExists := Map.Data.PositionToTile(RayOrigin.XY, TileUnderMouse);
326
327 { This is alternative way to query the map tile under mouse,
328 that will work even if map is possibly transformed,
329 directly or by parent TCastleTransform,
330 or if you may have different camera direction, maybe even 3D with perspective.
331
332 TileUnderMouseExists := false;
333 if ViewportMap.MouseRayHit <> nil then
334 begin
335 MapIndex := ViewportMap.MouseRayHit.IndexOfItem(Map);
336 if MapIndex <> -1 then
337 begin
338 TileUnderMouseExists := Map.Data.PositionToTile(
339 ViewportMap.MouseRayHit[MapIndex].Point.XY, TileUnderMouse);
340 end;
341 end;
342 }
343
344 { update TileUnderMouseImage, UnitUnderMouse }
345 TileUnderMouseImage.Exists := TileUnderMouseExists;
346 if TileUnderMouseExists then
347 begin
348 TileRect := Map.TileRectangle(TileUnderMouse);
349 TileUnderMouseImage.Translation := Vector3(TileRect.Center, ZHover);
350 TileUnderMouseImage.Size := Vector2(TileRect.Width, TileRect.Height);
351 UnitUnderMouse := UnitsOnMap[TileUnderMouse];
352 end else
353 UnitUnderMouse := nil;
354
355 { update TileUnderMouseImage.Color }
356 if (SelectedUnit <> nil) and
357 SelectedUnit.CanMove(TileUnderMouse) then
358 // can move by clicking here
359 TileUnderMouseImage.Color := ColorMoveAllowed
360 else
361 if (UnitUnderMouse <> nil) and
362 (UnitUnderMouse.Human = HumanTurn) then
363 // can select by clicking here
364 TileUnderMouseImage.Color := ColorAllowed
365 else
366 // cannot do anything by clicking here
367 TileUnderMouseImage.Color := ColorNotAllowed;
368
369 { update LabelStatus }
370 if TileUnderMouseExists then
371 begin
372 TileStr := TileUnderMouse.ToString;
373 if UnitsOnMap.IsWater(TileUnderMouse) then
374 TileStr := TileStr + NL + ' Water';
375 if UnitUnderMouse <> nil then
376 TileStr := TileStr + NL + ' Unit: ' + UnitUnderMouse.ToString;
377 end else
378 TileStr := 'none';
379 LabelStatus.Caption := Format('FPS: %s' + NL + 'Tile: %s', [
380 Container.Fps.ToString,
381 TileStr
382 ]);
383 end;
384
385 end.