DEADSOFTWARE

45e146140f4f17c7fb1ce3a54be460536741e792
[d2df-sdl.git] / src / game / g_player.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 {$M+}
17 unit g_player;
19 interface
21 uses
22 SysUtils, Classes,
23 {$IFDEF USE_MEMPOOL}mempool,{$ENDIF}
24 g_base, g_playermodel, g_basic, g_textures,
25 g_weapons, g_phys, g_sound, g_saveload, MAPDEF,
26 g_panel;
28 const
29 KEY_LEFT = 1;
30 KEY_RIGHT = 2;
31 KEY_UP = 3;
32 KEY_DOWN = 4;
33 KEY_FIRE = 5;
34 KEY_OPEN = 6;
35 KEY_JUMP = 7;
36 KEY_CHAT = 8;
38 WP_PREV = 0;
39 WP_NEXT = 1;
40 WP_FACT = WP_PREV;
41 WP_LACT = WP_NEXT;
43 R_ITEM_BACKPACK = 0;
44 R_KEY_RED = 1;
45 R_KEY_GREEN = 2;
46 R_KEY_BLUE = 3;
47 R_BERSERK = 4;
49 MR_SUIT = 0;
50 MR_INVUL = 1;
51 MR_INVIS = 2;
52 MR_MAX = 2;
54 A_BULLETS = 0;
55 A_SHELLS = 1;
56 A_ROCKETS = 2;
57 A_CELLS = 3;
58 A_FUEL = 4;
59 A_HIGH = 4;
61 AmmoLimits: Array [0..1] of Array [A_BULLETS..A_HIGH] of Word =
62 ((200, 50, 50, 300, 100),
63 (400, 100, 100, 600, 200));
65 K_SIMPLEKILL = 0;
66 K_HARDKILL = 1;
67 K_EXTRAHARDKILL = 2;
68 K_FALLKILL = 3;
70 T_RESPAWN = 0;
71 T_SWITCH = 1;
72 T_USE = 2;
73 T_FLAGCAP = 3;
75 TEAM_NONE = 0;
76 TEAM_RED = 1;
77 TEAM_BLUE = 2;
78 TEAM_COOP = 3;
80 SHELL_BULLET = 0;
81 SHELL_SHELL = 1;
82 SHELL_DBLSHELL = 2;
84 ANGLE_NONE = Low(SmallInt);
86 CORPSE_STATE_REMOVEME = 0;
87 CORPSE_STATE_NORMAL = 1;
88 CORPSE_STATE_MESS = 2;
90 PLAYER_RECT: TRectWH = (X:15; Y:12; Width:34; Height:52);
91 PLAYER_RECT_CX = 15+(34 div 2);
92 PLAYER_RECT_CY = 12+(52 div 2);
93 PLAYER_CORPSERECT: TRectWH = (X:15; Y:48; Width:34; Height:16);
95 PLAYER_HP_SOFT = 100;
96 PLAYER_HP_LIMIT = 200;
97 PLAYER_AP_SOFT = 100;
98 PLAYER_AP_LIMIT = 200;
99 SUICIDE_DAMAGE = 112;
100 WEAPON_DELAY = 5;
102 PLAYER_BURN_TIME = 110;
104 PLAYER1_DEF_COLOR: TRGB = (R:64; G:175; B:48);
105 PLAYER2_DEF_COLOR: TRGB = (R:96; G:96; B:96);
107 AIR_DEF = 360;
108 AIR_MAX = 1091;
109 JET_MAX = 540; // ~30 sec
110 ANGLE_RIGHTUP = 55;
111 ANGLE_RIGHTDOWN = -35;
112 ANGLE_LEFTUP = 125;
113 ANGLE_LEFTDOWN = -145;
114 WEAPONPOINT: Array [TDirection] of TDFPoint = ((X:16; Y:32), (X:47; Y:32));
115 TEAMCOLOR: Array [TEAM_RED..TEAM_BLUE] of TRGB = ((R:255; G:0; B:0),
116 (R:0; G:0; B:255));
118 type
119 TPlayerStat = record
120 Num: Integer;
121 Ping: Word;
122 Loss: Byte;
123 Name: String;
124 Team: Byte;
125 Frags: SmallInt;
126 Deaths: SmallInt;
127 Lives: Byte;
128 Kills: Word;
129 Color: TRGB;
130 Spectator: Boolean;
131 UID: Word;
132 end;
134 TPlayerStatArray = Array of TPlayerStat;
136 TPlayerSavedState = record
137 Health: Integer;
138 Armor: Integer;
139 Air: Integer;
140 JetFuel: Integer;
141 CurrWeap: Byte;
142 NextWeap: WORD;
143 NextWeapDelay: Byte;
144 Ammo: Array [A_BULLETS..A_HIGH] of Word;
145 MaxAmmo: Array [A_BULLETS..A_HIGH] of Word;
146 Weapon: Array [WP_FIRST..WP_LAST] of Boolean;
147 Rulez: Set of R_ITEM_BACKPACK..R_BERSERK;
148 Used: Boolean;
149 end;
151 TKeyState = record
152 Pressed: Boolean;
153 Time: Word;
154 end;
156 TPlayer = class{$IFDEF USE_MEMPOOL}(TPoolObject){$ENDIF}
157 private
158 FIamBot: Boolean;
159 FUID: Word;
160 FName: String;
161 FTeam: Byte;
162 FAlive: Boolean;
163 FSpawned: Boolean;
164 FDirection: TDirection;
165 FHealth: Integer;
166 FLives: Byte;
167 FArmor: Integer;
168 FAir: Integer;
169 FPain: Integer;
170 FPickup: Integer;
171 FKills: Integer;
172 FMonsterKills: Integer;
173 FFrags: Integer;
174 FFragCombo: Byte;
175 FLastFrag: LongWord;
176 FComboEvnt: Integer;
177 FDeath: Integer;
178 FCanJetpack: Boolean;
179 FJetFuel: Integer;
180 FFlag: Byte;
181 FSecrets: Integer;
182 FCurrWeap: Byte;
183 FNextWeap: WORD;
184 FNextWeapDelay: Byte; // frames
185 FBFGFireCounter: SmallInt;
186 FLastSpawnerUID: Word;
187 FLastHit: Byte;
188 FObj: TObj;
189 FXTo, FYTo: Integer;
190 FSpectatePlayer: Integer;
191 FFirePainTime: Integer;
192 FFireAttacker: Word;
194 FSavedStateNum: Integer;
196 FModel: TPlayerModel;
197 FPunchAnim: TAnimationState;
198 FActionPrior: Byte;
199 FActionAnim: Byte;
200 FActionForce: Boolean;
201 FActionChanged: Boolean;
202 FAngle: SmallInt;
203 FFireAngle: SmallInt;
204 FIncCamOld: Integer;
205 FIncCam: Integer;
206 FSlopeOld: Integer;
207 FShellTimer: Integer;
208 FShellType: Byte;
209 FSawSound: TPlayableSound;
210 FSawSoundIdle: TPlayableSound;
211 FSawSoundHit: TPlayableSound;
212 FSawSoundSelect: TPlayableSound;
213 FFlameSoundOn: TPlayableSound;
214 FFlameSoundOff: TPlayableSound;
215 FFlameSoundWork: TPlayableSound;
216 FJetSoundOn: TPlayableSound;
217 FJetSoundOff: TPlayableSound;
218 FJetSoundFly: TPlayableSound;
219 FGodMode: Boolean;
220 FNoTarget: Boolean;
221 FNoReload: Boolean;
222 FJustTeleported: Boolean;
223 FNetTime: LongWord;
224 mEDamageType: Integer;
227 function CollideLevel(XInc, YInc: Integer): Boolean;
228 function StayOnStep(XInc, YInc: Integer): Boolean;
229 function HeadInLiquid(XInc, YInc: Integer): Boolean;
230 function BodyInLiquid(XInc, YInc: Integer): Boolean;
231 function BodyInAcid(XInc, YInc: Integer): Boolean;
232 function FullInLift(XInc, YInc: Integer): Integer;
233 {procedure CollideItem();}
234 procedure FlySmoke(Times: DWORD = 1);
235 procedure OnFireFlame(Times: DWORD = 1);
236 procedure SetAction(Action: Byte; Force: Boolean = False);
237 procedure OnDamage(Angle: SmallInt); virtual;
238 function firediry(): Integer;
239 procedure DoPunch();
241 procedure Run(Direction: TDirection);
242 procedure NextWeapon();
243 procedure PrevWeapon();
244 procedure SeeUp();
245 procedure SeeDown();
246 procedure Fire();
247 procedure Jump();
248 procedure Use();
250 function getNextWeaponIndex (): Byte; // return 255 for "no switch"
251 procedure resetWeaponQueue ();
252 function hasAmmoForWeapon (weapon: Byte): Boolean;
253 function hasAmmoForShooting (weapon: Byte): Boolean;
254 function shouldSwitch (weapon: Byte; hadWeapon: Boolean) : Boolean;
256 procedure doDamage (v: Integer);
258 function refreshCorpse(): Boolean;
260 public
261 FDamageBuffer: Integer;
263 FAmmo: Array [A_BULLETS..A_HIGH] of Word;
264 FMaxAmmo: Array [A_BULLETS..A_HIGH] of Word;
265 FWeapon: Array [WP_FIRST..WP_LAST] of Boolean;
266 FRulez: Set of R_ITEM_BACKPACK..R_BERSERK;
267 FBerserk: Integer;
268 FMegaRulez: Array [MR_SUIT..MR_MAX] of DWORD;
269 FReloading: Array [WP_FIRST..WP_LAST] of Word;
270 FTime: Array [T_RESPAWN..T_FLAGCAP] of DWORD;
271 FKeys: Array [KEY_LEFT..KEY_CHAT] of TKeyState;
272 FWeapSwitchMode: Byte;
273 FWeapPreferences: Array [WP_FIRST .. WP_LAST+1] of Byte;
274 FSwitchToEmpty: Byte;
275 FSkipFist: Byte;
276 FColor: TRGB;
277 FPreferredTeam: Byte;
278 FSpectator: Boolean;
279 FNoRespawn: Boolean;
280 FWantsInGame: Boolean;
281 FGhost: Boolean;
282 FPhysics: Boolean;
283 FFlaming: Boolean;
284 FJetpack: Boolean;
285 FActualModelName: string;
286 FClientID: SmallInt;
287 FPing: Word;
288 FLoss: Byte;
289 FReady: Boolean;
290 FDummy: Boolean;
291 FFireTime: Integer;
292 FSpawnInvul: Integer;
293 FHandicap: Integer;
294 FWaitForFirstSpawn: Boolean; // set to `true` in server, used to spawn a player on first full state request
295 FCorpse: Integer;
297 // debug: viewport offset
298 viewPortX, viewPortY, viewPortW, viewPortH: Integer;
300 function isValidViewPort (): Boolean; inline;
302 constructor Create(); virtual;
303 destructor Destroy(); override;
304 procedure Respawn(Silent: Boolean; Force: Boolean = False); virtual;
305 function GetRespawnPoint(): Byte;
306 procedure PressKey(Key: Byte; Time: Word = 1);
307 procedure ReleaseKeys();
308 procedure SetModel(ModelName: String);
309 procedure SetColor(Color: TRGB);
310 function GetColor(): TRGB;
311 procedure SetWeapon(W: Byte);
312 function IsKeyPressed(K: Byte): Boolean;
313 function GetKeys(): Byte;
314 function PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean; virtual;
315 procedure SetWeaponPrefs(Prefs: Array of Byte);
316 procedure SetWeaponPref(Weapon, Pref: Byte);
317 function GetWeaponPref(Weapon: Byte) : Byte;
318 function GetMorePrefered() : Byte;
319 function MaySwitch(Weapon: Byte) : Boolean;
320 function Collide(X, Y: Integer; Width, Height: Word): Boolean; overload;
321 function Collide(Panel: TPanel): Boolean; overload;
322 function Collide(X, Y: Integer): Boolean; overload;
323 procedure SetDirection(Direction: TDirection);
324 procedure GetSecret();
325 function TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
326 procedure Touch();
327 procedure Push(vx, vy: Integer);
328 procedure ChangeModel(ModelName: String);
329 procedure SwitchTeam;
330 procedure ChangeTeam(Team: Byte);
331 procedure BFGHit();
332 function GetFlag(Flag: Byte): Boolean;
333 procedure SetFlag(Flag: Byte);
334 function DropFlag(Silent: Boolean = True; DoThrow: Boolean = False): Boolean;
335 function TryDropFlag(): Boolean;
336 procedure AllRulez(Health: Boolean);
337 procedure RestoreHealthArmor();
338 procedure FragCombo();
339 procedure GiveItem(ItemType: Byte);
340 procedure Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte); virtual;
341 function Heal(value: Word; Soft: Boolean): Boolean; virtual;
342 procedure MakeBloodVector(Count: Word; VelX, VelY: Integer);
343 procedure MakeBloodSimple(Count: Word);
344 procedure Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
345 procedure Reset(Force: Boolean);
346 procedure Spectate(NoMove: Boolean = False);
347 procedure SwitchNoClip;
348 procedure SoftReset();
349 procedure PreUpdate();
350 procedure Update(); virtual;
351 procedure RememberState();
352 procedure RecallState();
353 procedure SaveState (st: TStream); virtual;
354 procedure LoadState (st: TStream); virtual;
355 procedure PauseSounds(Enable: Boolean);
356 procedure NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
357 procedure DoLerp(Level: Integer = 2);
358 procedure SetLerp(XTo, YTo: Integer);
359 procedure ProcessWeaponAction(Action: Byte);
360 procedure QueueWeaponSwitch(Weapon: Byte);
361 procedure RealizeCurrentWeapon();
362 procedure FlamerOn;
363 procedure FlamerOff;
364 procedure JetpackOn;
365 procedure JetpackOff;
366 procedure CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
368 //WARNING! this does nothing for now, but still call it!
369 procedure positionChanged (); //WARNING! call this after entity position was changed, or coldet will not work right!
371 procedure getMapBox (out x, y, w, h: Integer); inline;
372 procedure moveBy (dx, dy: Integer); inline;
374 function getCameraObj(): TObj;
376 function GetAmmoByWeapon(Weapon: Byte): Word; // private state
378 public
379 property Vel: TPoint2i read FObj.Vel;
380 property Obj: TObj read FObj;
382 property Name: String read FName write FName;
383 property Model: TPlayerModel read FModel;
384 property Health: Integer read FHealth write FHealth;
385 property Lives: Byte read FLives write FLives;
386 property Armor: Integer read FArmor write FArmor;
387 property Air: Integer read FAir write FAir;
388 property JetFuel: Integer read FJetFuel write FJetFuel;
389 property Frags: Integer read FFrags write FFrags;
390 property Death: Integer read FDeath write FDeath;
391 property Kills: Integer read FKills write FKills;
392 property CurrWeap: Byte read FCurrWeap write FCurrWeap;
393 property WeapSwitchMode: Byte read FWeapSwitchMode write FWeapSwitchMode;
394 property SwitchToEmpty: Byte read FSwitchToEmpty write FSwitchToEmpty;
395 property SkipFist: Byte read FSkipFist write FSkipFist;
396 property MonsterKills: Integer read FMonsterKills write FMonsterKills;
397 property Secrets: Integer read FSecrets;
398 property GodMode: Boolean read FGodMode write FGodMode;
399 property NoTarget: Boolean read FNoTarget write FNoTarget;
400 property NoReload: Boolean read FNoReload write FNoReload;
401 property alive: Boolean read FAlive write FAlive;
402 property Flag: Byte read FFlag;
403 property Team: Byte read FTeam write FTeam;
404 property Direction: TDirection read FDirection;
405 property GameX: Integer read FObj.X write FObj.X;
406 property GameY: Integer read FObj.Y write FObj.Y;
407 property GameVelX: Integer read FObj.Vel.X write FObj.Vel.X;
408 property GameVelY: Integer read FObj.Vel.Y write FObj.Vel.Y;
409 property GameAccelX: Integer read FObj.Accel.X write FObj.Accel.X;
410 property GameAccelY: Integer read FObj.Accel.Y write FObj.Accel.Y;
411 property IncCam: Integer read FIncCam write FIncCam;
412 property IncCamOld: Integer read FIncCamOld write FIncCamOld;
413 property SlopeOld: Integer read FSlopeOld write FSlopeOld;
414 property UID: Word read FUID write FUID;
415 property JustTeleported: Boolean read FJustTeleported write FJustTeleported;
416 property NetTime: LongWord read FNetTime write FNetTime;
418 (* internal state *)
419 property Angle_: SmallInt read FAngle;
420 property Spectator: Boolean read FSpectator;
421 property NoRespawn: Boolean read FNoRespawn;
422 property Berserk: Integer read FBerserk;
423 property Pain: Integer read FPain;
424 property Pickup: Integer read FPickup;
425 property PunchAnim: TAnimationState read FPunchAnim write FPunchAnim;
426 property SpawnInvul: Integer read FSpawnInvul;
427 property Ghost: Boolean read FGhost;
429 published
430 property eName: String read FName write FName;
431 property eHealth: Integer read FHealth write FHealth;
432 property eLives: Byte read FLives write FLives;
433 property eArmor: Integer read FArmor write FArmor;
434 property eAir: Integer read FAir write FAir;
435 property eJetFuel: Integer read FJetFuel write FJetFuel;
436 property eFrags: Integer read FFrags write FFrags;
437 property eDeath: Integer read FDeath write FDeath;
438 property eKills: Integer read FKills write FKills;
439 property eCurrWeap: Byte read FCurrWeap write FCurrWeap;
440 property eMonsterKills: Integer read FMonsterKills write FMonsterKills;
441 property eSecrets: Integer read FSecrets write FSecrets;
442 property eGodMode: Boolean read FGodMode write FGodMode;
443 property eNoTarget: Boolean read FNoTarget write FNoTarget;
444 property eNoReload: Boolean read FNoReload write FNoReload;
445 property eAlive: Boolean read FAlive write FAlive;
446 property eFlag: Byte read FFlag;
447 property eTeam: Byte read FTeam write FTeam;
448 property eDirection: TDirection read FDirection;
449 property eGameX: Integer read FObj.X write FObj.X;
450 property eGameY: Integer read FObj.Y write FObj.Y;
451 property eGameVelX: Integer read FObj.Vel.X write FObj.Vel.X;
452 property eGameVelY: Integer read FObj.Vel.Y write FObj.Vel.Y;
453 property eGameAccelX: Integer read FObj.Accel.X write FObj.Accel.X;
454 property eGameAccelY: Integer read FObj.Accel.Y write FObj.Accel.Y;
455 property eIncCam: Integer read FIncCam write FIncCam;
456 property eUID: Word read FUID;
457 property eJustTeleported: Boolean read FJustTeleported;
458 property eNetTime: LongWord read FNetTime;
460 // set this before assigning something to `eDamage`
461 property eDamageType: Integer read mEDamageType write mEDamageType;
462 property eDamage: Integer write doDamage;
463 end;
465 TDifficult = record
466 public
467 DiagFire: Byte;
468 InvisFire: Byte;
469 DiagPrecision: Byte;
470 FlyPrecision: Byte;
471 Cover: Byte;
472 CloseJump: Byte;
473 WeaponPrior: packed array [WP_FIRST..WP_LAST] of Byte;
474 CloseWeaponPrior: packed array [WP_FIRST..WP_LAST] of Byte;
475 //SafeWeaponPrior: Array [WP_FIRST..WP_LAST] of Byte;
477 public
478 procedure save (st: TStream);
479 procedure load (st: TStream);
480 end;
482 TAIFlag = record
483 Name: String;
484 Value: String;
485 end;
487 TBot = class(TPlayer)
488 private
489 FSelectedWeapon: Byte;
490 FTargetUID: Word;
491 FLastVisible: DWORD;
492 FAIFlags: Array of TAIFlag;
493 FDifficult: TDifficult;
495 function GetRnd(a: Byte): Boolean;
496 function GetInterval(a: Byte; radius: SmallInt): SmallInt;
497 function RunDirection(): TDirection;
498 function FullInStep(XInc, YInc: Integer): Boolean;
499 //function NeedItem(Item: Byte): Byte;
500 procedure SelectWeapon(Dist: Integer);
501 procedure SetAIFlag(aName, fValue: String20);
502 function GetAIFlag(aName: String20): String20;
503 procedure RemoveAIFlag(aName: String20);
504 function Healthy(): Byte;
505 procedure UpdateMove();
506 procedure UpdateCombat();
507 function KeyPressed(Key: Word): Boolean;
508 procedure ReleaseKey(Key: Byte);
509 function TargetOnScreen(TX, TY: Integer): Boolean;
510 procedure OnDamage(Angle: SmallInt); override;
512 public
513 procedure Respawn(Silent: Boolean; Force: Boolean = False); override;
514 constructor Create(); override;
515 destructor Destroy(); override;
516 function PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean; override;
517 function Heal(value: Word; Soft: Boolean): Boolean; override;
518 procedure Update(); override;
519 procedure SaveState (st: TStream); override;
520 procedure LoadState (st: TStream); override;
521 end;
523 PGib = ^TGib;
524 TGib = record
525 alive: Boolean;
526 RAngle: Integer;
527 Color: TRGB;
528 Obj: TObj;
530 ModelID: Integer;
531 GibID: Integer;
533 procedure getMapBox (out x, y, w, h: Integer); inline;
534 procedure moveBy (dx, dy: Integer); inline;
536 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
537 end;
540 PShell = ^TShell;
541 TShell = record
542 alive: Boolean;
543 SType: Byte;
544 RAngle: Integer;
545 Timeout: Cardinal;
546 Obj: TObj;
548 procedure getMapBox (out x, y, w, h: Integer); inline;
549 procedure moveBy (dx, dy: Integer); inline;
551 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
552 end;
554 TCorpse = class{$IFDEF USE_MEMPOOL}(TPoolObject){$ENDIF}
555 private
556 FMess: Boolean;
557 FState: Byte;
558 FDamage: Byte;
559 FObj: TObj;
560 FPlayerUID: Word;
561 FModel: TPlayerModel;
563 public
564 constructor Create(X, Y: Integer; ModelName: String; aMess: Boolean);
565 destructor Destroy(); override;
566 procedure Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
567 procedure Update();
568 procedure SaveState (st: TStream);
569 procedure LoadState (st: TStream);
571 procedure getMapBox (out x, y, w, h: Integer); inline;
572 procedure moveBy (dx, dy: Integer); inline;
574 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
576 function ObjPtr (): PObj; inline;
578 property Obj: TObj read FObj; // copies object
579 property State: Byte read FState;
580 property Mess: Boolean read FMess;
581 property Model: TPlayerModel read FModel;
582 end;
584 TTeamStat = Array [TEAM_RED..TEAM_BLUE] of
585 record
586 Score: SmallInt;
587 end;
589 var
590 gPlayers: Array of TPlayer;
591 gCorpses: Array of TCorpse;
592 gGibs: Array of TGib;
593 gShells: Array of TShell;
594 gTeamStat: TTeamStat;
595 gFly: Boolean = False;
596 gAimLine: Boolean = False;
597 gChatBubble: Integer = 0;
598 gPlayerIndicator: Integer = 1;
599 gPlayerIndicatorStyle: Integer = 0;
600 gNumBots: Word = 0;
601 gSpectLatchPID1: Word = 0;
602 gSpectLatchPID2: Word = 0;
603 MAX_RUNVEL: Integer = 8;
604 VEL_JUMP: Integer = 10;
605 SHELL_TIMEOUT: Cardinal = 60000;
607 function Lerp(X, Y, Factor: Integer): Integer;
609 procedure g_Gibs_SetMax(Count: Word);
610 function g_Gibs_GetMax(): Word;
611 procedure g_Corpses_SetMax(Count: Word);
612 function g_Corpses_GetMax(): Word;
613 procedure g_Force_Model_Set(Mode: Word);
614 function g_Force_Model_Get(): Word;
615 procedure g_Forced_Model_SetName(Model: String);
616 function g_Forced_Model_GetName(): String;
617 procedure g_Shells_SetMax(Count: Word);
618 function g_Shells_GetMax(): Word;
620 procedure g_Player_Init();
621 procedure g_Player_Free();
622 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
623 function g_Player_CreateFromState (st: TStream): Word;
624 procedure g_Player_Remove(UID: Word);
625 procedure g_Player_ResetTeams();
626 procedure g_Player_PreUpdate();
627 procedure g_Player_UpdateAll();
628 procedure g_Player_RememberAll();
629 procedure g_Player_ResetAll(Force, Silent: Boolean);
630 function g_Player_Get(UID: Word): TPlayer;
631 function g_Player_GetCount(): Byte;
632 function g_Player_GetStats(): TPlayerStatArray;
633 function g_Player_ValidName(Name: String): Boolean;
634 function g_Player_CreateCorpse(Player: TPlayer): Integer;
635 procedure g_Player_CreateGibs (fX, fY, mid: Integer; fColor: TRGB);
636 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
637 procedure g_Player_UpdatePhysicalObjects();
638 procedure g_Player_RemoveAllCorpses();
639 procedure g_Player_Corpses_SaveState (st: TStream);
640 procedure g_Player_Corpses_LoadState (st: TStream);
641 procedure g_Player_ResetReady();
642 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
643 procedure g_Bot_AddList(Team: Byte; lname: ShortString; num: Integer = -1; Handicap: Integer = 100);
644 procedure g_Bot_MixNames();
645 procedure g_Bot_RemoveAll();
646 function g_Bot_GetCount(): Integer;
648 implementation
650 uses
651 {$IFDEF ENABLE_HOLMES}
652 g_holmes,
653 {$ENDIF}
654 {$IFDEF ENABLE_MENU}
655 g_menu,
656 {$ENDIF}
657 {$IFNDEF HEADLESS}
658 r_render,
659 {$ENDIF}
660 {$IFDEF ENABLE_GFX}
661 g_gfx,
662 {$ENDIF}
663 e_log, g_map, g_items, g_console, Math,
664 g_options, g_triggers, g_game, g_grid, e_res,
665 wadreader, g_monsters, CONFIG, g_language,
666 g_net, g_netmsg,
667 utils, xstreams;
669 const PLR_SAVE_VERSION = 0;
671 type
672 TBotProfile = record
673 name: ShortString;
674 model: ShortString;
675 team: Byte;
676 color: TRGB;
677 diag_fire: Byte;
678 invis_fire: Byte;
679 diag_precision: Byte;
680 fly_precision: Byte;
681 cover: Byte;
682 close_jump: Byte;
683 w_prior1: Array [WP_FIRST..WP_LAST] of Byte;
684 w_prior2: Array [WP_FIRST..WP_LAST] of Byte;
685 w_prior3: Array [WP_FIRST..WP_LAST] of Byte;
686 end;
688 const
689 TIME_RESPAWN1 = 1500;
690 TIME_RESPAWN2 = 2000;
691 TIME_RESPAWN3 = 3000;
692 PLAYER_SUIT_TIME = 30000;
693 PLAYER_INVUL_TIME = 30000;
694 PLAYER_INVIS_TIME = 35000;
695 FRAG_COMBO_TIME = 3000;
696 VEL_SW = 4;
697 VEL_FLY = 6;
698 PLAYER_HEADRECT: TRectWH = (X:24; Y:12; Width:20; Height:12);
699 BOT_MAXJUMP = 84;
700 BOT_LONGDIST = 300;
701 BOT_UNSAFEDIST = 128;
702 DIFFICULT_EASY: TDifficult = (DiagFire: 32; InvisFire: 32; DiagPrecision: 32;
703 FlyPrecision: 32; Cover: 32; CloseJump: 32;
704 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
705 DIFFICULT_MEDIUM: TDifficult = (DiagFire: 127; InvisFire: 127; DiagPrecision: 127;
706 FlyPrecision: 127; Cover: 127; CloseJump: 127;
707 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
708 DIFFICULT_HARD: TDifficult = (DiagFire: 255; InvisFire: 255; DiagPrecision: 255;
709 FlyPrecision: 255; Cover: 255; CloseJump: 255;
710 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
711 WEAPON_PRIOR1: Array [WP_FIRST..WP_LAST] of Byte =
712 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
713 WEAPON_SHOTGUN2, WEAPON_SHOTGUN1,
714 WEAPON_CHAINGUN, WEAPON_PLASMA, WEAPON_ROCKETLAUNCHER,
715 WEAPON_BFG, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
716 WEAPON_PRIOR2: Array [WP_FIRST..WP_LAST] of Byte =
717 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
718 WEAPON_BFG, WEAPON_ROCKETLAUNCHER,
719 WEAPON_SHOTGUN2, WEAPON_PLASMA, WEAPON_SHOTGUN1,
720 WEAPON_CHAINGUN, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
721 //WEAPON_PRIOR3: Array [WP_FIRST..WP_LAST] of Byte =
722 // (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
723 // WEAPON_BFG, WEAPON_PLASMA, WEAPON_SHOTGUN2,
724 // WEAPON_CHAINGUN, WEAPON_SHOTGUN1, WEAPON_SAW,
725 // WEAPON_ROCKETLAUNCHER, WEAPON_PISTOL, WEAPON_KASTET);
726 WEAPON_RELOAD: Array [WP_FIRST..WP_LAST] of Byte =
727 (5, 2, 6, 18, 36, 2, 12, 2, 14, 2, 2);
729 PLAYER_SIGNATURE = $52594C50; // 'PLYR'
730 CORPSE_SIGNATURE = $50524F43; // 'CORP'
732 BOTNAMES_FILENAME = 'botnames.txt';
733 BOTLIST_FILENAME = 'botlist.txt';
735 var
736 MaxGibs: Word = 150;
737 MaxCorpses: Word = 20;
738 MaxShells: Word = 300;
739 ForceModel: Word = 0;
740 ForcedModelName: String = STD_PLAYER_MODEL;
741 CurrentGib: Integer = 0;
742 CurrentShell: Integer = 0;
743 BotNames: Array of String;
744 BotList: Array of TBotProfile;
745 SavedStates: Array of TPlayerSavedState;
748 function Lerp(X, Y, Factor: Integer): Integer;
749 begin
750 Result := X + ((Y - X) div Factor);
751 end;
753 function SameTeam(UID1, UID2: Word): Boolean;
754 begin
755 Result := False;
757 if (UID1 > UID_MAX_PLAYER) or (UID1 <= UID_MAX_GAME) or
758 (UID2 > UID_MAX_PLAYER) or (UID2 <= UID_MAX_GAME) then Exit;
760 if (g_Player_Get(UID1) = nil) or (g_Player_Get(UID2) = nil) then Exit;
762 if ((g_Player_Get(UID1).Team = TEAM_NONE) or
763 (g_Player_Get(UID2).Team = TEAM_NONE)) then Exit;
765 Result := g_Player_Get(UID1).FTeam = g_Player_Get(UID2).FTeam;
766 end;
768 procedure g_Gibs_SetMax(Count: Word);
769 begin
770 MaxGibs := Count;
771 SetLength(gGibs, Count);
773 if CurrentGib >= Count then
774 CurrentGib := 0;
775 end;
777 function g_Gibs_GetMax(): Word;
778 begin
779 Result := MaxGibs;
780 end;
782 procedure g_Shells_SetMax(Count: Word);
783 begin
784 MaxShells := Count;
785 SetLength(gShells, Count);
787 if CurrentShell >= Count then
788 CurrentShell := 0;
789 end;
791 function g_Shells_GetMax(): Word;
792 begin
793 Result := MaxShells;
794 end;
797 procedure g_Corpses_SetMax(Count: Word);
798 begin
799 MaxCorpses := Count;
800 SetLength(gCorpses, Count);
801 end;
803 function g_Corpses_GetMax(): Word;
804 begin
805 Result := MaxCorpses;
806 end;
808 procedure g_Force_Model_Set(Mode: Word);
809 begin
810 ForceModel := Mode;
811 end;
813 function g_Force_Model_Get(): Word;
814 begin
815 Result := ForceModel;
816 end;
818 procedure g_Forced_Model_SetName(Model: String);
819 begin
820 ForcedModelName := Model;
821 end;
823 function g_Forced_Model_GetName(): String;
824 begin
825 Result := ForcedModelName;
826 end;
828 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
829 var
830 a: Integer;
831 ok: Boolean;
832 begin
833 Result := 0;
835 ok := False;
836 a := 0;
838 // Есть ли место в gPlayers:
839 if gPlayers <> nil then
840 for a := 0 to High(gPlayers) do
841 if gPlayers[a] = nil then
842 begin
843 ok := True;
844 Break;
845 end;
847 // Нет места - расширяем gPlayers:
848 if not ok then
849 begin
850 SetLength(gPlayers, Length(gPlayers)+1);
851 a := High(gPlayers);
852 end;
854 // Создаем объект игрока:
855 if Bot then
856 gPlayers[a] := TBot.Create()
857 else
858 gPlayers[a] := TPlayer.Create();
861 gPlayers[a].FActualModelName := ModelName;
862 gPlayers[a].SetModel(ModelName);
863 if Bot and (g_Force_Model_Get() <> 0) then
864 gPlayers[a].SetModel(g_Forced_Model_GetName());
866 // Нет модели - создание не возможно:
867 if gPlayers[a].FModel = nil then
868 begin
869 gPlayers[a].Free();
870 gPlayers[a] := nil;
871 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], [ModelName]));
872 Exit;
873 end;
875 if not (Team in [TEAM_RED, TEAM_BLUE]) then
876 if Random(2) = 0 then
877 Team := TEAM_RED
878 else
879 Team := TEAM_BLUE;
880 gPlayers[a].FPreferredTeam := Team;
882 case gGameSettings.GameMode of
883 GM_DM: gPlayers[a].FTeam := TEAM_NONE;
884 GM_TDM,
885 GM_CTF: gPlayers[a].FTeam := gPlayers[a].FPreferredTeam;
886 GM_SINGLE,
887 GM_COOP: gPlayers[a].FTeam := TEAM_COOP;
888 end;
890 // Если командная игра - красим модель в цвет команды:
891 gPlayers[a].FColor := Color;
892 if gPlayers[a].FTeam in [TEAM_RED, TEAM_BLUE] then
893 gPlayers[a].FModel.Color := TEAMCOLOR[gPlayers[a].FTeam]
894 else
895 gPlayers[a].FModel.Color := Color;
897 gPlayers[a].FUID := g_CreateUID(UID_PLAYER);
898 gPlayers[a].FAlive := False;
900 Result := gPlayers[a].FUID;
901 end;
903 function g_Player_CreateFromState (st: TStream): Word;
904 var a: Integer; ok, Bot: Boolean; pos: Int64;
905 begin
906 assert(st <> nil);
908 // check signature and entity type
909 pos := st.Position;
910 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
911 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
912 Bot := utils.readBool(st);
913 st.Position := pos;
915 // find free player slot
916 ok := false;
917 for a := 0 to High(gPlayers) do
918 if gPlayers[a] = nil then
919 begin
920 ok := true;
921 break;
922 end;
924 // allocate player slot
925 if not ok then
926 begin
927 SetLength(gPlayers, Length(gPlayers)+1);
928 a := High(gPlayers);
929 end;
931 // create entity and load state
932 if Bot then
933 begin
934 gPlayers[a] := TBot.Create();
935 if (g_Force_Model_Get() <> 0) then
936 gPlayers[a].SetModel(g_Forced_Model_GetName());
937 end
938 else
939 gPlayers[a] := TPlayer.Create();
940 gPlayers[a].FPhysics := True; // ???
941 gPlayers[a].LoadState(st);
943 result := gPlayers[a].FUID;
944 end;
947 procedure g_Player_ResetTeams();
948 var
949 a: Integer;
950 begin
951 if g_Game_IsClient then
952 Exit;
953 if gPlayers = nil then
954 Exit;
955 for a := Low(gPlayers) to High(gPlayers) do
956 if gPlayers[a] <> nil then
957 case gGameSettings.GameMode of
958 GM_DM:
959 gPlayers[a].ChangeTeam(TEAM_NONE);
960 GM_TDM, GM_CTF:
961 if not (gPlayers[a].Team in [TEAM_RED, TEAM_BLUE]) then
962 if gPlayers[a].FPreferredTeam in [TEAM_RED, TEAM_BLUE] then
963 gPlayers[a].ChangeTeam(gPlayers[a].FPreferredTeam)
964 else
965 if a mod 2 = 0 then
966 gPlayers[a].ChangeTeam(TEAM_RED)
967 else
968 gPlayers[a].ChangeTeam(TEAM_BLUE);
969 GM_SINGLE,
970 GM_COOP:
971 gPlayers[a].ChangeTeam(TEAM_COOP);
972 end;
973 end;
975 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
976 var
977 m: SSArray;
978 _name, _model: String;
979 a, tr, tb: Integer;
980 begin
981 if not g_Game_IsServer then Exit;
983 if (g_Bot_GetCount() >= gMaxBots) then Exit;
985 // Список названий моделей:
986 m := g_PlayerModel_GetNames();
987 if m = nil then
988 Exit;
990 // Команда:
991 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
992 Team := TEAM_COOP // COOP
993 else
994 if gGameSettings.GameMode = GM_DM then
995 Team := TEAM_NONE // DM
996 else
997 if Team = TEAM_NONE then // CTF / TDM
998 begin
999 // Автобаланс команд:
1000 tr := 0;
1001 tb := 0;
1003 for a := 0 to High(gPlayers) do
1004 if gPlayers[a] <> nil then
1005 begin
1006 if gPlayers[a].Team = TEAM_RED then
1007 Inc(tr)
1008 else
1009 if gPlayers[a].Team = TEAM_BLUE then
1010 Inc(tb);
1011 end;
1013 if tr > tb then
1014 Team := TEAM_BLUE
1015 else
1016 if tb > tr then
1017 Team := TEAM_RED
1018 else // tr = tb
1019 if Random(2) = 0 then
1020 Team := TEAM_RED
1021 else
1022 Team := TEAM_BLUE;
1023 end;
1025 // Выбираем боту имя:
1026 _name := '';
1027 if BotNames <> nil then
1028 for a := 0 to High(BotNames) do
1029 if g_Player_ValidName(BotNames[a]) then
1030 begin
1031 _name := BotNames[a];
1032 Break;
1033 end;
1035 // Выбираем случайную модель:
1036 _model := m[Random(Length(m))];
1038 // Создаем бота:
1039 with g_Player_Get(g_Player_Create(_model,
1040 _RGB(Min(Random(9)*32, 255),
1041 Min(Random(9)*32, 255),
1042 Min(Random(9)*32, 255)),
1043 Team, True)) as TBot do
1044 begin
1045 // Если имени нет, делаем его из UID бота
1046 if _name = '' then
1047 Name := Format('DFBOT%.5d', [UID])
1048 else
1049 Name := _name;
1051 case Difficult of
1052 1: FDifficult := DIFFICULT_EASY;
1053 2: FDifficult := DIFFICULT_MEDIUM;
1054 else FDifficult := DIFFICULT_HARD;
1055 end;
1057 for a := WP_FIRST to WP_LAST do
1058 begin
1059 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
1060 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
1061 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
1062 end;
1064 FHandicap := Handicap;
1066 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1068 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1069 if g_Game_IsServer and (gGameSettings.MaxLives > 0) then
1070 Spectate();
1071 end;
1072 end;
1074 procedure g_Bot_AddList(Team: Byte; lName: ShortString; num: Integer = -1; Handicap: Integer = 100);
1075 var
1076 m: SSArray;
1077 _name, _model: String;
1078 a: Integer;
1079 begin
1080 if not g_Game_IsServer then Exit;
1082 if (g_Bot_GetCount() >= gMaxBots) then Exit;
1084 // Список названий моделей:
1085 m := g_PlayerModel_GetNames();
1086 if m = nil then
1087 Exit;
1089 // Команда:
1090 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
1091 Team := TEAM_COOP // COOP
1092 else
1093 if gGameSettings.GameMode = GM_DM then
1094 Team := TEAM_NONE // DM
1095 else
1096 if Team = TEAM_NONE then
1097 Team := BotList[num].team; // CTF / TDM
1099 // Выбираем настройки бота из списка по номеру или имени:
1100 lName := AnsiLowerCase(lName);
1101 if (num < 0) or (num > Length(BotList)-1) then
1102 num := -1;
1103 if (num = -1) and (lName <> '') and (BotList <> nil) then
1104 for a := 0 to High(BotList) do
1105 if AnsiLowerCase(BotList[a].name) = lName then
1106 begin
1107 num := a;
1108 Break;
1109 end;
1110 if num = -1 then
1111 Exit;
1113 // Имя бота:
1114 _name := BotList[num].name;
1115 // Занято - выбираем случайное:
1116 if not g_Player_ValidName(_name) then
1117 repeat
1118 _name := Format('DFBOT%.2d', [Random(100)]);
1119 until g_Player_ValidName(_name);
1121 // Модель:
1122 _model := BotList[num].model;
1123 // Нет такой - выбираем случайную:
1124 if not InSArray(_model, m) then
1125 _model := m[Random(Length(m))];
1127 // Создаем бота:
1128 with g_Player_Get(g_Player_Create(_model, BotList[num].color, Team, True)) as TBot do
1129 begin
1130 Name := _name;
1132 FDifficult.DiagFire := BotList[num].diag_fire;
1133 FDifficult.InvisFire := BotList[num].invis_fire;
1134 FDifficult.DiagPrecision := BotList[num].diag_precision;
1135 FDifficult.FlyPrecision := BotList[num].fly_precision;
1136 FDifficult.Cover := BotList[num].cover;
1137 FDifficult.CloseJump := BotList[num].close_jump;
1139 FHandicap := Handicap;
1141 for a := WP_FIRST to WP_LAST do
1142 begin
1143 FDifficult.WeaponPrior[a] := BotList[num].w_prior1[a];
1144 FDifficult.CloseWeaponPrior[a] := BotList[num].w_prior2[a];
1145 //FDifficult.SafeWeaponPrior[a] := BotList[num].w_prior3[a];
1146 end;
1148 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1150 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1151 end;
1152 end;
1154 procedure g_Bot_RemoveAll();
1155 var
1156 a: Integer;
1157 begin
1158 if not g_Game_IsServer then Exit;
1159 if gPlayers = nil then Exit;
1161 for a := 0 to High(gPlayers) do
1162 if gPlayers[a] <> nil then
1163 if gPlayers[a] is TBot then
1164 begin
1165 gPlayers[a].Lives := 0;
1166 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
1167 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
1168 g_Player_Remove(gPlayers[a].FUID);
1169 end;
1171 g_Bot_MixNames();
1172 end;
1174 procedure g_Bot_MixNames();
1175 var
1176 s: String;
1177 a, b: Integer;
1178 begin
1179 if BotNames <> nil then
1180 for a := 0 to High(BotNames) do
1181 begin
1182 b := Random(Length(BotNames));
1183 s := BotNames[a];
1184 Botnames[a] := BotNames[b];
1185 BotNames[b] := s;
1186 end;
1187 end;
1189 procedure g_Player_Remove(UID: Word);
1190 var
1191 i: Integer;
1192 begin
1193 if gPlayers = nil then Exit;
1195 if g_Game_IsServer and g_Game_IsNet then
1196 MH_SEND_PlayerDelete(UID);
1198 for i := 0 to High(gPlayers) do
1199 if gPlayers[i] <> nil then
1200 if gPlayers[i].FUID = UID then
1201 begin
1202 if gPlayers[i] is TPlayer then
1203 TPlayer(gPlayers[i]).Free()
1204 else
1205 TBot(gPlayers[i]).Free();
1206 gPlayers[i] := nil;
1207 Exit;
1208 end;
1209 end;
1211 procedure g_Player_Init();
1212 var
1213 F: TextFile;
1214 s: String;
1215 a, b: Integer;
1216 config: TConfig;
1217 sa: SSArray;
1218 path: AnsiString;
1219 begin
1220 BotNames := nil;
1222 path := BOTNAMES_FILENAME;
1223 if e_FindResource(DataDirs, path) = false then
1224 Exit;
1226 // Читаем возможные имена ботов из файла:
1227 AssignFile(F, path);
1228 Reset(F);
1230 while not EOF(F) do
1231 begin
1232 ReadLn(F, s);
1234 s := Trim(s);
1235 if s = '' then
1236 Continue;
1238 SetLength(BotNames, Length(BotNames)+1);
1239 BotNames[High(BotNames)] := s;
1240 end;
1242 CloseFile(F);
1244 // Перемешиваем их:
1245 g_Bot_MixNames();
1247 // Читаем файл с параметрами ботов:
1248 config := TConfig.CreateFile(path);
1249 BotList := nil;
1250 a := 0;
1252 while config.SectionExists(IntToStr(a)) do
1253 begin
1254 SetLength(BotList, Length(BotList)+1);
1256 with BotList[High(BotList)] do
1257 begin
1258 // Имя бота:
1259 name := config.ReadStr(IntToStr(a), 'name', '');
1260 // Модель:
1261 model := config.ReadStr(IntToStr(a), 'model', '');
1262 // Команда:
1263 if config.ReadStr(IntToStr(a), 'team', 'red') = 'red' then
1264 team := TEAM_RED
1265 else
1266 team := TEAM_BLUE;
1267 // Цвет модели:
1268 sa := parse(config.ReadStr(IntToStr(a), 'color', ''));
1269 color.R := StrToIntDef(sa[0], 0);
1270 color.G := StrToIntDef(sa[1], 0);
1271 color.B := StrToIntDef(sa[2], 0);
1272 // Вероятность стрельбы под углом:
1273 diag_fire := config.ReadInt(IntToStr(a), 'diag_fire', 0);
1274 // Вероятность ответного огня по невидимому сопернику:
1275 invis_fire := config.ReadInt(IntToStr(a), 'invis_fire', 0);
1276 // Точность стрельбы под углом:
1277 diag_precision := config.ReadInt(IntToStr(a), 'diag_precision', 0);
1278 // Точность стрельбы в полете:
1279 fly_precision := config.ReadInt(IntToStr(a), 'fly_precision', 0);
1280 // Точность уклонения от снарядов:
1281 cover := config.ReadInt(IntToStr(a), 'cover', 0);
1282 // Вероятность прыжка при приближении соперника:
1283 close_jump := config.ReadInt(IntToStr(a), 'close_jump', 0);
1284 // Приоритеты оружия для дальнего боя:
1285 sa := parse(config.ReadStr(IntToStr(a), 'w_prior1', ''));
1286 if Length(sa) = 10 then
1287 for b := 0 to 9 do
1288 w_prior1[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1289 // Приоритеты оружия для ближнего боя:
1290 sa := parse(config.ReadStr(IntToStr(a), 'w_prior2', ''));
1291 if Length(sa) = 10 then
1292 for b := 0 to 9 do
1293 w_prior2[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1295 {sa := parse(config.ReadStr(IntToStr(a), 'w_prior3', ''));
1296 if Length(sa) = 10 then
1297 for b := 0 to 9 do
1298 w_prior3[b] := EnsureRange(StrToInt(sa[b]), 0, 9);}
1299 end;
1301 a := a + 1;
1302 end;
1304 config.Free();
1305 SetLength(SavedStates, 0);
1306 end;
1308 procedure g_Player_Free();
1309 var
1310 i: Integer;
1311 begin
1312 if gPlayers <> nil then
1313 begin
1314 for i := 0 to High(gPlayers) do
1315 if gPlayers[i] <> nil then
1316 begin
1317 if gPlayers[i] is TPlayer then
1318 TPlayer(gPlayers[i]).Free()
1319 else
1320 TBot(gPlayers[i]).Free();
1321 gPlayers[i] := nil;
1322 end;
1324 gPlayers := nil;
1325 end;
1327 gPlayer1 := nil;
1328 gPlayer2 := nil;
1329 SetLength(SavedStates, 0);
1330 end;
1332 procedure g_Player_PreUpdate();
1333 var
1334 i: Integer;
1335 begin
1336 if gPlayers = nil then Exit;
1337 for i := 0 to High(gPlayers) do
1338 if gPlayers[i] <> nil then
1339 gPlayers[i].PreUpdate();
1340 end;
1342 procedure g_Player_UpdateAll();
1343 var
1344 i: Integer;
1345 begin
1346 if gPlayers = nil then Exit;
1348 //e_WriteLog('***g_Player_UpdateAll: ENTER', MSG_WARNING);
1349 for i := 0 to High(gPlayers) do
1350 begin
1351 if gPlayers[i] <> nil then
1352 begin
1353 if gPlayers[i] is TPlayer then
1354 begin
1355 gPlayers[i].Update();
1356 gPlayers[i].RealizeCurrentWeapon(); // WARNING! DO NOT MOVE THIS INTO `Update()`!
1357 end
1358 else
1359 begin
1360 // bot updates weapons in `UpdateCombat()`
1361 TBot(gPlayers[i]).Update();
1362 end;
1363 end;
1364 end;
1365 //e_WriteLog('***g_Player_UpdateAll: EXIT', MSG_WARNING);
1366 end;
1368 function g_Player_Get(UID: Word): TPlayer;
1369 var
1370 a: Integer;
1371 begin
1372 Result := nil;
1374 if gPlayers = nil then
1375 Exit;
1377 for a := 0 to High(gPlayers) do
1378 if gPlayers[a] <> nil then
1379 if gPlayers[a].FUID = UID then
1380 begin
1381 Result := gPlayers[a];
1382 Exit;
1383 end;
1384 end;
1386 function g_Player_GetCount(): Byte;
1387 var
1388 a: Integer;
1389 begin
1390 Result := 0;
1392 if gPlayers = nil then
1393 Exit;
1395 for a := 0 to High(gPlayers) do
1396 if gPlayers[a] <> nil then
1397 Result := Result + 1;
1398 end;
1400 function g_Bot_GetCount(): Integer;
1401 var
1402 a: Integer;
1403 begin
1404 Result := 0;
1406 if gPlayers = nil then
1407 Exit;
1409 for a := 0 to High(gPlayers) do
1410 if (gPlayers[a] <> nil) and (gPlayers[a] is TBot) then
1411 Result := Result + 1;
1412 end;
1414 function g_Player_GetStats(): TPlayerStatArray;
1415 var
1416 a: Integer;
1417 begin
1418 Result := nil;
1420 if gPlayers = nil then Exit;
1422 for a := 0 to High(gPlayers) do
1423 if gPlayers[a] <> nil then
1424 begin
1425 SetLength(Result, Length(Result)+1);
1426 with Result[High(Result)] do
1427 begin
1428 Num := a;
1429 Ping := gPlayers[a].FPing;
1430 Loss := gPlayers[a].FLoss;
1431 Name := gPlayers[a].FName;
1432 Team := gPlayers[a].FTeam;
1433 Frags := gPlayers[a].FFrags;
1434 Deaths := gPlayers[a].FDeath;
1435 Kills := gPlayers[a].FKills;
1436 Color := gPlayers[a].FModel.Color;
1437 Lives := gPlayers[a].FLives;
1438 Spectator := gPlayers[a].FSpectator;
1439 UID := gPlayers[a].FUID;
1440 end;
1441 end;
1442 end;
1444 procedure g_Player_ResetReady();
1445 var
1446 a: Integer;
1447 begin
1448 if not g_Game_IsServer then Exit;
1449 if gPlayers = nil then Exit;
1451 for a := 0 to High(gPlayers) do
1452 if gPlayers[a] <> nil then
1453 begin
1454 gPlayers[a].FReady := False;
1455 if g_Game_IsNet then
1456 MH_SEND_GameEvent(NET_EV_INTER_READY, gPlayers[a].UID, 'N');
1457 end;
1458 end;
1460 procedure g_Player_RememberAll;
1461 var
1462 i: Integer;
1463 begin
1464 for i := Low(gPlayers) to High(gPlayers) do
1465 if (gPlayers[i] <> nil) and gPlayers[i].alive then
1466 gPlayers[i].RememberState;
1467 end;
1469 procedure g_Player_ResetAll(Force, Silent: Boolean);
1470 var
1471 i: Integer;
1472 begin
1473 gTeamStat[TEAM_RED].Score := 0;
1474 gTeamStat[TEAM_BLUE].Score := 0;
1476 if gPlayers <> nil then
1477 for i := 0 to High(gPlayers) do
1478 if gPlayers[i] <> nil then
1479 begin
1480 gPlayers[i].Reset(Force);
1482 if gPlayers[i] is TPlayer then
1483 begin
1484 if (not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame then
1485 gPlayers[i].Respawn(Silent)
1486 else
1487 gPlayers[i].Spectate();
1488 end
1489 else
1490 TBot(gPlayers[i]).Respawn(Silent);
1491 end;
1492 end;
1494 function g_Player_CreateCorpse(Player: TPlayer): Integer;
1495 var
1496 i: Integer;
1497 find_id: DWORD;
1498 ok: Boolean;
1499 begin
1500 Result := -1;
1502 if Player.alive then
1503 Exit;
1505 // Разрываем связь с прежним трупом:
1506 i := Player.FCorpse;
1507 if (i >= 0) and (i < Length(gCorpses)) then
1508 begin
1509 if (gCorpses[i] <> nil) and (gCorpses[i].FPlayerUID = Player.FUID) then
1510 gCorpses[i].FPlayerUID := 0;
1511 end;
1513 if Player.FObj.Y >= gMapInfo.Height+128 then
1514 Exit;
1516 with Player do
1517 begin
1518 if (FHealth >= -50) or (gGibsCount = 0) then
1519 begin
1520 if (gCorpses = nil) or (Length(gCorpses) = 0) then
1521 Exit;
1523 ok := False;
1524 for find_id := 0 to High(gCorpses) do
1525 if gCorpses[find_id] = nil then
1526 begin
1527 ok := True;
1528 Break;
1529 end;
1531 if not ok then
1532 find_id := Random(Length(gCorpses));
1534 gCorpses[find_id] := TCorpse.Create(FObj.X, FObj.Y, FModel.GetName(), FHealth < -20);
1535 gCorpses[find_id].FModel.Color := FModel.Color;
1536 gCorpses[find_id].FObj.Vel := FObj.Vel;
1537 gCorpses[find_id].FObj.Accel := FObj.Accel;
1538 gCorpses[find_id].FPlayerUID := FUID;
1540 Result := find_id;
1541 end
1542 else
1543 g_Player_CreateGibs(FObj.X + PLAYER_RECT_CX, FObj.Y + PLAYER_RECT_CY, FModel.id, FModel.Color);
1544 end;
1545 end;
1547 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
1548 begin
1549 if (gShells = nil) or (Length(gShells) = 0) then
1550 Exit;
1552 with gShells[CurrentShell] do
1553 begin
1554 g_Obj_Init(@Obj);
1555 Obj.Rect.X := 0;
1556 Obj.Rect.Y := 0;
1557 if T = SHELL_BULLET then
1558 begin
1559 Obj.Rect.Width := 4;
1560 Obj.Rect.Height := 2;
1561 end
1562 else
1563 begin
1564 Obj.Rect.Width := 7;
1565 Obj.Rect.Height := 3;
1566 end;
1567 SType := T;
1568 alive := True;
1569 Obj.X := fX;
1570 Obj.Y := fY;
1571 g_Obj_Push(@Obj, dX + Random(4)-Random(4), dY-Random(4));
1572 positionChanged(); // this updates spatial accelerators
1573 RAngle := Random(360);
1574 Timeout := gTime + SHELL_TIMEOUT;
1576 if CurrentShell >= High(gShells) then
1577 CurrentShell := 0
1578 else
1579 Inc(CurrentShell);
1580 end;
1581 end;
1583 procedure g_Player_CreateGibs (fX, fY, mid: Integer; fColor: TRGB);
1584 var
1585 a: Integer;
1586 GibsArray: TGibsArray;
1587 {$IFDEF ENABLE_GFX}
1588 Blood: TModelBlood;
1589 {$ENDIF}
1590 begin
1591 if mid = -1 then
1592 Exit;
1593 if (gGibs = nil) or (Length(gGibs) = 0) then
1594 Exit;
1595 if not g_PlayerModel_GetGibs(mid, GibsArray) then
1596 Exit;
1598 {$IFDEF ENABLE_GFX}
1599 Blood := PlayerModelsArray[mid].Blood;
1600 {$ENDIF}
1602 for a := 0 to High(GibsArray) do
1603 with gGibs[CurrentGib] do
1604 begin
1605 ModelID := mid;
1606 GibID := GibsArray[a];
1607 Color := fColor;
1608 alive := True;
1609 g_Obj_Init(@Obj);
1610 {$IFNDEF HEADLESS}
1611 Obj.Rect := r_Render_GetGibRect(ModelID, GibID);
1612 {$ELSE}
1613 Obj.Rect.X := 16;
1614 Obj.Rect.Y := 16;
1615 Obj.Rect.Width := 16;
1616 Obj.Rect.Height := 16;
1617 {$ENDIF}
1618 Obj.X := fX - Obj.Rect.X - (Obj.Rect.Width div 2);
1619 Obj.Y := fY - Obj.Rect.Y - (Obj.Rect.Height div 2);
1620 g_Obj_PushA(@Obj, 25 + Random(10), Random(361));
1621 positionChanged(); // this updates spatial accelerators
1622 RAngle := Random(360);
1624 {$IFDEF ENABLE_GFX}
1625 if gBloodCount > 0 then
1626 begin
1627 g_GFX_Blood(
1628 fX,
1629 fY,
1630 16 * gBloodCount + Random(5 * gBloodCount),
1631 -16 + Random(33),
1632 -16 + Random(33),
1633 Random(48),
1634 Random(48),
1635 Blood.R,
1636 Blood.G,
1637 Blood.B,
1638 Blood.Kind
1639 );
1640 end;
1641 {$ENDIF}
1643 if CurrentGib >= High(gGibs) then
1644 CurrentGib := 0
1645 else
1646 Inc(CurrentGib);
1647 end;
1648 end;
1650 procedure g_Player_UpdatePhysicalObjects();
1651 var
1652 i: Integer;
1653 vel: TPoint2i;
1654 mr: Word;
1656 procedure ShellSound_Bounce(X, Y: Integer; T: Byte);
1657 var
1658 k: Integer;
1659 begin
1660 k := 1 + Random(2);
1661 if T = SHELL_BULLET then
1662 g_Sound_PlayExAt('SOUND_PLAYER_CASING' + IntToStr(k), X, Y)
1663 else
1664 g_Sound_PlayExAt('SOUND_PLAYER_SHELL' + IntToStr(k), X, Y);
1665 end;
1667 begin
1668 // Куски мяса:
1669 if gGibs <> nil then
1670 for i := 0 to High(gGibs) do
1671 if gGibs[i].alive then
1672 with gGibs[i] do
1673 begin
1674 Obj.oldX := Obj.X;
1675 Obj.oldY := Obj.Y;
1677 vel := Obj.Vel;
1678 mr := g_Obj_Move(@Obj, True, False, True);
1679 positionChanged(); // this updates spatial accelerators
1681 if WordBool(mr and MOVE_FALLOUT) then
1682 begin
1683 alive := False;
1684 Continue;
1685 end;
1687 // Отлетает от удара о стену/потолок/пол:
1688 if WordBool(mr and MOVE_HITWALL) then
1689 Obj.Vel.X := -(vel.X div 2);
1690 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1691 Obj.Vel.Y := -(vel.Y div 2);
1693 if (Obj.Vel.X >= 0) then
1694 begin // Clockwise
1695 RAngle := RAngle + Abs(Obj.Vel.X)*6 + Abs(Obj.Vel.Y);
1696 if RAngle >= 360 then
1697 RAngle := RAngle mod 360;
1698 end else begin // Counter-clockwise
1699 RAngle := RAngle - Abs(Obj.Vel.X)*6 - Abs(Obj.Vel.Y);
1700 if RAngle < 0 then
1701 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1702 end;
1704 // Сопротивление воздуха для куска трупа:
1705 if gTime mod (GAME_TICK*3) = 0 then
1706 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
1707 end;
1709 // Трупы:
1710 if gCorpses <> nil then
1711 for i := 0 to High(gCorpses) do
1712 if gCorpses[i] <> nil then
1713 if gCorpses[i].State = CORPSE_STATE_REMOVEME then
1714 begin
1715 gCorpses[i].Free();
1716 gCorpses[i] := nil;
1717 end
1718 else
1719 gCorpses[i].Update();
1721 // Гильзы:
1722 if gShells <> nil then
1723 for i := 0 to High(gShells) do
1724 if gShells[i].alive then
1725 with gShells[i] do
1726 begin
1727 Obj.oldX := Obj.X;
1728 Obj.oldY := Obj.Y;
1730 vel := Obj.Vel;
1731 mr := g_Obj_Move(@Obj, True, False, True);
1732 positionChanged(); // this updates spatial accelerators
1734 if WordBool(mr and MOVE_FALLOUT) or (gShells[i].Timeout < gTime) then
1735 begin
1736 alive := False;
1737 Continue;
1738 end;
1740 // Отлетает от удара о стену/потолок/пол:
1741 if WordBool(mr and MOVE_HITWALL) then
1742 begin
1743 Obj.Vel.X := -(vel.X div 2);
1744 if not WordBool(mr and MOVE_INWATER) then
1745 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1746 end;
1747 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1748 begin
1749 Obj.Vel.Y := -(vel.Y div 2);
1750 if Obj.Vel.X <> 0 then Obj.Vel.X := Obj.Vel.X div 2;
1751 if (Obj.Vel.X = 0) and (Obj.Vel.Y = 0) then
1752 begin
1753 if RAngle mod 90 <> 0 then
1754 RAngle := (RAngle div 90) * 90;
1755 end
1756 else if not WordBool(mr and MOVE_INWATER) then
1757 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1758 end;
1760 if (Obj.Vel.X >= 0) then
1761 begin // Clockwise
1762 RAngle := RAngle + Abs(Obj.Vel.X)*8 + Abs(Obj.Vel.Y);
1763 if RAngle >= 360 then
1764 RAngle := RAngle mod 360;
1765 end else begin // Counter-clockwise
1766 RAngle := RAngle - Abs(Obj.Vel.X)*8 - Abs(Obj.Vel.Y);
1767 if RAngle < 0 then
1768 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1769 end;
1770 end;
1771 end;
1774 procedure TGib.getMapBox (out x, y, w, h: Integer); inline;
1775 begin
1776 x := Obj.X+Obj.Rect.X;
1777 y := Obj.Y+Obj.Rect.Y;
1778 w := Obj.Rect.Width;
1779 h := Obj.Rect.Height;
1780 end;
1782 procedure TGib.moveBy (dx, dy: Integer); inline;
1783 begin
1784 if (dx <> 0) or (dy <> 0) then
1785 begin
1786 Obj.X += dx;
1787 Obj.Y += dy;
1788 positionChanged();
1789 end;
1790 end;
1793 procedure TShell.getMapBox (out x, y, w, h: Integer); inline;
1794 begin
1795 x := Obj.X;
1796 y := Obj.Y;
1797 w := Obj.Rect.Width;
1798 h := Obj.Rect.Height;
1799 end;
1801 procedure TShell.moveBy (dx, dy: Integer); inline;
1802 begin
1803 if (dx <> 0) or (dy <> 0) then
1804 begin
1805 Obj.X += dx;
1806 Obj.Y += dy;
1807 positionChanged();
1808 end;
1809 end;
1812 procedure TGib.positionChanged (); inline; begin end;
1813 procedure TShell.positionChanged (); inline; begin end;
1816 procedure g_Player_RemoveAllCorpses();
1817 var
1818 i: Integer;
1819 begin
1820 gGibs := nil;
1821 gShells := nil;
1822 SetLength(gGibs, MaxGibs);
1823 SetLength(gShells, MaxGibs);
1824 CurrentGib := 0;
1825 CurrentShell := 0;
1827 if gCorpses <> nil then
1828 for i := 0 to High(gCorpses) do
1829 gCorpses[i].Free();
1831 gCorpses := nil;
1832 SetLength(gCorpses, MaxCorpses);
1833 end;
1835 procedure g_Player_Corpses_SaveState (st: TStream);
1836 var
1837 count, i: Integer;
1838 begin
1839 // Считаем количество существующих трупов
1840 count := 0;
1841 for i := 0 to High(gCorpses) do if (gCorpses[i] <> nil) then Inc(count);
1843 // Количество трупов
1844 utils.writeInt(st, LongInt(count));
1846 if (count = 0) then exit;
1848 // Сохраняем трупы
1849 for i := 0 to High(gCorpses) do
1850 begin
1851 if gCorpses[i] <> nil then
1852 begin
1853 // Название модели
1854 utils.writeStr(st, gCorpses[i].FModel.GetName());
1855 // Тип смерти
1856 utils.writeBool(st, gCorpses[i].Mess);
1857 // Сохраняем данные трупа:
1858 gCorpses[i].SaveState(st);
1859 end;
1860 end;
1861 end;
1864 procedure g_Player_Corpses_LoadState (st: TStream);
1865 var
1866 count, i: Integer;
1867 str: String;
1868 b: Boolean;
1869 begin
1870 assert(st <> nil);
1872 g_Player_RemoveAllCorpses();
1874 // Количество трупов:
1875 count := utils.readLongInt(st);
1876 if (count < 0) or (count > Length(gCorpses)) then raise XStreamError.Create('invalid number of corpses');
1878 if (count = 0) then exit;
1880 // Загружаем трупы
1881 for i := 0 to count-1 do
1882 begin
1883 // Название модели:
1884 str := utils.readStr(st);
1885 // Тип смерти
1886 b := utils.readBool(st);
1887 // Создаем труп
1888 gCorpses[i] := TCorpse.Create(0, 0, str, b);
1889 // Загружаем данные трупа
1890 gCorpses[i].LoadState(st);
1891 end;
1892 end;
1895 { T P l a y e r : }
1897 function TPlayer.isValidViewPort (): Boolean; inline; begin result := (viewPortW > 0) and (viewPortH > 0); end;
1899 procedure TPlayer.BFGHit();
1900 begin
1901 g_Weapon_BFGHit(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1902 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2));
1903 if g_Game_IsServer and g_Game_IsNet then
1904 MH_SEND_Effect(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1905 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
1906 0, NET_GFX_BFGHIT);
1907 end;
1909 procedure TPlayer.ChangeModel(ModelName: string);
1910 var
1911 locModel: TPlayerModel;
1912 begin
1913 locModel := g_PlayerModel_Get(ModelName);
1914 if locModel = nil then Exit;
1916 FModel.Free();
1917 FModel := locModel;
1918 end;
1920 procedure TPlayer.SetModel(ModelName: string);
1921 var
1922 m: TPlayerModel;
1923 begin
1924 m := g_PlayerModel_Get(ModelName);
1925 if m = nil then
1926 begin
1927 g_SimpleError(Format(_lc[I_GAME_ERROR_MODEL_FALLBACK], [ModelName]));
1928 m := g_PlayerModel_Get('doomer');
1929 if m = nil then
1930 begin
1931 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], ['doomer']));
1932 Exit;
1933 end;
1934 end;
1936 if FModel <> nil then
1937 FModel.Free();
1939 FModel := m;
1941 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1942 FModel.Color := FColor
1943 else
1944 FModel.Color := TEAMCOLOR[FTeam];
1945 FModel.SetWeapon(FCurrWeap);
1946 FModel.SetFlag(FFlag);
1947 SetDirection(FDirection);
1948 end;
1950 procedure TPlayer.SetColor(Color: TRGB);
1951 begin
1952 FColor := Color;
1953 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1954 if FModel <> nil then FModel.Color := Color;
1955 end;
1959 function TPlayer.GetColor(): TRGB;
1960 begin
1961 result := FModel.Color;
1962 end;
1964 procedure TPlayer.SetWeaponPrefs(Prefs: Array of Byte);
1965 var
1966 i: Integer;
1967 begin
1968 for i := WP_FIRST to WP_LAST + 1 do
1969 begin
1970 if (Prefs[i] > WP_LAST + 1) then
1971 FWeapPreferences[i] := 0
1972 else
1973 FWeapPreferences[i] := Prefs[i];
1974 end;
1975 end;
1977 procedure TPlayer.SetWeaponPref(Weapon, Pref: Byte);
1978 begin
1979 if (Weapon > WP_LAST + 1) then
1980 exit
1981 else if (Pref <= WP_LAST + 1) and (Weapon <= WP_LAST + 1) then
1982 FWeapPreferences[Weapon] := Pref
1983 else if (Weapon <= WP_LAST + 1) and (Pref > WP_LAST + 1) then
1984 FWeapPreferences[Weapon] := 0;
1985 end;
1987 function TPlayer.GetWeaponPref(Weapon: Byte) : Byte;
1988 begin
1989 if (Weapon > WP_LAST + 1) then
1990 result := 0
1991 else if (FWeapPreferences[Weapon] > WP_LAST + 1) then
1992 result := 0
1993 else
1994 result := FWeapPreferences[Weapon];
1995 end;
1997 function TPlayer.GetMorePrefered() : Byte;
1998 var
1999 testedWeap, i: Byte;
2000 begin
2001 testedWeap := FCurrWeap;
2002 for i := WP_FIRST to WP_LAST do
2003 if FWeapon[i] and maySwitch(i) and (FWeapPreferences[i] > FWeapPreferences[testedWeap]) then
2004 testedWeap := i;
2005 if (R_BERSERK in FRulez) and (FWeapPreferences[WP_LAST + 1] > FWeapPreferences[testedWeap]) then
2006 testedWeap := WEAPON_KASTET;
2007 result := testedWeap;
2008 end;
2010 function TPlayer.maySwitch(Weapon: Byte) : Boolean;
2011 begin
2012 result := true;
2013 if (Weapon = WEAPON_KASTET) and (FSkipFist <> 0) then
2014 begin
2015 if (FSkipFist = 1) and (not (R_BERSERK in FRulez)) then
2016 result := false;
2017 end
2018 else if (FSwitchToEmpty = 0) and (not hasAmmoForShooting(Weapon)) then
2019 result := false;
2020 end;
2022 procedure TPlayer.SwitchTeam;
2023 begin
2024 if g_Game_IsClient then
2025 Exit;
2026 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then Exit;
2028 if gGameOn and FAlive then
2029 Kill(K_SIMPLEKILL, FUID, HIT_SELF);
2031 if FTeam = TEAM_RED then
2032 begin
2033 ChangeTeam(TEAM_BLUE);
2034 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_BLUE], [FName]), True);
2035 if g_Game_IsNet then
2036 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_BLUE, FName);
2037 end
2038 else
2039 begin
2040 ChangeTeam(TEAM_RED);
2041 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_RED], [FName]), True);
2042 if g_Game_IsNet then
2043 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_RED, FName);
2044 end;
2045 FPreferredTeam := FTeam;
2046 end;
2048 procedure TPlayer.ChangeTeam(Team: Byte);
2049 var
2050 OldTeam: Byte;
2051 begin
2052 OldTeam := FTeam;
2053 FTeam := Team;
2054 case Team of
2055 TEAM_RED, TEAM_BLUE:
2056 FModel.Color := TEAMCOLOR[Team];
2057 else
2058 FModel.Color := FColor;
2059 end;
2060 if (FTeam <> OldTeam) and g_Game_IsNet and g_Game_IsServer then
2061 MH_SEND_PlayerStats(FUID);
2062 end;
2065 procedure TPlayer.CollideItem();
2066 var
2067 i: Integer;
2068 r: Boolean;
2069 begin
2070 if gItems = nil then Exit;
2071 if not FAlive then Exit;
2073 for i := 0 to High(gItems) do
2074 with gItems[i] do
2075 begin
2076 if (ItemType <> ITEM_NONE) and alive then
2077 if g_Obj_Collide(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
2078 PLAYER_RECT.Height, @Obj) then
2079 begin
2080 if not PickItem(ItemType, gItems[i].Respawnable, r) then Continue;
2082 if ItemType in [ITEM_SPHERE_BLUE, ITEM_SPHERE_WHITE, ITEM_INVUL] then
2083 g_Sound_PlayExAt('SOUND_ITEM_GETRULEZ', FObj.X, FObj.Y)
2084 else if ItemType in [ITEM_MEDKIT_SMALL, ITEM_MEDKIT_LARGE, ITEM_MEDKIT_BLACK] then
2085 g_Sound_PlayExAt('SOUND_ITEM_GETMED', FObj.X, FObj.Y)
2086 else g_Sound_PlayExAt('SOUND_ITEM_GETITEM', FObj.X, FObj.Y);
2088 // Надо убрать с карты, если это не ключ, которым нужно поделится с другим игроком:
2089 if r and not ((ItemType in [ITEM_KEY_RED, ITEM_KEY_GREEN, ITEM_KEY_BLUE]) and
2090 (gGameSettings.GameType = GT_SINGLE) and
2091 (g_Player_GetCount() > 1)) then
2092 if not Respawnable then g_Items_Remove(i) else g_Items_Pick(i);
2093 end;
2094 end;
2095 end;
2098 function TPlayer.CollideLevel(XInc, YInc: Integer): Boolean;
2099 begin
2100 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
2101 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_WALL,
2102 False);
2103 end;
2105 constructor TPlayer.Create();
2106 begin
2107 viewPortX := 0;
2108 viewPortY := 0;
2109 viewPortW := 0;
2110 viewPortH := 0;
2111 mEDamageType := HIT_SOME;
2113 FIamBot := False;
2114 FDummy := False;
2115 FSpawned := False;
2117 FSawSound := TPlayableSound.Create();
2118 FSawSoundIdle := TPlayableSound.Create();
2119 FSawSoundHit := TPlayableSound.Create();
2120 FSawSoundSelect := TPlayableSound.Create();
2121 FFlameSoundOn := TPlayableSound.Create();
2122 FFlameSoundOff := TPlayableSound.Create();
2123 FFlameSoundWork := TPlayableSound.Create();
2124 FJetSoundFly := TPlayableSound.Create();
2125 FJetSoundOn := TPlayableSound.Create();
2126 FJetSoundOff := TPlayableSound.Create();
2128 FSawSound.SetByName('SOUND_WEAPON_FIRESAW');
2129 FSawSoundIdle.SetByName('SOUND_WEAPON_IDLESAW');
2130 FSawSoundHit.SetByName('SOUND_WEAPON_HITSAW');
2131 FSawSoundSelect.SetByName('SOUND_WEAPON_SELECTSAW');
2132 FFlameSoundOn.SetByName('SOUND_WEAPON_FLAMEON');
2133 FFlameSoundOff.SetByName('SOUND_WEAPON_FLAMEOFF');
2134 FFlameSoundWork.SetByName('SOUND_WEAPON_FLAMEWORK');
2135 FJetSoundFly.SetByName('SOUND_PLAYER_JETFLY');
2136 FJetSoundOn.SetByName('SOUND_PLAYER_JETON');
2137 FJetSoundOff.SetByName('SOUND_PLAYER_JETOFF');
2139 FSpectatePlayer := -1;
2140 FClientID := -1;
2141 FPing := 0;
2142 FLoss := 0;
2143 FSavedStateNum := -1;
2144 FShellTimer := -1;
2145 FFireTime := 0;
2146 FFirePainTime := 0;
2147 FFireAttacker := 0;
2148 FHandicap := 100;
2149 FCorpse := -1;
2151 FActualModelName := 'doomer';
2153 g_Obj_Init(@FObj);
2154 FObj.Rect := PLAYER_RECT;
2156 FBFGFireCounter := -1;
2157 FJustTeleported := False;
2158 FNetTime := 0;
2160 FWaitForFirstSpawn := false;
2161 FPunchAnim := TAnimationState.Create(False, 1, 4);
2162 FPunchAnim.Disable;
2164 resetWeaponQueue();
2165 end;
2167 procedure TPlayer.positionChanged (); inline;
2168 begin
2169 end;
2171 procedure TPlayer.doDamage (v: Integer);
2172 begin
2173 if (v <= 0) then exit;
2174 if (v > 32767) then v := 32767;
2175 Damage(v, 0, 0, 0, mEDamageType);
2176 end;
2178 procedure TPlayer.Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte);
2179 var
2180 c: Word;
2181 begin
2182 if (not g_Game_IsClient) and (not FAlive) then
2183 Exit;
2185 FLastHit := t;
2187 // Неуязвимость не спасает от ловушек:
2188 if ((t = HIT_TRAP) or (t = HIT_SELF)) and (not FGodMode) then
2189 begin
2190 if not g_Game_IsClient then
2191 begin
2192 FArmor := 0;
2193 if t = HIT_TRAP then
2194 begin
2195 // Ловушка убивает сразу:
2196 FHealth := -100;
2197 Kill(K_EXTRAHARDKILL, SpawnerUID, t);
2198 end;
2199 if t = HIT_SELF then
2200 begin
2201 // Самоубийство:
2202 FHealth := 0;
2203 Kill(K_SIMPLEKILL, SpawnerUID, t);
2204 end;
2205 end;
2206 // Обнулить действия примочек, чтобы фон пропал
2207 FMegaRulez[MR_SUIT] := 0;
2208 FMegaRulez[MR_INVUL] := 0;
2209 FMegaRulez[MR_INVIS] := 0;
2210 FSpawnInvul := 0;
2211 FBerserk := 0;
2212 end;
2214 // Но от остального спасает:
2215 if FMegaRulez[MR_INVUL] >= gTime then
2216 Exit;
2218 // Чит-код "ГОРЕЦ":
2219 if FGodMode then
2220 Exit;
2222 // Если есть урон своим, или ранил сам себя, или тебя ранил противник:
2223 if LongBool(gGameSettings.Options and GAME_OPTION_TEAMDAMAGE) or
2224 (SpawnerUID = FUID) or
2225 (not SameTeam(FUID, SpawnerUID)) then
2226 begin
2227 FLastSpawnerUID := SpawnerUID;
2229 // Кровь (пузырьки, если в воде):
2230 if gBloodCount > 0 then
2231 begin
2232 c := Min(value, 200)*gBloodCount + Random(Min(value, 200) div 2);
2233 if value div 4 <= c then
2234 c := c - (value div 4)
2235 else
2236 c := 0;
2238 if (t = HIT_SOME) and (vx = 0) and (vy = 0) then
2239 MakeBloodSimple(c)
2240 else
2241 case t of
2242 HIT_TRAP, HIT_ACID, HIT_FLAME, HIT_SELF: MakeBloodSimple(c);
2243 HIT_BFG, HIT_ROCKET, HIT_SOME: MakeBloodVector(c, vx, vy);
2244 end;
2246 {$IFDEF ENABLE_GFX}
2247 if t = HIT_WATER then
2248 begin
2249 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
2250 FObj.Y+PLAYER_RECT.Y-4, value div 2, 8, 4);
2251 if Random(2) = 0
2252 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
2253 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
2254 end;
2255 {$ENDIF}
2256 end;
2258 // Буфер урона:
2259 if FAlive then
2260 Inc(FDamageBuffer, value);
2262 // Вспышка боли:
2263 if gFlash <> 0 then
2264 FPain := FPain + value;
2265 end;
2267 if g_Game_IsServer and g_Game_IsNet then
2268 begin
2269 MH_SEND_PlayerDamage(FUID, t, SpawnerUID, value, vx, vy);
2270 MH_SEND_PlayerStats(FUID);
2271 MH_SEND_PlayerPos(False, FUID);
2272 end;
2273 end;
2275 function TPlayer.Heal(value: Word; Soft: Boolean): Boolean;
2276 begin
2277 Result := False;
2278 if g_Game_IsClient then
2279 Exit;
2280 if not FAlive then
2281 Exit;
2283 if Soft and (FHealth < PLAYER_HP_SOFT) then
2284 begin
2285 IncMax(FHealth, value, PLAYER_HP_SOFT);
2286 Result := True;
2287 end;
2288 if (not Soft) and (FHealth < PLAYER_HP_LIMIT) then
2289 begin
2290 IncMax(FHealth, value, PLAYER_HP_LIMIT);
2291 Result := True;
2292 end;
2294 if Result and g_Game_IsServer and g_Game_IsNet then
2295 MH_SEND_PlayerStats(FUID);
2296 end;
2298 destructor TPlayer.Destroy();
2299 begin
2300 if (gPlayer1 <> nil) and (gPlayer1.FUID = FUID) then
2301 gPlayer1 := nil;
2302 if (gPlayer2 <> nil) and (gPlayer2.FUID = FUID) then
2303 gPlayer2 := nil;
2305 FSawSound.Free();
2306 FSawSoundIdle.Free();
2307 FSawSoundHit.Free();
2308 FSawSoundSelect.Free();
2309 FFlameSoundOn.Free();
2310 FFlameSoundOff.Free();
2311 FFlameSoundWork.Free();
2312 FJetSoundFly.Free();
2313 FJetSoundOn.Free();
2314 FJetSoundOff.Free();
2315 FModel.Free();
2316 FPunchAnim.Free();
2318 inherited;
2319 end;
2321 procedure TPlayer.DoPunch();
2322 begin
2323 FPunchAnim.Reset;
2324 FPunchAnim.Enable;
2325 end;
2327 procedure TPlayer.Fire();
2328 var
2329 f, DidFire: Boolean;
2330 wx, wy, xd, yd: Integer;
2331 locobj: TObj;
2332 begin
2333 if g_Game_IsClient then Exit;
2334 // FBFGFireCounter - время перед выстрелом (для BFG)
2335 // FReloading - время после выстрела (для всего)
2337 if FSpectator then
2338 begin
2339 Respawn(False);
2340 Exit;
2341 end;
2343 if FReloading[FCurrWeap] <> 0 then Exit;
2345 DidFire := False;
2347 f := False;
2348 wx := FObj.X+WEAPONPOINT[FDirection].X;
2349 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
2350 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
2351 yd := wy+firediry();
2353 case FCurrWeap of
2354 WEAPON_KASTET:
2355 begin
2356 DoPunch();
2357 if R_BERSERK in FRulez then
2358 begin
2359 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
2360 locobj.X := FObj.X+FObj.Rect.X;
2361 locobj.Y := FObj.Y+FObj.Rect.Y;
2362 locobj.rect.X := 0;
2363 locobj.rect.Y := 0;
2364 locobj.rect.Width := 39;
2365 locobj.rect.Height := 52;
2366 locobj.Vel.X := (xd-wx) div 2;
2367 locobj.Vel.Y := (yd-wy) div 2;
2368 locobj.Accel.X := xd-wx;
2369 locobj.Accel.y := yd-wy;
2371 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
2372 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
2373 else
2374 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
2376 if (gFlash = 1) and (FPain < 50) then FPain := min(FPain + 25, 50);
2377 end
2378 else
2379 begin
2380 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
2381 end;
2383 DidFire := True;
2384 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2385 end;
2387 WEAPON_SAW:
2388 begin
2389 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
2390 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
2391 begin
2392 FSawSoundSelect.Stop();
2393 FSawSound.Stop();
2394 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
2395 end
2396 else if not FSawSoundHit.IsPlaying() then
2397 begin
2398 FSawSoundSelect.Stop();
2399 FSawSound.PlayAt(FObj.X, FObj.Y);
2400 end;
2402 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2403 DidFire := True;
2404 f := True;
2405 end;
2407 WEAPON_PISTOL:
2408 if FAmmo[A_BULLETS] > 0 then
2409 begin
2410 g_Weapon_pistol(wx, wy, xd, yd, FUID);
2411 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2412 Dec(FAmmo[A_BULLETS]);
2413 FFireAngle := FAngle;
2414 f := True;
2415 DidFire := True;
2416 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2417 GameVelX, GameVelY-2, SHELL_BULLET);
2418 end;
2420 WEAPON_SHOTGUN1:
2421 if FAmmo[A_SHELLS] > 0 then
2422 begin
2423 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2424 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', wx, wy);
2425 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2426 Dec(FAmmo[A_SHELLS]);
2427 FFireAngle := FAngle;
2428 f := True;
2429 DidFire := True;
2430 FShellTimer := 10;
2431 FShellType := SHELL_SHELL;
2432 end;
2434 WEAPON_SHOTGUN2:
2435 if FAmmo[A_SHELLS] >= 2 then
2436 begin
2437 g_Weapon_dshotgun(wx, wy, xd, yd, FUID);
2438 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2439 Dec(FAmmo[A_SHELLS], 2);
2440 FFireAngle := FAngle;
2441 f := True;
2442 DidFire := True;
2443 FShellTimer := 13;
2444 FShellType := SHELL_DBLSHELL;
2445 end;
2447 WEAPON_CHAINGUN:
2448 if FAmmo[A_BULLETS] > 0 then
2449 begin
2450 g_Weapon_mgun(wx, wy, xd, yd, FUID);
2451 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', wx, wy);
2452 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2453 Dec(FAmmo[A_BULLETS]);
2454 FFireAngle := FAngle;
2455 f := True;
2456 DidFire := True;
2457 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2458 GameVelX, GameVelY-2, SHELL_BULLET);
2459 end;
2461 WEAPON_ROCKETLAUNCHER:
2462 if FAmmo[A_ROCKETS] > 0 then
2463 begin
2464 g_Weapon_rocket(wx, wy, xd, yd, FUID);
2465 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2466 Dec(FAmmo[A_ROCKETS]);
2467 FFireAngle := FAngle;
2468 f := True;
2469 DidFire := True;
2470 end;
2472 WEAPON_PLASMA:
2473 if FAmmo[A_CELLS] > 0 then
2474 begin
2475 g_Weapon_plasma(wx, wy, xd, yd, FUID);
2476 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2477 Dec(FAmmo[A_CELLS]);
2478 FFireAngle := FAngle;
2479 f := True;
2480 DidFire := True;
2481 end;
2483 WEAPON_BFG:
2484 if (FAmmo[A_CELLS] >= 40) and (FBFGFireCounter = -1) then
2485 begin
2486 FBFGFireCounter := 17;
2487 if not FNoReload then
2488 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', FObj.X, FObj.Y);
2489 Dec(FAmmo[A_CELLS], 40);
2490 DidFire := True;
2491 end;
2493 WEAPON_SUPERPULEMET:
2494 if FAmmo[A_SHELLS] > 0 then
2495 begin
2496 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2497 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', wx, wy);
2498 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2499 Dec(FAmmo[A_SHELLS]);
2500 FFireAngle := FAngle;
2501 f := True;
2502 DidFire := True;
2503 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2504 GameVelX, GameVelY-2, SHELL_SHELL);
2505 end;
2507 WEAPON_FLAMETHROWER:
2508 if FAmmo[A_FUEL] > 0 then
2509 begin
2510 g_Weapon_flame(wx, wy, xd, yd, FUID);
2511 FlamerOn;
2512 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2513 Dec(FAmmo[A_FUEL]);
2514 FFireAngle := FAngle;
2515 f := True;
2516 DidFire := True;
2517 end
2518 else
2519 begin
2520 FlamerOff;
2521 if g_Game_IsNet and g_Game_IsServer then MH_SEND_PlayerStats(FUID);
2522 end;
2523 end;
2525 if g_Game_IsNet then
2526 begin
2527 if DidFire then
2528 begin
2529 if FCurrWeap <> WEAPON_BFG then
2530 MH_SEND_PlayerFire(FUID, FCurrWeap, wx, wy, xd, yd, LastShotID)
2531 else
2532 if not FNoReload then
2533 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_WEAPON_STARTFIREBFG');
2534 end;
2536 MH_SEND_PlayerStats(FUID);
2537 end;
2539 if not f then Exit;
2541 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
2542 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
2543 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
2544 end;
2546 function TPlayer.GetAmmoByWeapon(Weapon: Byte): Word;
2547 begin
2548 case Weapon of
2549 WEAPON_PISTOL, WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS];
2550 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS];
2551 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS];
2552 WEAPON_PLASMA, WEAPON_BFG: Result := FAmmo[A_CELLS];
2553 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL];
2554 else Result := 0;
2555 end;
2556 end;
2558 function TPlayer.HeadInLiquid(XInc, YInc: Integer): Boolean;
2559 begin
2560 Result := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X+XInc, FObj.Y+PLAYER_HEADRECT.Y+YInc,
2561 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
2562 PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, True);
2563 end;
2565 procedure TPlayer.FlamerOn;
2566 begin
2567 FFlameSoundOff.Stop();
2568 FFlameSoundOff.SetPosition(0);
2569 if FFlaming then
2570 begin
2571 if (not FFlameSoundOn.IsPlaying()) and (not FFlameSoundWork.IsPlaying()) then
2572 FFlameSoundWork.PlayAt(FObj.X, FObj.Y);
2573 end
2574 else
2575 begin
2576 FFlameSoundOn.PlayAt(FObj.X, FObj.Y);
2577 FFlaming := True;
2578 end;
2579 end;
2581 procedure TPlayer.FlamerOff;
2582 begin
2583 if FFlaming then
2584 begin
2585 FFlameSoundOn.Stop();
2586 FFlameSoundOn.SetPosition(0);
2587 FFlameSoundWork.Stop();
2588 FFlameSoundWork.SetPosition(0);
2589 FFlameSoundOff.PlayAt(FObj.X, FObj.Y);
2590 FFlaming := False;
2591 end;
2592 end;
2594 procedure TPlayer.JetpackOn;
2595 begin
2596 FJetSoundFly.Stop;
2597 FJetSoundOff.Stop;
2598 FJetSoundOn.SetPosition(0);
2599 FJetSoundOn.PlayAt(FObj.X, FObj.Y);
2600 FlySmoke(8);
2601 end;
2603 procedure TPlayer.JetpackOff;
2604 begin
2605 FJetSoundFly.Stop;
2606 FJetSoundOn.Stop;
2607 FJetSoundOff.SetPosition(0);
2608 FJetSoundOff.PlayAt(FObj.X, FObj.Y);
2609 end;
2611 procedure TPlayer.CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
2612 begin
2613 if Timeout <= 0 then
2614 exit;
2615 if (FMegaRulez[MR_SUIT] > gTime) or (FMegaRulez[MR_INVUL] > gTime) then
2616 exit; // Не загораемся когда есть защита
2617 if g_Obj_CollidePanel(@FObj, 0, 0, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2) then
2618 exit; // Не подгораем в воде на всякий случай
2619 if FFireTime <= 0 then
2620 g_Sound_PlayExAt('SOUND_IGNITE', FObj.X, FObj.Y);
2621 FFireTime := Timeout;
2622 FFireAttacker := Attacker;
2623 if g_Game_IsNet and g_Game_IsServer then
2624 MH_SEND_PlayerStats(FUID);
2625 end;
2627 procedure TPlayer.Jump();
2628 begin
2629 if gFly or FJetpack then
2630 begin
2631 // Полет (чит-код или джетпак):
2632 if FObj.Vel.Y > -VEL_FLY then
2633 FObj.Vel.Y := FObj.Vel.Y - 3;
2634 if FJetpack then
2635 begin
2636 if FJetFuel > 0 then
2637 Dec(FJetFuel);
2638 if (FJetFuel < 1) and g_Game_IsServer then
2639 begin
2640 FJetpack := False;
2641 JetpackOff;
2642 if g_Game_IsNet then
2643 MH_SEND_PlayerStats(FUID);
2644 end;
2645 end;
2646 Exit;
2647 end;
2649 // Не включать джетпак в режиме прохождения сквозь стены
2650 if FGhost then
2651 FCanJetpack := False;
2653 // Прыгаем или всплываем:
2654 if (CollideLevel(0, 1) or
2655 g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y+36, PLAYER_RECT.Width,
2656 PLAYER_RECT.Height-33, PANEL_STEP, False)
2657 ) and (FObj.Accel.Y = 0) then // Не прыгать, если есть вертикальное ускорение
2658 begin
2659 FObj.Vel.Y := -VEL_JUMP;
2660 FCanJetpack := False;
2661 end
2662 else
2663 begin
2664 if BodyInLiquid(0, 0) then
2665 FObj.Vel.Y := -VEL_SW
2666 else if (FJetFuel > 0) and FCanJetpack and
2667 g_Game_IsServer and (not g_Obj_CollideLiquid(@FObj, 0, 0)) then
2668 begin
2669 FJetpack := True;
2670 JetpackOn;
2671 if g_Game_IsNet then
2672 MH_SEND_PlayerStats(FUID);
2673 end;
2674 end;
2675 end;
2677 procedure TPlayer.Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
2678 var
2679 a, i, k, ab, ar: Byte;
2680 s: String;
2681 mon: TMonster;
2682 plr: TPlayer;
2683 srv, netsrv: Boolean;
2684 DoFrags: Boolean;
2685 OldLR: Byte;
2686 KP: TPlayer;
2687 it: PItem;
2689 procedure PushItem(t: Byte);
2690 var
2691 id: DWORD;
2692 begin
2693 id := g_Items_Create(FObj.X, FObj.Y, t, True, False);
2694 it := g_Items_ByIdx(id);
2695 if KillType = K_EXTRAHARDKILL then // -7..+7; -8..0
2696 begin
2697 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-7+Random(15),
2698 (FObj.Vel.Y div 2)-Random(9));
2699 it.positionChanged(); // this updates spatial accelerators
2700 end
2701 else
2702 begin
2703 if KillType = K_HARDKILL then // -5..+5; -5..0
2704 begin
2705 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-5+Random(11),
2706 (FObj.Vel.Y div 2)-Random(6));
2707 end
2708 else // -3..+3; -3..0
2709 begin
2710 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-3+Random(7),
2711 (FObj.Vel.Y div 2)-Random(4));
2712 end;
2713 it.positionChanged(); // this updates spatial accelerators
2714 end;
2716 if g_Game_IsNet and g_Game_IsServer then
2717 MH_SEND_ItemSpawn(True, id);
2718 end;
2720 begin
2721 DoFrags := (gGameSettings.MaxLives = 0) or (gGameSettings.GameMode = GM_COOP);
2722 Srv := g_Game_IsServer;
2723 Netsrv := g_Game_IsServer and g_Game_IsNet;
2724 if Srv then FDeath := FDeath + 1;
2725 if FAlive then
2726 begin
2727 if FGhost then
2728 FGhost := False;
2729 if not FPhysics then
2730 FPhysics := True;
2731 FAlive := False;
2732 end;
2733 FShellTimer := -1;
2735 if (gGameSettings.MaxLives > 0) and Srv and (gLMSRespawn = LMS_RESPAWN_NONE) then
2736 begin
2737 if FLives > 0 then FLives := FLives - 1;
2738 if FLives = 0 then FNoRespawn := True;
2739 end;
2741 // Номер типа смерти:
2742 a := 1;
2743 case KillType of
2744 K_SIMPLEKILL: a := 1;
2745 K_HARDKILL: a := 2;
2746 K_EXTRAHARDKILL: a := 3;
2747 K_FALLKILL: a := 4;
2748 end;
2750 // Звук смерти:
2751 if not FModel.PlaySound(MODELSOUND_DIE, a, FObj.X, FObj.Y) then
2752 for i := 1 to 3 do
2753 if FModel.PlaySound(MODELSOUND_DIE, i, FObj.X, FObj.Y) then
2754 Break;
2756 // Время респауна:
2757 if Srv then
2758 case KillType of
2759 K_SIMPLEKILL:
2760 FTime[T_RESPAWN] := gTime + TIME_RESPAWN1;
2761 K_HARDKILL:
2762 FTime[T_RESPAWN] := gTime + TIME_RESPAWN2;
2763 K_EXTRAHARDKILL, K_FALLKILL:
2764 FTime[T_RESPAWN] := gTime + TIME_RESPAWN3;
2765 end;
2767 // Переключаем состояние:
2768 case KillType of
2769 K_SIMPLEKILL:
2770 SetAction(A_DIE1);
2771 K_HARDKILL, K_EXTRAHARDKILL:
2772 SetAction(A_DIE2);
2773 end;
2775 // Реакция монстров на смерть игрока:
2776 if (KillType <> K_FALLKILL) and (Srv) then
2777 g_Monsters_killedp();
2779 if SpawnerUID = FUID then
2780 begin // Самоубился
2781 if Srv then
2782 begin
2783 if gGameSettings.GameMode = GM_TDM then
2784 Dec(gTeamStat[FTeam].Score);
2785 if DoFrags or (gGameSettings.GameMode = GM_TDM) then
2786 begin
2787 Dec(FFrags);
2788 FLastFrag := 0;
2789 end;
2790 end;
2791 g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2792 end
2793 else
2794 if g_GetUIDType(SpawnerUID) = UID_PLAYER then
2795 begin // Убит другим игроком
2796 KP := g_Player_Get(SpawnerUID);
2797 if (KP <> nil) and Srv then
2798 begin
2799 if (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2800 if SameTeam(FUID, SpawnerUID) then
2801 begin
2802 Dec(KP.FFrags);
2803 KP.FLastFrag := 0;
2804 end else
2805 begin
2806 Inc(KP.FFrags);
2807 KP.FragCombo();
2808 end;
2810 if (gGameSettings.GameMode = GM_TDM) and DoFrags then
2811 Inc(gTeamStat[KP.Team].Score,
2812 IfThen(SameTeam(FUID, SpawnerUID), -1, 1));
2814 if netsrv then MH_SEND_PlayerStats(SpawnerUID);
2815 end;
2817 plr := g_Player_Get(SpawnerUID);
2818 if plr = nil then
2819 s := '?'
2820 else
2821 s := plr.FName;
2823 case KillType of
2824 K_HARDKILL:
2825 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2826 [FName, s]),
2827 gShowKillMsg);
2828 K_EXTRAHARDKILL:
2829 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2830 [FName, s]),
2831 gShowKillMsg);
2832 else
2833 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2834 [FName, s]),
2835 gShowKillMsg);
2836 end;
2837 end
2838 else if g_GetUIDType(SpawnerUID) = UID_MONSTER then
2839 begin // Убит монстром
2840 mon := g_Monsters_ByUID(SpawnerUID);
2841 if mon = nil then
2842 s := '?'
2843 else
2844 s := g_Mons_GetKilledByTypeId(mon.MonsterType);
2846 case KillType of
2847 K_HARDKILL:
2848 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2849 [FName, s]),
2850 gShowKillMsg);
2851 K_EXTRAHARDKILL:
2852 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2853 [FName, s]),
2854 gShowKillMsg);
2855 else
2856 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2857 [FName, s]),
2858 gShowKillMsg);
2859 end;
2860 end
2861 else // Особые типы смерти
2862 case t of
2863 HIT_DISCON: ;
2864 HIT_SELF: g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2865 HIT_FALL: g_Console_Add(Format(_lc[I_PLAYER_KILL_FALL], [FName]), True);
2866 HIT_WATER: g_Console_Add(Format(_lc[I_PLAYER_KILL_WATER], [FName]), True);
2867 HIT_ACID: g_Console_Add(Format(_lc[I_PLAYER_KILL_ACID], [FName]), True);
2868 HIT_TRAP: g_Console_Add(Format(_lc[I_PLAYER_KILL_TRAP], [FName]), True);
2869 else g_Console_Add(Format(_lc[I_PLAYER_DIED], [FName]), True);
2870 end;
2872 if Srv then
2873 begin
2874 // Выброс оружия:
2875 for a := WP_FIRST to WP_LAST do
2876 if FWeapon[a] then
2877 begin
2878 case a of
2879 WEAPON_SAW: i := ITEM_WEAPON_SAW;
2880 WEAPON_SHOTGUN1: i := ITEM_WEAPON_SHOTGUN1;
2881 WEAPON_SHOTGUN2: i := ITEM_WEAPON_SHOTGUN2;
2882 WEAPON_CHAINGUN: i := ITEM_WEAPON_CHAINGUN;
2883 WEAPON_ROCKETLAUNCHER: i := ITEM_WEAPON_ROCKETLAUNCHER;
2884 WEAPON_PLASMA: i := ITEM_WEAPON_PLASMA;
2885 WEAPON_BFG: i := ITEM_WEAPON_BFG;
2886 WEAPON_SUPERPULEMET: i := ITEM_WEAPON_SUPERPULEMET;
2887 WEAPON_FLAMETHROWER: i := ITEM_WEAPON_FLAMETHROWER;
2888 else i := 0;
2889 end;
2891 if i <> 0 then
2892 PushItem(i);
2893 end;
2895 // Выброс рюкзака:
2896 if R_ITEM_BACKPACK in FRulez then
2897 PushItem(ITEM_AMMO_BACKPACK);
2899 // Выброс ракетного ранца:
2900 if FJetFuel > 0 then
2901 PushItem(ITEM_JETPACK);
2903 // Выброс ключей:
2904 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) or
2905 (not LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS)) then
2906 begin
2907 if R_KEY_RED in FRulez then
2908 PushItem(ITEM_KEY_RED);
2910 if R_KEY_GREEN in FRulez then
2911 PushItem(ITEM_KEY_GREEN);
2913 if R_KEY_BLUE in FRulez then
2914 PushItem(ITEM_KEY_BLUE);
2915 end;
2917 // Выброс флага:
2918 DropFlag(KillType = K_FALLKILL);
2919 end;
2921 FCorpse := g_Player_CreateCorpse(Self);
2923 if Srv and (gGameSettings.MaxLives > 0) and FNoRespawn and
2924 (gLMSRespawn = LMS_RESPAWN_NONE) then
2925 begin
2926 a := 0;
2927 k := 0;
2928 ar := 0;
2929 ab := 0;
2930 for i := Low(gPlayers) to High(gPlayers) do
2931 begin
2932 if gPlayers[i] = nil then continue;
2933 if (not gPlayers[i].FNoRespawn) and (not gPlayers[i].FSpectator) then
2934 begin
2935 Inc(a);
2936 if gPlayers[i].FTeam = TEAM_RED then Inc(ar)
2937 else if gPlayers[i].FTeam = TEAM_BLUE then Inc(ab);
2938 k := i;
2939 end;
2940 end;
2942 OldLR := gLMSRespawn;
2943 if (gGameSettings.GameMode = GM_COOP) then
2944 begin
2945 if (a = 0) then
2946 begin
2947 // everyone is dead, restart the map
2948 g_Game_Message(_lc[I_MESSAGE_LMS_LOSE], 144);
2949 if Netsrv then
2950 MH_SEND_GameEvent(NET_EV_LMS_LOSE);
2951 gLMSRespawn := LMS_RESPAWN_FINAL;
2952 gLMSRespawnTime := gTime + 5000;
2953 end
2954 else if (a = 1) then
2955 begin
2956 if (gPlayers[k] <> nil) and not (gPlayers[k] is TBot) then
2957 if (gPlayers[k] = gPlayer1) or
2958 (gPlayers[k] = gPlayer2) then
2959 g_Console_Add('*** ' + _lc[I_MESSAGE_LMS_SURVIVOR] + ' ***', True)
2960 else if Netsrv and (gPlayers[k].FClientID >= 0) then
2961 MH_SEND_GameEvent(NET_EV_LMS_SURVIVOR, 0, 'N', gPlayers[k].FClientID);
2962 end;
2963 end
2964 else if (gGameSettings.GameMode = GM_TDM) then
2965 begin
2966 if (ab = 0) and (ar <> 0) then
2967 begin
2968 // blu team ded
2969 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 144);
2970 if Netsrv then
2971 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_RED);
2972 Inc(gTeamStat[TEAM_RED].Score);
2973 gLMSRespawn := LMS_RESPAWN_FINAL;
2974 gLMSRespawnTime := gTime + 5000;
2975 end
2976 else if (ar = 0) and (ab <> 0) then
2977 begin
2978 // red team ded
2979 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 144);
2980 if Netsrv then
2981 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_BLUE);
2982 Inc(gTeamStat[TEAM_BLUE].Score);
2983 gLMSRespawn := LMS_RESPAWN_FINAL;
2984 gLMSRespawnTime := gTime + 5000;
2985 end
2986 else if (ar = 0) and (ab = 0) then
2987 begin
2988 // everyone ded
2989 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2990 if Netsrv then
2991 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2992 gLMSRespawn := LMS_RESPAWN_FINAL;
2993 gLMSRespawnTime := gTime + 5000;
2994 end;
2995 end
2996 else if (gGameSettings.GameMode = GM_DM) then
2997 begin
2998 if (a = 1) then
2999 begin
3000 if gPlayers[k] <> nil then
3001 with gPlayers[k] do
3002 begin
3003 // survivor is the winner
3004 g_Game_Message(Format(_lc[I_MESSAGE_LMS_WIN], [AnsiUpperCase(FName)]), 144);
3005 if Netsrv then
3006 MH_SEND_GameEvent(NET_EV_LMS_WIN, 0, FName);
3007 Inc(FFrags);
3008 end;
3009 gLMSRespawn := LMS_RESPAWN_FINAL;
3010 gLMSRespawnTime := gTime + 5000;
3011 end
3012 else if (a = 0) then
3013 begin
3014 // everyone is dead, restart the map
3015 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
3016 if Netsrv then
3017 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
3018 gLMSRespawn := LMS_RESPAWN_FINAL;
3019 gLMSRespawnTime := gTime + 5000;
3020 end;
3021 end;
3022 if srv and (OldLR = LMS_RESPAWN_NONE) and (gLMSRespawn > LMS_RESPAWN_NONE) then
3023 begin
3024 if NetMode = NET_SERVER then
3025 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime)
3026 else
3027 g_Console_Add(Format(_lc[I_MSG_WARMUP_START], [(gLMSRespawnTime - gTime) div 1000]), True);
3028 end;
3029 end;
3031 if Netsrv then
3032 begin
3033 MH_SEND_PlayerStats(FUID);
3034 MH_SEND_PlayerDeath(FUID, KillType, t, SpawnerUID);
3035 if gGameSettings.GameMode = GM_TDM then MH_SEND_GameStats;
3036 end;
3038 if srv and FNoRespawn then Spectate(True);
3039 FWantsInGame := True;
3040 end;
3042 function TPlayer.BodyInLiquid(XInc, YInc: Integer): Boolean;
3043 begin
3044 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3045 PLAYER_RECT.Height-20, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, False);
3046 end;
3048 function TPlayer.BodyInAcid(XInc, YInc: Integer): Boolean;
3049 begin
3050 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3051 PLAYER_RECT.Height-20, PANEL_ACID1 or PANEL_ACID2, False);
3052 end;
3054 procedure TPlayer.MakeBloodSimple(Count: Word);
3055 {$IFDEF ENABLE_GFX}
3056 var Blood: TModelBlood;
3057 {$ENDIF}
3058 begin
3059 {$IFDEF ENABLE_GFX}
3060 Blood := SELF.FModel.GetBlood();
3061 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)+8,
3062 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3063 Count div 2, 3, -1, 16, (PLAYER_RECT.Height*2 div 3),
3064 Blood.R, Blood.G, Blood.B, Blood.Kind);
3065 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-8,
3066 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3067 Count div 2, -3, -1, 16, (PLAYER_RECT.Height*2) div 3,
3068 Blood.R, Blood.G, Blood.B, Blood.Kind);
3069 {$ENDIF}
3070 end;
3072 procedure TPlayer.MakeBloodVector(Count: Word; VelX, VelY: Integer);
3073 {$IFDEF ENABLE_GFX}
3074 var Blood: TModelBlood;
3075 {$ENDIF}
3076 begin
3077 {$IFDEF ENABLE_GFX}
3078 Blood := SELF.FModel.GetBlood();
3079 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
3080 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3081 Count, VelX, VelY, 16, (PLAYER_RECT.Height*2) div 3,
3082 Blood.R, Blood.G, Blood.B, Blood.Kind);
3083 {$ENDIF}
3084 end;
3086 procedure TPlayer.ProcessWeaponAction(Action: Byte);
3087 begin
3088 if g_Game_IsClient then Exit;
3089 case Action of
3090 WP_PREV: PrevWeapon();
3091 WP_NEXT: NextWeapon();
3092 end;
3093 end;
3095 procedure TPlayer.QueueWeaponSwitch(Weapon: Byte);
3096 begin
3097 if g_Game_IsClient then Exit;
3098 if Weapon > High(FWeapon) then Exit;
3099 FNextWeap := FNextWeap or (1 shl Weapon);
3100 end;
3102 procedure TPlayer.resetWeaponQueue ();
3103 begin
3104 FNextWeap := 0;
3105 FNextWeapDelay := 0;
3106 end;
3108 function TPlayer.hasAmmoForWeapon (weapon: Byte): Boolean;
3109 begin
3110 result := false;
3111 case weapon of
3112 WEAPON_KASTET, WEAPON_SAW: result := true;
3113 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3114 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3115 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3116 WEAPON_PLASMA, WEAPON_BFG: result := (FAmmo[A_CELLS] > 0);
3117 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3118 else result := (weapon < length(FWeapon));
3119 end;
3120 end;
3122 function TPlayer.hasAmmoForShooting (weapon: Byte): Boolean;
3123 begin
3124 result := false;
3125 case weapon of
3126 WEAPON_KASTET, WEAPON_SAW: result := true;
3127 WEAPON_SHOTGUN1, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3128 WEAPON_SHOTGUN2: result := (FAmmo[A_SHELLS] > 1);
3129 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3130 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3131 WEAPON_PLASMA: result := (FAmmo[A_CELLS] > 0);
3132 WEAPON_BFG: result := (FAmmo[A_CELLS] >= 40);
3133 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3134 else result := (weapon < length(FWeapon));
3135 end;
3136 end;
3138 function TPlayer.shouldSwitch (weapon: Byte; hadWeapon: Boolean): Boolean;
3139 begin
3140 result := false;
3141 if (weapon > WP_LAST + 1) then
3142 begin
3143 result := false;
3144 exit;
3145 end;
3146 if (FWeapSwitchMode = 1) and not hadWeapon then
3147 result := true
3148 else if (FWeapSwitchMode = 2) then
3149 result := (FWeapPreferences[weapon] > FWeapPreferences[FCurrWeap]);
3150 end;
3152 // return 255 for "no switch"
3153 function TPlayer.getNextWeaponIndex (): Byte;
3154 var
3155 i: Word;
3156 wantThisWeapon: array[0..64] of Boolean;
3157 wwc: Integer = 0; //HACK!
3158 dir, cwi: Integer;
3159 begin
3160 result := 255; // default result: "no switch"
3161 //e_LogWriteFln('FSWITCHTOEMPTY: %s', [FSwitchToEmpty], TMsgType.Notify);
3162 // had weapon cycling on previous frame? remove that flag
3163 if (FNextWeap and $2000) <> 0 then
3164 begin
3165 FNextWeap := FNextWeap and $1FFF;
3166 FNextWeapDelay := 0;
3167 end;
3168 // cycling has priority
3169 if (FNextWeap and $C000) <> 0 then
3170 begin
3171 if (FNextWeap and $8000) <> 0 then
3172 dir := 1
3173 else
3174 dir := -1;
3175 FNextWeap := FNextWeap or $2000; // we need this
3176 if FNextWeapDelay > 0 then
3177 exit; // cooldown time
3178 cwi := FCurrWeap;
3179 for i := 0 to High(FWeapon) do
3180 begin
3181 cwi := (cwi+length(FWeapon)+dir) mod length(FWeapon);
3182 if FWeapon[cwi] and maySwitch(cwi) then
3183 begin
3184 //e_LogWriteFln(' SWITCH: cur=%d; new=%d %s %s', [FCurrWeap, cwi, FSwitchToEmpty, hasAmmoForWeapon(cwi)], TMsgType.Notify);
3185 result := Byte(cwi);
3186 FNextWeapDelay := WEAPON_DELAY;
3187 exit;
3188 end;
3189 end;
3190 resetWeaponQueue();
3191 exit;
3192 end;
3193 // no cycling
3194 for i := 0 to High(wantThisWeapon) do
3195 wantThisWeapon[i] := false;
3196 for i := 0 to High(FWeapon) do
3197 if (FNextWeap and (1 shl i)) <> 0 then
3198 begin
3199 wantThisWeapon[i] := true;
3200 Inc(wwc);
3201 end;
3203 // exclude currently selected weapon from the set
3204 wantThisWeapon[FCurrWeap] := false;
3205 // slow down alterations a little
3206 if wwc > 1 then
3207 begin
3208 //e_WriteLog(Format(' FNextWeap=%x; delay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3209 // more than one weapon requested, assume "alteration" and check alteration delay
3210 if FNextWeapDelay > 0 then
3211 begin
3212 FNextWeap := 0;
3213 exit;
3214 end; // yeah
3215 end;
3216 // do not reset weapon queue, it will be done in `RealizeCurrentWeapon()`
3217 // but clear all counters if no weapon should be switched
3218 if wwc < 1 then
3219 begin
3220 resetWeaponQueue();
3221 exit;
3222 end;
3223 //e_WriteLog(Format('wwc=%d', [wwc]), MSG_WARNING);
3224 // try weapons in descending order
3225 for i := High(FWeapon) downto 0 do
3226 begin
3227 if wantThisWeapon[i] and FWeapon[i] and ((wwc = 1) or hasAmmoForWeapon(i)) then
3228 begin
3229 // i found her!
3230 result := Byte(i);
3231 resetWeaponQueue();
3232 FNextWeapDelay := WEAPON_DELAY * 2; // anyway, 'cause why not
3233 //e_LogWriteFln('FOUND %s %s %s', [result, FSwitchToEmpty, hasAmmoForWeapon(i)], TMsgType.Notify);
3234 exit;
3235 end;
3236 end;
3237 // no suitable weapon found, so reset the queue, to avoid accidental "queuing" of weapon w/o ammo
3238 resetWeaponQueue();
3239 end;
3241 procedure TPlayer.RealizeCurrentWeapon();
3242 function switchAllowed (): Boolean;
3243 var
3244 i: Byte;
3245 begin
3246 result := false;
3247 if FBFGFireCounter <> -1 then
3248 exit;
3249 if FTime[T_SWITCH] > gTime then
3250 exit;
3251 for i := WP_FIRST to WP_LAST do
3252 if FReloading[i] > 0 then
3253 exit;
3254 result := true;
3255 end;
3257 var
3258 nw: Byte;
3259 begin
3260 //e_WriteLog(Format('***RealizeCurrentWeapon: FNextWeap=%x; FNextWeapDelay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3261 //FNextWeap := FNextWeap and $1FFF;
3262 if FNextWeapDelay > 0 then Dec(FNextWeapDelay); // "alteration delay"
3264 if not switchAllowed then
3265 begin
3266 //HACK for weapon cycling
3267 if (FNextWeap and $E000) <> 0 then FNextWeap := 0;
3268 exit;
3269 end;
3271 nw := getNextWeaponIndex();
3272 //
3273 if nw = 255 then exit; // don't reset anything here
3274 if nw > High(FWeapon) then
3275 begin
3276 // don't forget to reset queue here!
3277 //e_WriteLog(' RealizeCurrentWeapon: WUTAFUUUU', MSG_WARNING);
3278 resetWeaponQueue();
3279 exit;
3280 end;
3282 if FWeapon[nw] then
3283 begin
3284 FCurrWeap := nw;
3285 FTime[T_SWITCH] := gTime+156;
3286 if FCurrWeap = WEAPON_SAW then FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3287 FModel.SetWeapon(FCurrWeap);
3288 if g_Game_IsNet then MH_SEND_PlayerStats(FUID);
3289 end;
3290 end;
3292 procedure TPlayer.NextWeapon();
3293 begin
3294 if g_Game_IsClient then Exit;
3295 FNextWeap := $8000;
3296 end;
3298 procedure TPlayer.PrevWeapon();
3299 begin
3300 if g_Game_IsClient then Exit;
3301 FNextWeap := $4000;
3302 end;
3304 procedure TPlayer.SetWeapon(W: Byte);
3305 begin
3306 if FCurrWeap <> W then
3307 if W = WEAPON_SAW then
3308 FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3310 FCurrWeap := W;
3311 FModel.SetWeapon(CurrWeap);
3312 resetWeaponQueue();
3313 end;
3315 function TPlayer.PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean;
3316 var
3317 a: Boolean;
3318 switchWeapon: Byte = 255;
3319 hadWeapon: Boolean = False;
3320 begin
3321 Result := False;
3322 if g_Game_IsClient then Exit;
3324 // a = true - место спавна предмета:
3325 a := LongBool(gGameSettings.Options and GAME_OPTION_WEAPONSTAY) and arespawn;
3326 remove := not a;
3327 case ItemType of
3328 ITEM_MEDKIT_SMALL:
3329 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3330 begin
3331 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
3332 Result := True;
3333 remove := True;
3334 FFireTime := 0;
3335 if gFlash = 2 then Inc(FPickup, 5);
3336 end;
3338 ITEM_MEDKIT_LARGE:
3339 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3340 begin
3341 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
3342 Result := True;
3343 remove := True;
3344 FFireTime := 0;
3345 if gFlash = 2 then Inc(FPickup, 5);
3346 end;
3348 ITEM_ARMOR_GREEN:
3349 if FArmor < PLAYER_AP_SOFT then
3350 begin
3351 FArmor := PLAYER_AP_SOFT;
3352 Result := True;
3353 remove := True;
3354 if gFlash = 2 then Inc(FPickup, 5);
3355 end;
3357 ITEM_ARMOR_BLUE:
3358 if FArmor < PLAYER_AP_LIMIT then
3359 begin
3360 FArmor := PLAYER_AP_LIMIT;
3361 Result := True;
3362 remove := True;
3363 if gFlash = 2 then Inc(FPickup, 5);
3364 end;
3366 ITEM_SPHERE_BLUE:
3367 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3368 begin
3369 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
3370 Result := True;
3371 remove := True;
3372 FFireTime := 0;
3373 if gFlash = 2 then Inc(FPickup, 5);
3374 end;
3376 ITEM_SPHERE_WHITE:
3377 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) or (FFireTime > 0) then
3378 begin
3379 if FHealth < PLAYER_HP_LIMIT then
3380 FHealth := PLAYER_HP_LIMIT;
3381 if FArmor < PLAYER_AP_LIMIT then
3382 FArmor := PLAYER_AP_LIMIT;
3383 Result := True;
3384 remove := True;
3385 FFireTime := 0;
3386 if gFlash = 2 then Inc(FPickup, 5);
3387 end;
3389 ITEM_WEAPON_SAW:
3390 if (not FWeapon[WEAPON_SAW]) or ((not arespawn) and (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) then
3391 begin
3392 hadWeapon := FWeapon[WEAPON_SAW];
3393 switchWeapon := WEAPON_SAW;
3394 FWeapon[WEAPON_SAW] := True;
3395 Result := True;
3396 if gFlash = 2 then Inc(FPickup, 5);
3397 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3398 end;
3400 ITEM_WEAPON_SHOTGUN1:
3401 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN1] then
3402 begin
3403 // Нужно, чтобы не взять все пули сразу:
3404 if a and FWeapon[WEAPON_SHOTGUN1] then Exit;
3405 hadWeapon := FWeapon[WEAPON_SHOTGUN1];
3406 switchWeapon := WEAPON_SHOTGUN1;
3407 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3408 FWeapon[WEAPON_SHOTGUN1] := True;
3409 Result := True;
3410 if gFlash = 2 then Inc(FPickup, 5);
3411 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3412 end;
3414 ITEM_WEAPON_SHOTGUN2:
3415 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN2] then
3416 begin
3417 if a and FWeapon[WEAPON_SHOTGUN2] then Exit;
3418 hadWeapon := FWeapon[WEAPON_SHOTGUN2];
3419 switchWeapon := WEAPON_SHOTGUN2;
3420 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3421 FWeapon[WEAPON_SHOTGUN2] := True;
3422 Result := True;
3423 if gFlash = 2 then Inc(FPickup, 5);
3424 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3425 end;
3427 ITEM_WEAPON_CHAINGUN:
3428 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or not FWeapon[WEAPON_CHAINGUN] then
3429 begin
3430 if a and FWeapon[WEAPON_CHAINGUN] then Exit;
3431 hadWeapon := FWeapon[WEAPON_CHAINGUN];
3432 switchWeapon := WEAPON_CHAINGUN;
3433 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3434 FWeapon[WEAPON_CHAINGUN] := True;
3435 Result := True;
3436 if gFlash = 2 then Inc(FPickup, 5);
3437 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3438 end;
3440 ITEM_WEAPON_ROCKETLAUNCHER:
3441 if (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or not FWeapon[WEAPON_ROCKETLAUNCHER] then
3442 begin
3443 if a and FWeapon[WEAPON_ROCKETLAUNCHER] then Exit;
3444 switchWeapon := WEAPON_ROCKETLAUNCHER;
3445 hadWeapon := FWeapon[WEAPON_ROCKETLAUNCHER];
3446 IncMax(FAmmo[A_ROCKETS], 2, FMaxAmmo[A_ROCKETS]);
3447 FWeapon[WEAPON_ROCKETLAUNCHER] := True;
3448 Result := True;
3449 if gFlash = 2 then Inc(FPickup, 5);
3450 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3451 end;
3453 ITEM_WEAPON_PLASMA:
3454 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_PLASMA] then
3455 begin
3456 if a and FWeapon[WEAPON_PLASMA] then Exit;
3457 switchWeapon := WEAPON_PLASMA;
3458 hadWeapon := FWeapon[WEAPON_PLASMA];
3459 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3460 FWeapon[WEAPON_PLASMA] := True;
3461 Result := True;
3462 if gFlash = 2 then Inc(FPickup, 5);
3463 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3464 end;
3466 ITEM_WEAPON_BFG:
3467 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_BFG] then
3468 begin
3469 if a and FWeapon[WEAPON_BFG] then Exit;
3470 switchWeapon := WEAPON_BFG;
3471 hadWeapon := FWeapon[WEAPON_BFG];
3472 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3473 FWeapon[WEAPON_BFG] := True;
3474 Result := True;
3475 if gFlash = 2 then Inc(FPickup, 5);
3476 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3477 end;
3479 ITEM_WEAPON_SUPERPULEMET:
3480 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SUPERPULEMET] then
3481 begin
3482 if a and FWeapon[WEAPON_SUPERPULEMET] then Exit;
3483 switchWeapon := WEAPON_SUPERPULEMET;
3484 hadWeapon := FWeapon[WEAPON_SUPERPULEMET];
3485 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3486 FWeapon[WEAPON_SUPERPULEMET] := True;
3487 Result := True;
3488 if gFlash = 2 then Inc(FPickup, 5);
3489 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3490 end;
3492 ITEM_WEAPON_FLAMETHROWER:
3493 if (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) or not FWeapon[WEAPON_FLAMETHROWER] then
3494 begin
3495 if a and FWeapon[WEAPON_FLAMETHROWER] then Exit;
3496 switchWeapon := WEAPON_FLAMETHROWER;
3497 hadWeapon := FWeapon[WEAPON_FLAMETHROWER];
3498 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3499 FWeapon[WEAPON_FLAMETHROWER] := True;
3500 Result := True;
3501 if gFlash = 2 then Inc(FPickup, 5);
3502 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3503 end;
3505 ITEM_AMMO_BULLETS:
3506 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3507 begin
3508 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3509 Result := True;
3510 remove := True;
3511 if gFlash = 2 then Inc(FPickup, 5);
3512 end;
3514 ITEM_AMMO_BULLETS_BOX:
3515 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3516 begin
3517 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3518 Result := True;
3519 remove := True;
3520 if gFlash = 2 then Inc(FPickup, 5);
3521 end;
3523 ITEM_AMMO_SHELLS:
3524 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3525 begin
3526 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3527 Result := True;
3528 remove := True;
3529 if gFlash = 2 then Inc(FPickup, 5);
3530 end;
3532 ITEM_AMMO_SHELLS_BOX:
3533 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3534 begin
3535 IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
3536 Result := True;
3537 remove := True;
3538 if gFlash = 2 then Inc(FPickup, 5);
3539 end;
3541 ITEM_AMMO_ROCKET:
3542 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3543 begin
3544 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3545 Result := True;
3546 remove := True;
3547 if gFlash = 2 then Inc(FPickup, 5);
3548 end;
3550 ITEM_AMMO_ROCKET_BOX:
3551 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3552 begin
3553 IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
3554 Result := True;
3555 remove := True;
3556 if gFlash = 2 then Inc(FPickup, 5);
3557 end;
3559 ITEM_AMMO_CELL:
3560 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3561 begin
3562 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3563 Result := True;
3564 remove := True;
3565 if gFlash = 2 then Inc(FPickup, 5);
3566 end;
3568 ITEM_AMMO_CELL_BIG:
3569 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3570 begin
3571 IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
3572 Result := True;
3573 remove := True;
3574 if gFlash = 2 then Inc(FPickup, 5);
3575 end;
3577 ITEM_AMMO_FUELCAN:
3578 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3579 begin
3580 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3581 Result := True;
3582 remove := True;
3583 if gFlash = 2 then Inc(FPickup, 5);
3584 end;
3586 ITEM_AMMO_BACKPACK:
3587 if not(R_ITEM_BACKPACK in FRulez) or
3588 (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
3589 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
3590 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
3591 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
3592 (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) then
3593 begin
3594 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
3595 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
3596 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
3597 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
3598 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
3600 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3601 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3602 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3603 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3604 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3605 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3606 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3607 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3608 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3609 IncMax(FAmmo[A_FUEL], 50, FMaxAmmo[A_FUEL]);
3611 FRulez := FRulez + [R_ITEM_BACKPACK];
3612 Result := True;
3613 remove := True;
3614 if gFlash = 2 then Inc(FPickup, 5);
3615 end;
3617 ITEM_KEY_RED:
3618 if not(R_KEY_RED in FRulez) then
3619 begin
3620 Include(FRulez, R_KEY_RED);
3621 Result := True;
3622 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3623 if gFlash = 2 then Inc(FPickup, 5);
3624 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3625 end;
3627 ITEM_KEY_GREEN:
3628 if not(R_KEY_GREEN in FRulez) then
3629 begin
3630 Include(FRulez, R_KEY_GREEN);
3631 Result := True;
3632 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3633 if gFlash = 2 then Inc(FPickup, 5);
3634 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3635 end;
3637 ITEM_KEY_BLUE:
3638 if not(R_KEY_BLUE in FRulez) then
3639 begin
3640 Include(FRulez, R_KEY_BLUE);
3641 Result := True;
3642 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3643 if gFlash = 2 then Inc(FPickup, 5);
3644 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3645 end;
3647 ITEM_SUIT:
3648 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
3649 begin
3650 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
3651 Result := True;
3652 remove := True;
3653 FFireTime := 0;
3654 if gFlash = 2 then Inc(FPickup, 5);
3655 end;
3657 ITEM_OXYGEN:
3658 if FAir < AIR_MAX then
3659 begin
3660 FAir := AIR_MAX;
3661 Result := True;
3662 remove := True;
3663 if gFlash = 2 then Inc(FPickup, 5);
3664 end;
3666 ITEM_MEDKIT_BLACK:
3667 begin
3668 if not (R_BERSERK in FRulez) then
3669 begin
3670 Include(FRulez, R_BERSERK);
3671 if (FBFGFireCounter = -1) then
3672 begin
3673 FCurrWeap := WEAPON_KASTET;
3674 resetWeaponQueue();
3675 FModel.SetWeapon(WEAPON_KASTET);
3676 end;
3677 if gFlash <> 0 then
3678 begin
3679 Inc(FPain, 100);
3680 if gFlash = 2 then Inc(FPickup, 5);
3681 end;
3682 FBerserk := gTime+30000;
3683 Result := True;
3684 remove := True;
3685 FFireTime := 0;
3686 end;
3687 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3688 begin
3689 if FHealth < PLAYER_HP_SOFT then FHealth := PLAYER_HP_SOFT;
3690 FBerserk := gTime+30000;
3691 Result := True;
3692 remove := True;
3693 FFireTime := 0;
3694 end;
3695 end;
3697 ITEM_INVUL:
3698 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
3699 begin
3700 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
3701 FSpawnInvul := 0;
3702 Result := True;
3703 remove := True;
3704 if gFlash = 2 then Inc(FPickup, 5);
3705 end;
3707 ITEM_BOTTLE:
3708 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3709 begin
3710 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
3711 Result := True;
3712 remove := True;
3713 FFireTime := 0;
3714 if gFlash = 2 then Inc(FPickup, 5);
3715 end;
3717 ITEM_HELMET:
3718 if FArmor < PLAYER_AP_LIMIT then
3719 begin
3720 IncMax(FArmor, 5, PLAYER_AP_LIMIT);
3721 Result := True;
3722 remove := True;
3723 if gFlash = 2 then Inc(FPickup, 5);
3724 end;
3726 ITEM_JETPACK:
3727 if FJetFuel < JET_MAX then
3728 begin
3729 FJetFuel := JET_MAX;
3730 Result := True;
3731 remove := True;
3732 if gFlash = 2 then Inc(FPickup, 5);
3733 end;
3735 ITEM_INVIS:
3736 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
3737 begin
3738 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
3739 Result := True;
3740 remove := True;
3741 if gFlash = 2 then Inc(FPickup, 5);
3742 end;
3743 end;
3745 if (shouldSwitch(switchWeapon, hadWeapon)) then
3746 QueueWeaponSwitch(switchWeapon);
3747 end;
3749 procedure TPlayer.Touch();
3750 begin
3751 if not FAlive then
3752 Exit;
3753 //FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
3754 if FIamBot then
3755 begin
3756 // Бросить флаг товарищу:
3757 if gGameSettings.GameMode = GM_CTF then
3758 DropFlag();
3759 end;
3760 end;
3762 procedure TPlayer.Push(vx, vy: Integer);
3763 begin
3764 if (not FPhysics) and FGhost then
3765 Exit;
3766 FObj.Accel.X := FObj.Accel.X + vx;
3767 FObj.Accel.Y := FObj.Accel.Y + vy;
3768 if g_Game_IsNet and g_Game_IsServer then
3769 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3770 end;
3772 procedure TPlayer.Reset(Force: Boolean);
3773 begin
3774 if Force then
3775 FAlive := False;
3777 FSpawned := False;
3778 FTime[T_RESPAWN] := 0;
3779 FTime[T_FLAGCAP] := 0;
3780 FGodMode := False;
3781 FNoTarget := False;
3782 FNoReload := False;
3783 FFrags := 0;
3784 FLastFrag := 0;
3785 FComboEvnt := -1;
3786 FKills := 0;
3787 FMonsterKills := 0;
3788 FDeath := 0;
3789 FSecrets := 0;
3790 FSpawnInvul := 0;
3791 FCorpse := -1;
3792 FReady := False;
3793 if FNoRespawn then
3794 begin
3795 FSpectator := False;
3796 FGhost := False;
3797 FPhysics := True;
3798 FSpectatePlayer := -1;
3799 FNoRespawn := False;
3800 end;
3801 FLives := gGameSettings.MaxLives;
3803 SetFlag(FLAG_NONE);
3804 end;
3806 procedure TPlayer.SoftReset();
3807 begin
3808 ReleaseKeys();
3810 FDamageBuffer := 0;
3811 FSlopeOld := 0;
3812 FIncCamOld := 0;
3813 FIncCam := 0;
3814 FBFGFireCounter := -1;
3815 FShellTimer := -1;
3816 FPain := 0;
3817 FLastHit := 0;
3818 FLastFrag := 0;
3819 FComboEvnt := -1;
3821 SetFlag(FLAG_NONE);
3822 SetAction(A_STAND, True);
3823 end;
3825 function TPlayer.GetRespawnPoint(): Byte;
3826 var
3827 c: Byte;
3828 begin
3829 Result := 255;
3830 // На будущее: FSpawn - игрок уже играл и перерождается
3832 // Одиночная игра/кооператив
3833 if gGameSettings.GameMode in [GM_COOP, GM_SINGLE] then
3834 begin
3835 if Self = gPlayer1 then
3836 begin
3837 // player 1 should try to spawn on the player 1 point
3838 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3839 Exit(RESPAWNPOINT_PLAYER1)
3840 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3841 Exit(RESPAWNPOINT_PLAYER2);
3842 end
3843 else if Self = gPlayer2 then
3844 begin
3845 // player 2 should try to spawn on the player 2 point
3846 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3847 Exit(RESPAWNPOINT_PLAYER2)
3848 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3849 Exit(RESPAWNPOINT_PLAYER1);
3850 end
3851 else
3852 begin
3853 // other players randomly pick either the first or the second point
3854 c := IfThen((Random(2) = 0), RESPAWNPOINT_PLAYER1, RESPAWNPOINT_PLAYER2);
3855 if g_Map_GetPointCount(c) > 0 then
3856 Exit(c);
3857 // try the other one
3858 c := IfThen((c = RESPAWNPOINT_PLAYER1), RESPAWNPOINT_PLAYER2, RESPAWNPOINT_PLAYER1);
3859 if g_Map_GetPointCount(c) > 0 then
3860 Exit(c);
3861 end;
3862 end;
3864 // Мясоповал
3865 if gGameSettings.GameMode = GM_DM then
3866 begin
3867 // try DM points first
3868 if g_Map_GetPointCount(RESPAWNPOINT_DM) > 0 then
3869 Exit(RESPAWNPOINT_DM);
3870 end;
3872 // Командные
3873 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3874 begin
3875 // try team points first
3876 c := RESPAWNPOINT_DM;
3877 if FTeam = TEAM_RED then
3878 c := RESPAWNPOINT_RED
3879 else if FTeam = TEAM_BLUE then
3880 c := RESPAWNPOINT_BLUE;
3881 if g_Map_GetPointCount(c) > 0 then
3882 Exit(c);
3883 end;
3885 // still haven't found a spawnpoint, try random shit
3886 Result := g_Map_GetRandomPointType();
3887 end;
3889 procedure TPlayer.Respawn(Silent: Boolean; Force: Boolean = False);
3890 var
3891 RespawnPoint: TRespawnPoint;
3892 a, b, c: Byte;
3893 begin
3894 FSlopeOld := 0;
3895 FIncCamOld := 0;
3896 FIncCam := 0;
3897 FBFGFireCounter := -1;
3898 FShellTimer := -1;
3899 FPain := 0;
3900 FLastHit := 0;
3901 FSpawnInvul := 0;
3902 FCorpse := -1;
3904 if not g_Game_IsServer then
3905 Exit;
3906 if FDummy then
3907 Exit;
3908 FWantsInGame := True;
3909 FJustTeleported := True;
3910 if Force then
3911 begin
3912 FTime[T_RESPAWN] := 0;
3913 FAlive := False;
3914 end;
3915 FNetTime := 0;
3916 // if server changes MaxLives we gotta be ready
3917 if gGameSettings.MaxLives = 0 then FNoRespawn := False;
3919 // Еще нельзя возродиться:
3920 if FTime[T_RESPAWN] > gTime then
3921 Exit;
3923 // Просрал все жизни:
3924 if FNoRespawn then
3925 begin
3926 if not FSpectator then Spectate(True);
3927 FWantsInGame := True;
3928 Exit;
3929 end;
3931 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.GameMode <> GM_COOP) then
3932 begin // "Своя игра"
3933 // Берсерк не сохраняется между уровнями:
3934 FRulez := FRulez-[R_BERSERK];
3935 end
3936 else // "Одиночная игра"/"Кооп"
3937 begin
3938 // Берсерк и ключи не сохраняются между уровнями:
3939 FRulez := FRulez-[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE, R_BERSERK];
3940 end;
3942 // Получаем точку спауна игрока:
3943 c := GetRespawnPoint();
3945 ReleaseKeys();
3946 SetFlag(FLAG_NONE);
3948 // Воскрешение без оружия:
3949 if not FAlive then
3950 begin
3951 FHealth := Round(PLAYER_HP_SOFT * (FHandicap / 100));
3952 FArmor := 0;
3953 FAlive := True;
3954 FAir := AIR_DEF;
3955 FJetFuel := 0;
3957 for a := WP_FIRST to WP_LAST do
3958 begin
3959 FWeapon[a] := False;
3960 FReloading[a] := 0;
3961 end;
3963 FWeapon[WEAPON_PISTOL] := True;
3964 FWeapon[WEAPON_KASTET] := True;
3965 FCurrWeap := WEAPON_PISTOL;
3966 resetWeaponQueue();
3968 FModel.SetWeapon(FCurrWeap);
3970 for b := A_BULLETS to A_HIGH do
3971 FAmmo[b] := 0;
3973 FAmmo[A_BULLETS] := 50;
3975 FMaxAmmo[A_BULLETS] := AmmoLimits[0, A_BULLETS];
3976 FMaxAmmo[A_SHELLS] := AmmoLimits[0, A_SHELLS];
3977 FMaxAmmo[A_ROCKETS] := AmmoLimits[0, A_SHELLS];
3978 FMaxAmmo[A_CELLS] := AmmoLimits[0, A_CELLS];
3979 FMaxAmmo[A_FUEL] := AmmoLimits[0, A_FUEL];
3981 if (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) and
3982 LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS) then
3983 FRulez := [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE]
3984 else
3985 FRulez := [];
3986 end;
3988 // Получаем координаты точки возрождения:
3989 if not g_Map_GetPoint(c, RespawnPoint) then
3990 begin
3991 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3992 Exit;
3993 end;
3995 // Установка координат и сброс всех параметров:
3996 FObj.X := RespawnPoint.X-PLAYER_RECT.X;
3997 FObj.Y := RespawnPoint.Y-PLAYER_RECT.Y;
3998 FObj.oldX := FObj.X; // don't interpolate after respawn
3999 FObj.oldY := FObj.Y;
4000 FObj.Vel.X := 0;
4001 FObj.Vel.Y := 0;
4002 FObj.Accel.X := 0;
4003 FObj.Accel.Y := 0;
4005 FDirection := RespawnPoint.Direction;
4006 if FDirection = TDirection.D_LEFT then
4007 FAngle := 180
4008 else
4009 FAngle := 0;
4011 SetAction(A_STAND, True);
4012 FModel.Direction := FDirection;
4014 for a := Low(FTime) to High(FTime) do
4015 FTime[a] := 0;
4017 for a := Low(FMegaRulez) to High(FMegaRulez) do
4018 FMegaRulez[a] := 0;
4020 // Respawn invulnerability
4021 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.SpawnInvul > 0) then
4022 begin
4023 FMegaRulez[MR_INVUL] := gTime + gGameSettings.SpawnInvul * 1000;
4024 FSpawnInvul := FMegaRulez[MR_INVUL];
4025 end;
4027 FDamageBuffer := 0;
4028 FJetpack := False;
4029 FCanJetpack := False;
4030 FFlaming := False;
4031 FFireTime := 0;
4032 FFirePainTime := 0;
4033 FFireAttacker := 0;
4035 {$IFDEF ENABLE_GFX}
4036 // Анимация возрождения:
4037 if (not gLoadGameMode) and (not Silent) then
4038 begin
4039 g_GFX_QueueEffect(
4040 R_GFX_TELEPORT_FAST,
4041 FObj.X + PLAYER_RECT.X + (PLAYER_RECT.Width div 2) - 32,
4042 FObj.Y + PLAYER_RECT.Y + (PLAYER_RECT.Height div 2) - 32
4043 );
4044 end;
4045 {$ENDIF}
4047 FSpectator := False;
4048 FGhost := False;
4049 FPhysics := True;
4050 FSpectatePlayer := -1;
4051 FSpawned := True;
4053 if (gPlayer1 = nil) and (gSpectLatchPID1 = FUID) then
4054 gPlayer1 := self;
4055 if (gPlayer2 = nil) and (gSpectLatchPID2 = FUID) then
4056 gPlayer2 := self;
4058 if g_Game_IsNet then
4059 begin
4060 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
4061 MH_SEND_PlayerStats(FUID, NET_EVERYONE);
4062 if not Silent then
4063 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4064 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32,
4065 0, NET_GFX_TELE);
4066 end;
4067 end;
4069 procedure TPlayer.Spectate(NoMove: Boolean = False);
4070 begin
4071 if FAlive then
4072 Kill(K_EXTRAHARDKILL, FUID, HIT_SOME)
4073 else if (not NoMove) then
4074 begin
4075 GameX := gMapInfo.Width div 2;
4076 GameY := gMapInfo.Height div 2;
4077 end;
4078 FXTo := GameX;
4079 FYTo := GameY;
4081 FAlive := False;
4082 FSpectator := True;
4083 FGhost := True;
4084 FPhysics := False;
4085 FWantsInGame := False;
4086 FSpawned := False;
4087 FCorpse := -1;
4089 if FNoRespawn then
4090 begin
4091 if Self = gPlayer1 then
4092 begin
4093 gSpectLatchPID1 := FUID;
4094 gPlayer1 := nil;
4095 end
4096 else if Self = gPlayer2 then
4097 begin
4098 gSpectLatchPID2 := FUID;
4099 gPlayer2 := nil;
4100 end;
4101 end;
4103 if g_Game_IsNet then
4104 MH_SEND_PlayerStats(FUID);
4105 end;
4107 procedure TPlayer.SwitchNoClip;
4108 begin
4109 if not FAlive then
4110 Exit;
4111 FGhost := not FGhost;
4112 FPhysics := not FGhost;
4113 if FGhost then
4114 begin
4115 FXTo := FObj.X;
4116 FYTo := FObj.Y;
4117 end else
4118 begin
4119 FObj.Accel.X := 0;
4120 FObj.Accel.Y := 0;
4121 end;
4122 end;
4124 procedure TPlayer.Run(Direction: TDirection);
4125 var
4126 a, b: Integer;
4127 begin
4128 if MAX_RUNVEL > 8 then
4129 FlySmoke();
4131 // Бежим:
4132 if Direction = TDirection.D_LEFT then
4133 begin
4134 if FObj.Vel.X > -MAX_RUNVEL then
4135 FObj.Vel.X := FObj.Vel.X - (MAX_RUNVEL shr 3);
4136 end
4137 else
4138 if FObj.Vel.X < MAX_RUNVEL then
4139 FObj.Vel.X := FObj.Vel.X + (MAX_RUNVEL shr 3);
4141 // Возможно, пинаем куски:
4142 if (FObj.Vel.X <> 0) and (gGibs <> nil) then
4143 begin
4144 b := Abs(FObj.Vel.X);
4145 if b > 1 then b := b * (Random(8 div b) + 1);
4146 for a := 0 to High(gGibs) do
4147 begin
4148 if gGibs[a].alive and
4149 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
4150 FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
4151 begin
4152 // Пинаем куски
4153 if FObj.Vel.X < 0 then
4154 begin
4155 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)+120) // налево
4156 end
4157 else
4158 begin
4159 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)); // направо
4160 end;
4161 gGibs[a].positionChanged(); // this updates spatial accelerators
4162 end;
4163 end;
4164 end;
4166 SetAction(A_WALK);
4167 end;
4169 procedure TPlayer.SeeDown();
4170 begin
4171 SetAction(A_SEEDOWN);
4173 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTDOWN else FAngle := ANGLE_RIGHTDOWN;
4175 if FIncCam > -120 then DecMin(FIncCam, 5, -120);
4176 end;
4178 procedure TPlayer.SeeUp();
4179 begin
4180 SetAction(A_SEEUP);
4182 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTUP else FAngle := ANGLE_RIGHTUP;
4184 if FIncCam < 120 then IncMax(FIncCam, 5, 120);
4185 end;
4187 procedure TPlayer.SetAction(Action: Byte; Force: Boolean = False);
4188 var
4189 Prior: Byte;
4190 begin
4191 case Action of
4192 A_WALK: Prior := 3;
4193 A_DIE1: Prior := 5;
4194 A_DIE2: Prior := 5;
4195 A_ATTACK: Prior := 2;
4196 A_SEEUP: Prior := 1;
4197 A_SEEDOWN: Prior := 1;
4198 A_ATTACKUP: Prior := 2;
4199 A_ATTACKDOWN: Prior := 2;
4200 A_PAIN: Prior := 4;
4201 else Prior := 0;
4202 end;
4204 if (Prior > FActionPrior) or Force then
4205 if not ((Prior = 2) and (FCurrWeap = WEAPON_SAW)) then
4206 begin
4207 FActionPrior := Prior;
4208 FActionAnim := Action;
4209 FActionForce := Force;
4210 FActionChanged := True;
4211 end;
4213 if Action in [A_ATTACK, A_ATTACKUP, A_ATTACKDOWN] then FModel.SetFire(True);
4214 end;
4216 function TPlayer.StayOnStep(XInc, YInc: Integer): Boolean;
4217 begin
4218 Result := not g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height-1,
4219 PLAYER_RECT.Width, 1, PANEL_STEP, False)
4220 and g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height,
4221 PLAYER_RECT.Width, 1, PANEL_STEP, False);
4222 end;
4224 function TPlayer.TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
4225 begin
4226 Result := False;
4228 if g_CollideLevel(X, Y, PLAYER_RECT.Width, PLAYER_RECT.Height) then
4229 begin
4230 g_Sound_PlayExAt('SOUND_GAME_NOTELEPORT', FObj.X, FObj.Y);
4231 if g_Game_IsServer and g_Game_IsNet then
4232 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_GAME_NOTELEPORT');
4233 Exit;
4234 end;
4236 FJustTeleported := True;
4238 if not silent then
4239 begin
4240 g_Sound_PlayExAt('SOUND_GAME_TELEPORT', FObj.X, FObj.Y);
4241 {$IFDEF ENABLE_GFX}
4242 g_GFX_QueueEffect(
4243 R_GFX_TELEPORT_FAST,
4244 FObj.X + PLAYER_RECT.X + (PLAYER_RECT.Width div 2) - 32,
4245 FObj.Y + PLAYER_RECT.Y + (PLAYER_RECT.Height div 2) - 32
4246 );
4247 {$ENDIF}
4248 if g_Game_IsServer and g_Game_IsNet then
4249 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4250 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 1,
4251 NET_GFX_TELE);
4252 end;
4254 FObj.X := X-PLAYER_RECT.X;
4255 FObj.Y := Y-PLAYER_RECT.Y;
4256 FObj.oldX := FObj.X; // don't interpolate after respawn
4257 FObj.oldY := FObj.Y;
4258 if FAlive and FGhost then
4259 begin
4260 FXTo := FObj.X;
4261 FYTo := FObj.Y;
4262 end;
4264 if not g_Game_IsNet then
4265 begin
4266 if dir = 1 then
4267 begin
4268 SetDirection(TDirection.D_LEFT);
4269 FAngle := 180;
4270 end
4271 else
4272 if dir = 2 then
4273 begin
4274 SetDirection(TDirection.D_RIGHT);
4275 FAngle := 0;
4276 end
4277 else
4278 if dir = 3 then
4279 begin // обратное
4280 if FDirection = TDirection.D_RIGHT then
4281 begin
4282 SetDirection(TDirection.D_LEFT);
4283 FAngle := 180;
4284 end
4285 else
4286 begin
4287 SetDirection(TDirection.D_RIGHT);
4288 FAngle := 0;
4289 end;
4290 end;
4291 end;
4293 if not silent then
4294 begin
4295 {$IFDEF ENABLE_GFX}
4296 g_GFX_QueueEffect(
4297 R_GFX_TELEPORT_FAST,
4298 FObj.X + PLAYER_RECT.X + (PLAYER_RECT.Width div 2) - 32,
4299 FObj.Y + PLAYER_RECT.Y + (PLAYER_RECT.Height div 2) - 32
4300 );
4301 {$ENDIF}
4302 if g_Game_IsServer and g_Game_IsNet then
4303 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4304 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 0,
4305 NET_GFX_TELE);
4306 end;
4308 Result := True;
4309 end;
4311 function nonz(a: Single): Single;
4312 begin
4313 if a <> 0 then
4314 Result := a
4315 else
4316 Result := 1;
4317 end;
4319 function TPlayer.refreshCorpse(): Boolean;
4320 var
4321 i: Integer;
4322 begin
4323 Result := False;
4324 FCorpse := -1;
4325 if FAlive or FSpectator then
4326 Exit;
4327 if (gCorpses = nil) or (Length(gCorpses) = 0) then
4328 Exit;
4329 for i := 0 to High(gCorpses) do
4330 if gCorpses[i] <> nil then
4331 if gCorpses[i].FPlayerUID = FUID then
4332 begin
4333 Result := True;
4334 FCorpse := i;
4335 break;
4336 end;
4337 end;
4339 function TPlayer.getCameraObj(): TObj;
4340 begin
4341 if (not FAlive) and (not FSpectator) and
4342 (FCorpse >= 0) and (FCorpse < Length(gCorpses)) and
4343 (gCorpses[FCorpse] <> nil) and (gCorpses[FCorpse].FPlayerUID = FUID) then
4344 begin
4345 gCorpses[FCorpse].FObj.slopeUpLeft := FObj.slopeUpLeft;
4346 Result := gCorpses[FCorpse].FObj;
4347 end
4348 else
4349 begin
4350 Result := FObj;
4351 end;
4352 end;
4354 procedure TPlayer.PreUpdate();
4355 begin
4356 FSlopeOld := FObj.slopeUpLeft;
4357 FIncCamOld := FIncCam;
4358 FObj.oldX := FObj.X;
4359 FObj.oldY := FObj.Y;
4360 end;
4362 procedure TPlayer.Update();
4363 var
4364 b: Byte;
4365 i, ii, wx, wy, xd, yd, k: Integer;
4366 blockmon, headwater, dospawn: Boolean;
4367 NetServer: Boolean;
4368 AnyServer: Boolean;
4369 SetSpect: Boolean;
4370 begin
4371 NetServer := g_Game_IsNet and g_Game_IsServer;
4372 AnyServer := g_Game_IsServer;
4374 if g_Game_IsClient and (NetInterpLevel > 0) then
4375 DoLerp(NetInterpLevel + 1)
4376 else
4377 if FGhost then
4378 DoLerp(4);
4380 if NetServer then
4381 if (FClientID >= 0) and (NetClients[FClientID].Peer <> nil) then
4382 begin
4383 FPing := NetClients[FClientID].Peer^.lastRoundTripTime;
4384 if NetClients[FClientID].Peer^.packetsSent > 0 then
4385 FLoss := Round(100*NetClients[FClientID].Peer^.packetsLost/NetClients[FClientID].Peer^.packetsSent)
4386 else
4387 FLoss := 0;
4388 end else
4389 begin
4390 FPing := 0;
4391 FLoss := 0;
4392 end;
4394 if FAlive then
4395 FPunchAnim.Update;
4396 if FPunchAnim.played then
4397 FPunchAnim.Disable;
4399 if FAlive and (gFly or FJetpack) then
4400 FlySmoke();
4402 if FDirection = TDirection.D_LEFT then
4403 FAngle := 180
4404 else
4405 FAngle := 0;
4407 if FAlive and (not FGhost) then
4408 begin
4409 if FKeys[KEY_UP].Pressed then
4410 SeeUp();
4411 if FKeys[KEY_DOWN].Pressed then
4412 SeeDown();
4413 end;
4415 if (not (FKeys[KEY_UP].Pressed or FKeys[KEY_DOWN].Pressed)) and
4416 (FIncCam <> 0) then
4417 begin
4418 i := g_basic.Sign(FIncCam);
4419 FIncCam := Abs(FIncCam);
4420 DecMin(FIncCam, 5, 0);
4421 FIncCam := FIncCam*i;
4422 end;
4424 if gTime mod (GAME_TICK*2) <> 0 then
4425 begin
4426 if (FObj.Vel.X = 0) and FAlive then
4427 begin
4428 if FKeys[KEY_LEFT].Pressed then
4429 Run(TDirection.D_LEFT);
4430 if FKeys[KEY_RIGHT].Pressed then
4431 Run(TDirection.D_RIGHT);
4432 end;
4434 if FPhysics then
4435 begin
4436 g_Obj_Move(@FObj, True, True, True);
4437 positionChanged(); // this updates spatial accelerators
4438 end;
4440 Exit;
4441 end;
4443 FActionChanged := False;
4445 if FAlive then
4446 begin
4447 // Let alive player do some actions
4448 if FKeys[KEY_LEFT].Pressed then Run(TDirection.D_LEFT);
4449 if FKeys[KEY_RIGHT].Pressed then Run(TDirection.D_RIGHT);
4450 if FKeys[KEY_FIRE].Pressed and AnyServer then Fire()
4451 else
4452 begin
4453 if AnyServer then
4454 begin
4455 FlamerOff;
4456 if NetServer then MH_SEND_PlayerStats(FUID);
4457 end;
4458 end;
4459 if FKeys[KEY_OPEN].Pressed and AnyServer then Use();
4460 if FKeys[KEY_JUMP].Pressed then Jump()
4461 else
4462 begin
4463 if AnyServer and FJetpack then
4464 begin
4465 FJetpack := False;
4466 JetpackOff;
4467 if NetServer then MH_SEND_PlayerStats(FUID);
4468 end;
4469 FCanJetpack := True;
4470 end;
4471 end
4472 else // Dead
4473 begin
4474 dospawn := False;
4475 if not FGhost then
4476 for k := Low(FKeys) to KEY_CHAT-1 do
4477 begin
4478 if FKeys[k].Pressed then
4479 begin
4480 dospawn := True;
4481 break;
4482 end;
4483 end;
4484 if dospawn then
4485 begin
4486 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
4487 Respawn(False)
4488 else // Single
4489 if (FTime[T_RESPAWN] <= gTime) and
4490 gGameOn and (not FAlive) then
4491 begin
4492 if (g_Player_GetCount() > 1) then
4493 Respawn(False)
4494 else
4495 begin
4496 gExit := EXIT_RESTART;
4497 Exit;
4498 end;
4499 end;
4500 end;
4501 // Dead spectator actions
4502 if FGhost then
4503 begin
4504 if FKeys[KEY_OPEN].Pressed and AnyServer then Fire();
4505 if FKeys[KEY_FIRE].Pressed and AnyServer then
4506 begin
4507 if FSpectator then
4508 begin
4509 if (FSpectatePlayer >= High(gPlayers)) then
4510 FSpectatePlayer := -1
4511 else
4512 begin
4513 SetSpect := False;
4514 for I := FSpectatePlayer + 1 to High(gPlayers) do
4515 if gPlayers[I] <> nil then
4516 if gPlayers[I].alive then
4517 if gPlayers[I].UID <> FUID then
4518 begin
4519 FSpectatePlayer := I;
4520 SetSpect := True;
4521 break;
4522 end;
4524 if not SetSpect then FSpectatePlayer := -1;
4525 end;
4527 ReleaseKeys;
4528 end;
4529 end;
4530 end;
4531 end;
4532 // No clipping
4533 if FGhost then
4534 begin
4535 if FKeys[KEY_UP].Pressed or FKeys[KEY_JUMP].Pressed then
4536 begin
4537 FYTo := FObj.Y - 32;
4538 FSpectatePlayer := -1;
4539 end;
4540 if FKeys[KEY_DOWN].Pressed then
4541 begin
4542 FYTo := FObj.Y + 32;
4543 FSpectatePlayer := -1;
4544 end;
4545 if FKeys[KEY_LEFT].Pressed then
4546 begin
4547 FXTo := FObj.X - 32;
4548 FSpectatePlayer := -1;
4549 end;
4550 if FKeys[KEY_RIGHT].Pressed then
4551 begin
4552 FXTo := FObj.X + 32;
4553 FSpectatePlayer := -1;
4554 end;
4556 if (FXTo < -64) then
4557 FXTo := -64
4558 else if (FXTo > gMapInfo.Width + 32) then
4559 FXTo := gMapInfo.Width + 32;
4560 if (FYTo < -72) then
4561 FYTo := -72
4562 else if (FYTo > gMapInfo.Height + 32) then
4563 FYTo := gMapInfo.Height + 32;
4564 end;
4566 if FPhysics then
4567 begin
4568 g_Obj_Move(@FObj, True, True, True);
4569 positionChanged(); // this updates spatial accelerators
4570 end
4571 else
4572 begin
4573 FObj.Vel.X := 0;
4574 FObj.Vel.Y := 0;
4575 if FSpectator then
4576 if (FSpectatePlayer <= High(gPlayers)) and (FSpectatePlayer >= 0) then
4577 if gPlayers[FSpectatePlayer] <> nil then
4578 if gPlayers[FSpectatePlayer].alive then
4579 begin
4580 FXTo := gPlayers[FSpectatePlayer].GameX;
4581 FYTo := gPlayers[FSpectatePlayer].GameY;
4582 end;
4583 end;
4585 blockmon := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X, FObj.Y+PLAYER_HEADRECT.Y,
4586 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
4587 PANEL_BLOCKMON, True);
4588 headwater := HeadInLiquid(0, 0);
4590 // Сопротивление воздуха:
4591 if (not FAlive) or not (FKeys[KEY_LEFT].Pressed or FKeys[KEY_RIGHT].Pressed) then
4592 if FObj.Vel.X <> 0 then
4593 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
4595 if (FLastHit = HIT_TRAP) and (FPain > 90) then FPain := 90;
4596 DecMin(FPain, 5, 0);
4597 DecMin(FPickup, 1, 0);
4599 if FAlive and (FObj.Y > Integer(gMapInfo.Height)+128) and AnyServer then
4600 begin
4601 // Обнулить действия примочек, чтобы фон пропал
4602 FMegaRulez[MR_SUIT] := 0;
4603 FMegaRulez[MR_INVUL] := 0;
4604 FMegaRulez[MR_INVIS] := 0;
4605 Kill(K_FALLKILL, 0, HIT_FALL);
4606 end;
4608 i := 9;
4610 if FAlive then
4611 begin
4612 if FCurrWeap = WEAPON_SAW then
4613 if not (FSawSound.IsPlaying() or FSawSoundHit.IsPlaying() or
4614 FSawSoundSelect.IsPlaying()) then
4615 FSawSoundIdle.PlayAt(FObj.X, FObj.Y);
4617 if FJetpack then
4618 if (not FJetSoundFly.IsPlaying()) and (not FJetSoundOn.IsPlaying()) and
4619 (not FJetSoundOff.IsPlaying()) then
4620 begin
4621 FJetSoundFly.SetPosition(0);
4622 FJetSoundFly.PlayAt(FObj.X, FObj.Y);
4623 end;
4625 for b := WP_FIRST to WP_LAST do
4626 if FReloading[b] > 0 then
4627 if FNoReload then
4628 FReloading[b] := 0
4629 else
4630 Dec(FReloading[b]);
4632 if FShellTimer > -1 then
4633 if FShellTimer = 0 then
4634 begin
4635 if FShellType = SHELL_SHELL then
4636 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4637 GameVelX, GameVelY-2, SHELL_SHELL)
4638 else if FShellType = SHELL_DBLSHELL then
4639 begin
4640 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4641 GameVelX+1, GameVelY-2, SHELL_SHELL);
4642 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4643 GameVelX-1, GameVelY-2, SHELL_SHELL);
4644 end;
4645 FShellTimer := -1;
4646 end else Dec(FShellTimer);
4648 if (FBFGFireCounter > -1) then
4649 if FBFGFireCounter = 0 then
4650 begin
4651 if AnyServer then
4652 begin
4653 wx := FObj.X+WEAPONPOINT[FDirection].X;
4654 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
4655 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
4656 yd := wy+firediry();
4657 g_Weapon_bfgshot(wx, wy, xd, yd, FUID);
4658 if NetServer then MH_SEND_PlayerFire(FUID, WEAPON_BFG, wx, wy, xd, yd);
4659 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4660 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4661 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4662 end;
4664 FReloading[WEAPON_BFG] := WEAPON_RELOAD[WEAPON_BFG];
4665 FBFGFireCounter := -1;
4666 end else
4667 if FNoReload then
4668 FBFGFireCounter := 0
4669 else
4670 Dec(FBFGFireCounter);
4672 if (FMegaRulez[MR_SUIT] < gTime) and AnyServer then
4673 begin
4674 b := g_GetAcidHit(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width, PLAYER_RECT.Height);
4676 if (b > 0) and (gTime mod (15*GAME_TICK) = 0) then Damage(b, 0, 0, 0, HIT_ACID);
4677 end;
4679 if (headwater or blockmon) then
4680 begin
4681 Dec(FAir);
4683 if FAir < -9 then
4684 begin
4685 if AnyServer then Damage(10, 0, 0, 0, HIT_WATER);
4686 FAir := 0;
4687 end
4688 else if (FAir mod 31 = 0) and not blockmon then
4689 begin
4690 {$IFDEF ENABLE_GFX}
4691 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2), FObj.Y+PLAYER_RECT.Y-4, 5+Random(6), 8, 4);
4692 {$ENDIF}
4693 if Random(2) = 0
4694 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
4695 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
4696 end;
4697 end else if FAir < AIR_DEF then
4698 FAir := AIR_DEF;
4700 if FFireTime > 0 then
4701 begin
4702 if BodyInLiquid(0, 0) then
4703 begin
4704 FFireTime := 0;
4705 FFirePainTime := 0;
4706 end
4707 else if FMegaRulez[MR_SUIT] >= gTime then
4708 begin
4709 if FMegaRulez[MR_SUIT] = gTime then
4710 FFireTime := 1;
4711 FFirePainTime := 0;
4712 end
4713 else
4714 begin
4715 OnFireFlame(1);
4716 if FFirePainTime <= 0 then
4717 begin
4718 if g_Game_IsServer then
4719 Damage(2, FFireAttacker, 0, 0, HIT_FLAME);
4720 FFirePainTime := 12 - FFireTime div 12;
4721 end;
4722 FFirePainTime := FFirePainTime - 1;
4723 FFireTime := FFireTime - 1;
4724 if ((FFireTime mod 33) = 0) and (FMegaRulez[MR_INVUL] < gTime) then
4725 FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
4726 if (FFireTime = 0) and g_Game_IsNet and g_Game_IsServer then
4727 MH_SEND_PlayerStats(FUID);
4728 end;
4729 end;
4731 if FDamageBuffer > 0 then
4732 begin
4733 if FDamageBuffer >= 9 then
4734 begin
4735 SetAction(A_PAIN);
4737 if FDamageBuffer < 30 then i := 9
4738 else if FDamageBuffer < 100 then i := 18
4739 else i := 27;
4740 end;
4742 ii := Round(FDamageBuffer*FHealth / nonz(FArmor*(3/4)+FHealth));
4743 FArmor := FArmor-(FDamageBuffer-ii);
4744 FHealth := FHealth-ii;
4745 if FArmor < 0 then
4746 begin
4747 FHealth := FHealth+FArmor;
4748 FArmor := 0;
4749 end;
4751 if AnyServer then
4752 if FHealth <= 0 then
4753 if FHealth > -30 then Kill(K_SIMPLEKILL, FLastSpawnerUID, FLastHit)
4754 else if FHealth > -50 then Kill(K_HARDKILL, FLastSpawnerUID, FLastHit)
4755 else Kill(K_EXTRAHARDKILL, FLastSpawnerUID, FLastHit);
4757 if FAlive and ((FLastHit <> HIT_FLAME) or (FFireTime <= 0)) then
4758 begin
4759 if FDamageBuffer <= 20 then FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y)
4760 else if FDamageBuffer <= 55 then FModel.PlaySound(MODELSOUND_PAIN, 2, FObj.X, FObj.Y)
4761 else if FDamageBuffer <= 120 then FModel.PlaySound(MODELSOUND_PAIN, 3, FObj.X, FObj.Y)
4762 else FModel.PlaySound(MODELSOUND_PAIN, 4, FObj.X, FObj.Y);
4763 end;
4765 FDamageBuffer := 0;
4766 end;
4768 {CollideItem();}
4769 end; // if FAlive then ...
4771 if (FActionAnim = A_PAIN) and (FModel.Animation <> A_PAIN) then
4772 begin
4773 FModel.ChangeAnimation(FActionAnim, FActionForce);
4774 FModel.AnimState.MinLength := i;
4775 end else FModel.ChangeAnimation(FActionAnim, FActionForce and (FModel.Animation <> A_STAND));
4777 if (FModel.AnimState.Played or ((not FActionChanged) and (FModel.Animation = A_WALK)))
4778 then SetAction(A_STAND, True);
4780 if not ((FModel.Animation = A_WALK) and (Abs(FObj.Vel.X) < 4) and not FModel.GetFire()) then FModel.Update;
4782 for b := Low(FKeys) to High(FKeys) do
4783 if FKeys[b].Time = 0 then FKeys[b].Pressed := False else Dec(FKeys[b].Time);
4784 end;
4787 procedure TPlayer.getMapBox (out x, y, w, h: Integer); inline;
4788 begin
4789 x := FObj.X+PLAYER_RECT.X;
4790 y := FObj.Y+PLAYER_RECT.Y;
4791 w := PLAYER_RECT.Width;
4792 h := PLAYER_RECT.Height;
4793 end;
4796 procedure TPlayer.moveBy (dx, dy: Integer); inline;
4797 begin
4798 if (dx <> 0) or (dy <> 0) then
4799 begin
4800 FObj.X += dx;
4801 FObj.Y += dy;
4802 positionChanged();
4803 end;
4804 end;
4807 function TPlayer.Collide(X, Y: Integer; Width, Height: Word): Boolean;
4808 begin
4809 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4810 FObj.Y+PLAYER_RECT.Y,
4811 PLAYER_RECT.Width,
4812 PLAYER_RECT.Height,
4813 X, Y,
4814 Width, Height);
4815 end;
4817 function TPlayer.Collide(Panel: TPanel): Boolean;
4818 begin
4819 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4820 FObj.Y+PLAYER_RECT.Y,
4821 PLAYER_RECT.Width,
4822 PLAYER_RECT.Height,
4823 Panel.X, Panel.Y,
4824 Panel.Width, Panel.Height);
4825 end;
4827 function TPlayer.Collide(X, Y: Integer): Boolean;
4828 begin
4829 X := X-FObj.X-PLAYER_RECT.X;
4830 Y := Y-FObj.Y-PLAYER_RECT.Y;
4831 Result := (x >= 0) and (x <= PLAYER_RECT.Width) and
4832 (y >= 0) and (y <= PLAYER_RECT.Height);
4833 end;
4835 function g_Player_ValidName(Name: string): Boolean;
4836 var
4837 a: Integer;
4838 begin
4839 Result := True;
4841 if gPlayers = nil then Exit;
4843 for a := 0 to High(gPlayers) do
4844 if gPlayers[a] <> nil then
4845 if LowerCase(Name) = LowerCase(gPlayers[a].FName) then
4846 begin
4847 Result := False;
4848 Exit;
4849 end;
4850 end;
4852 procedure TPlayer.SetDirection(Direction: TDirection);
4853 var
4854 d: TDirection;
4855 begin
4856 d := FModel.Direction;
4858 FModel.Direction := Direction;
4859 if d <> Direction then FModel.ChangeAnimation(FModel.Animation, True);
4861 FDirection := Direction;
4862 end;
4864 function TPlayer.GetKeys(): Byte;
4865 begin
4866 Result := 0;
4868 if R_KEY_RED in FRulez then Result := KEY_RED;
4869 if R_KEY_GREEN in FRulez then Result := Result or KEY_GREEN;
4870 if R_KEY_BLUE in FRulez then Result := Result or KEY_BLUE;
4872 if FTeam = TEAM_RED then Result := Result or KEY_REDTEAM;
4873 if FTeam = TEAM_BLUE then Result := Result or KEY_BLUETEAM;
4874 end;
4876 procedure TPlayer.Use();
4877 var
4878 a: Integer;
4879 begin
4880 if FTime[T_USE] > gTime then Exit;
4882 g_Triggers_PressR(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
4883 PLAYER_RECT.Height, FUID, ACTIVATE_PLAYERPRESS);
4885 for a := 0 to High(gPlayers) do
4886 if (gPlayers[a] <> nil) and (gPlayers[a] <> Self) and
4887 gPlayers[a].alive and SameTeam(FUID, gPlayers[a].FUID) and
4888 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4889 FObj.Rect.Width, FObj.Rect.Height, @gPlayers[a].FObj) then
4890 begin
4891 gPlayers[a].Touch();
4892 if g_Game_IsNet and g_Game_IsServer then
4893 MH_SEND_GameEvent(NET_EV_PLAYER_TOUCH, gPlayers[a].FUID);
4894 end;
4896 FTime[T_USE] := gTime+120;
4897 end;
4899 procedure TPlayer.NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
4900 var
4901 locObj: TObj;
4902 visible: Boolean = True;
4903 WX, WY, XD, YD: Integer;
4904 begin
4905 WX := X;
4906 WY := Y;
4907 XD := AX;
4908 YD := AY;
4910 case FCurrWeap of
4911 WEAPON_KASTET:
4912 begin
4913 visible := False;
4914 DoPunch();
4915 if R_BERSERK in FRulez then
4916 begin
4917 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
4918 locobj.X := FObj.X+FObj.Rect.X;
4919 locobj.Y := FObj.Y+FObj.Rect.Y;
4920 locobj.rect.X := 0;
4921 locobj.rect.Y := 0;
4922 locobj.rect.Width := 39;
4923 locobj.rect.Height := 52;
4924 locobj.Vel.X := (xd-wx) div 2;
4925 locobj.Vel.Y := (yd-wy) div 2;
4926 locobj.Accel.X := xd-wx;
4927 locobj.Accel.y := yd-wy;
4929 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
4930 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
4931 else
4932 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
4934 if gFlash = 1 then
4935 if FPain < 50 then
4936 FPain := min(FPain + 25, 50);
4937 end else
4938 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
4939 end;
4941 WEAPON_SAW:
4942 begin
4943 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4944 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
4945 begin
4946 FSawSoundSelect.Stop();
4947 FSawSound.Stop();
4948 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
4949 end
4950 else if not FSawSoundHit.IsPlaying() then
4951 begin
4952 FSawSoundSelect.Stop();
4953 FSawSound.PlayAt(FObj.X, FObj.Y);
4954 end;
4955 end;
4957 WEAPON_PISTOL:
4958 begin
4959 g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', GameX, Gamey);
4960 FFireAngle := FAngle;
4961 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4962 GameVelX, GameVelY-2, SHELL_BULLET);
4963 end;
4965 WEAPON_SHOTGUN1:
4966 begin
4967 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4968 FFireAngle := FAngle;
4969 FShellTimer := 10;
4970 FShellType := SHELL_SHELL;
4971 end;
4973 WEAPON_SHOTGUN2:
4974 begin
4975 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN2', Gamex, Gamey);
4976 FFireAngle := FAngle;
4977 FShellTimer := 13;
4978 FShellType := SHELL_DBLSHELL;
4979 end;
4981 WEAPON_CHAINGUN:
4982 begin
4983 g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', Gamex, Gamey);
4984 FFireAngle := FAngle;
4985 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4986 GameVelX, GameVelY-2, SHELL_BULLET);
4987 end;
4989 WEAPON_ROCKETLAUNCHER:
4990 begin
4991 g_Weapon_Rocket(wx, wy, xd, yd, FUID, WID);
4992 FFireAngle := FAngle;
4993 end;
4995 WEAPON_PLASMA:
4996 begin
4997 g_Weapon_Plasma(wx, wy, xd, yd, FUID, WID);
4998 FFireAngle := FAngle;
4999 end;
5001 WEAPON_BFG:
5002 begin
5003 g_Weapon_BFGShot(wx, wy, xd, yd, FUID, WID);
5004 FFireAngle := FAngle;
5005 end;
5007 WEAPON_SUPERPULEMET:
5008 begin
5009 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
5010 FFireAngle := FAngle;
5011 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
5012 GameVelX, GameVelY-2, SHELL_SHELL);
5013 end;
5015 WEAPON_FLAMETHROWER:
5016 begin
5017 g_Weapon_flame(wx, wy, xd, yd, FUID, WID);
5018 FlamerOn;
5019 FFireAngle := FAngle;
5020 end;
5021 end;
5023 if not visible then Exit;
5025 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
5026 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
5027 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
5028 end;
5030 procedure TPlayer.DoLerp(Level: Integer = 2);
5031 begin
5032 if FObj.X <> FXTo then FObj.X := Lerp(FObj.X, FXTo, Level);
5033 if FObj.Y <> FYTo then FObj.Y := Lerp(FObj.Y, FYTo, Level);
5034 end;
5036 procedure TPlayer.SetLerp(XTo, YTo: Integer);
5037 var
5038 AX, AY: Integer;
5039 begin
5040 FXTo := XTo;
5041 FYTo := YTo;
5042 if FJustTeleported or (NetInterpLevel < 1) then
5043 begin
5044 FObj.X := XTo;
5045 FObj.Y := YTo;
5046 if FJustTeleported then
5047 begin
5048 FObj.oldX := FObj.X;
5049 FObj.oldY := FObj.Y;
5050 end;
5051 end
5052 else
5053 begin
5054 AX := Abs(FXTo - FObj.X);
5055 AY := Abs(FYTo - FObj.Y);
5056 if (AX > 32) or (AX <= NetInterpLevel) then
5057 FObj.X := FXTo;
5058 if (AY > 32) or (AY <= NetInterpLevel) then
5059 FObj.Y := FYTo;
5060 end;
5061 end;
5063 function TPlayer.FullInLift(XInc, YInc: Integer): Integer;
5064 begin
5065 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5066 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5067 PANEL_LIFTUP, False) then Result := -1
5068 else
5069 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5070 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5071 PANEL_LIFTDOWN, False) then Result := 1
5072 else Result := 0;
5073 end;
5075 function TPlayer.GetFlag(Flag: Byte): Boolean;
5076 var
5077 s, ts: String;
5078 evtype, a: Byte;
5079 begin
5080 Result := False;
5082 if Flag = FLAG_NONE then
5083 Exit;
5085 if not g_Game_IsServer then Exit;
5087 // Принес чужой флаг на свою базу:
5088 if (Flag = FTeam) and
5089 (gFlags[Flag].State = FLAG_STATE_NORMAL) and
5090 (FFlag <> FLAG_NONE) then
5091 begin
5092 if FFlag = FLAG_RED then
5093 s := _lc[I_PLAYER_FLAG_RED]
5094 else
5095 s := _lc[I_PLAYER_FLAG_BLUE];
5097 evtype := FLAG_STATE_SCORED;
5099 ts := Format('%.4d', [gFlags[FFlag].CaptureTime]);
5100 Insert('.', ts, Length(ts) + 1 - 3);
5101 g_Console_Add(Format(_lc[I_PLAYER_FLAG_CAPTURE], [FName, s, ts]), True);
5103 g_Map_ResetFlag(FFlag);
5104 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_CAPTURE], [AnsiUpperCase(s)]), 144);
5106 if ((Self = gPlayer1) or (Self = gPlayer2)
5107 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5108 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5109 a := 0
5110 else
5111 a := 1;
5113 if not sound_cap_flag[a].IsPlaying() then
5114 sound_cap_flag[a].Play();
5116 gTeamStat[FTeam].Score += 1;
5118 Result := True;
5119 if g_Game_IsNet then
5120 begin
5121 MH_SEND_FlagEvent(evtype, FFlag, FUID, False);
5122 MH_SEND_GameStats;
5123 end;
5125 gFlags[FFlag].CaptureTime := 0;
5126 SetFlag(FLAG_NONE);
5127 Exit;
5128 end;
5130 // Подобрал свой флаг - вернул его на базу:
5131 if (Flag = FTeam) and
5132 (gFlags[Flag].State = FLAG_STATE_DROPPED) then
5133 begin
5134 if Flag = FLAG_RED then
5135 s := _lc[I_PLAYER_FLAG_RED]
5136 else
5137 s := _lc[I_PLAYER_FLAG_BLUE];
5139 evtype := FLAG_STATE_RETURNED;
5140 gFlags[Flag].CaptureTime := 0;
5142 g_Console_Add(Format(_lc[I_PLAYER_FLAG_RETURN], [FName, s]), True);
5144 g_Map_ResetFlag(Flag);
5145 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
5147 if ((Self = gPlayer1) or (Self = gPlayer2)
5148 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5149 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5150 a := 0
5151 else
5152 a := 1;
5154 if not sound_ret_flag[a].IsPlaying() then
5155 sound_ret_flag[a].Play();
5157 Result := True;
5158 if g_Game_IsNet then
5159 begin
5160 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5161 MH_SEND_GameStats;
5162 end;
5163 Exit;
5164 end;
5166 // Подобрал чужой флаг:
5167 if (Flag <> FTeam) and (FTime[T_FLAGCAP] <= gTime) then
5168 begin
5169 SetFlag(Flag);
5171 if Flag = FLAG_RED then
5172 s := _lc[I_PLAYER_FLAG_RED]
5173 else
5174 s := _lc[I_PLAYER_FLAG_BLUE];
5176 evtype := FLAG_STATE_CAPTURED;
5178 g_Console_Add(Format(_lc[I_PLAYER_FLAG_GET], [FName, s]), True);
5180 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_GET], [AnsiUpperCase(s)]), 144);
5182 gFlags[Flag].State := FLAG_STATE_CAPTURED;
5184 if ((Self = gPlayer1) or (Self = gPlayer2)
5185 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5186 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5187 a := 0
5188 else
5189 a := 1;
5191 if not sound_get_flag[a].IsPlaying() then
5192 sound_get_flag[a].Play();
5194 Result := True;
5195 if g_Game_IsNet then
5196 begin
5197 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5198 MH_SEND_GameStats;
5199 end;
5200 end;
5201 end;
5203 procedure TPlayer.SetFlag(Flag: Byte);
5204 begin
5205 FFlag := Flag;
5206 if FModel <> nil then
5207 FModel.SetFlag(FFlag);
5208 end;
5210 function TPlayer.TryDropFlag(): Boolean;
5211 begin
5212 if LongBool(gGameSettings.Options and GAME_OPTION_ALLOWDROPFLAG) then
5213 Result := DropFlag(False, LongBool(gGameSettings.Options and GAME_OPTION_THROWFLAG))
5214 else
5215 Result := False;
5216 end;
5218 function TPlayer.DropFlag(Silent: Boolean = True; DoThrow: Boolean = False): Boolean;
5219 var
5220 s: String;
5221 a: Byte;
5222 xv, yv: Integer;
5223 begin
5224 Result := False;
5225 if (not g_Game_IsServer) or (FFlag = FLAG_NONE) then
5226 Exit;
5227 FTime[T_FLAGCAP] := gTime + 2000;
5228 with gFlags[FFlag] do
5229 begin
5230 Obj.X := FObj.X;
5231 Obj.Y := FObj.Y;
5232 Direction := FDirection;
5233 State := FLAG_STATE_DROPPED;
5234 Count := FLAG_TIME;
5235 if DoThrow then
5236 begin
5237 xv := FObj.Vel.X + IfThen(Direction = TDirection.D_RIGHT, 10, -10);
5238 yv := FObj.Vel.Y - 2;
5239 end
5240 else
5241 begin
5242 xv := (FObj.Vel.X div 2);
5243 yv := (FObj.Vel.Y div 2) - 2;
5244 end;
5245 g_Obj_Push(@Obj, xv, yv);
5247 positionChanged(); // this updates spatial accelerators
5249 if FFlag = FLAG_RED then
5250 s := _lc[I_PLAYER_FLAG_RED]
5251 else
5252 s := _lc[I_PLAYER_FLAG_BLUE];
5254 g_Console_Add(Format(_lc[I_PLAYER_FLAG_DROP], [FName, s]), True);
5255 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_DROP], [AnsiUpperCase(s)]), 144);
5257 if ((Self = gPlayer1) or (Self = gPlayer2)
5258 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5259 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5260 a := 0
5261 else
5262 a := 1;
5264 if (not Silent) and (not sound_lost_flag[a].IsPlaying()) then
5265 sound_lost_flag[a].Play();
5267 if g_Game_IsNet then
5268 MH_SEND_FlagEvent(FLAG_STATE_DROPPED, Flag, FUID, False);
5269 end;
5270 SetFlag(FLAG_NONE);
5271 Result := True;
5272 end;
5274 procedure TPlayer.GetSecret();
5275 begin
5276 if (self = gPlayer1) or (self = gPlayer2) then
5277 begin
5278 g_Console_Add(Format(_lc[I_PLAYER_SECRET], [FName]), True);
5279 g_Sound_PlayEx('SOUND_GAME_SECRET');
5280 end;
5281 Inc(FSecrets);
5282 end;
5284 procedure TPlayer.PressKey(Key: Byte; Time: Word = 1);
5285 begin
5286 Assert(Key <= High(FKeys));
5288 FKeys[Key].Pressed := True;
5289 FKeys[Key].Time := Time;
5290 end;
5292 function TPlayer.IsKeyPressed(K: Byte): Boolean;
5293 begin
5294 Result := FKeys[K].Pressed;
5295 end;
5297 procedure TPlayer.ReleaseKeys();
5298 var
5299 a: Integer;
5300 begin
5301 for a := Low(FKeys) to High(FKeys) do
5302 begin
5303 FKeys[a].Pressed := False;
5304 FKeys[a].Time := 0;
5305 end;
5306 end;
5308 procedure TPlayer.OnDamage(Angle: SmallInt);
5309 begin
5310 end;
5312 function TPlayer.firediry(): Integer;
5313 begin
5314 if FKeys[KEY_UP].Pressed then Result := -42
5315 else if FKeys[KEY_DOWN].Pressed then Result := 19
5316 else Result := 0;
5317 end;
5319 procedure TPlayer.RememberState();
5320 var
5321 i: Integer;
5322 SavedState: TPlayerSavedState;
5323 begin
5324 SavedState.Health := FHealth;
5325 SavedState.Armor := FArmor;
5326 SavedState.Air := FAir;
5327 SavedState.JetFuel := FJetFuel;
5328 SavedState.CurrWeap := FCurrWeap;
5329 SavedState.NextWeap := FNextWeap;
5330 SavedState.NextWeapDelay := FNextWeapDelay;
5331 for i := Low(FWeapon) to High(FWeapon) do
5332 SavedState.Weapon[i] := FWeapon[i];
5333 for i := Low(FAmmo) to High(FAmmo) do
5334 SavedState.Ammo[i] := FAmmo[i];
5335 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5336 SavedState.MaxAmmo[i] := FMaxAmmo[i];
5337 SavedState.Rulez := FRulez - [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5339 FSavedStateNum := -1;
5340 for i := Low(SavedStates) to High(SavedStates) do
5341 if not SavedStates[i].Used then
5342 begin
5343 FSavedStateNum := i;
5344 break;
5345 end;
5346 if FSavedStateNum < 0 then
5347 begin
5348 SetLength(SavedStates, Length(SavedStates) + 1);
5349 FSavedStateNum := High(SavedStates);
5350 end;
5352 SavedState.Used := True;
5353 SavedStates[FSavedStateNum] := SavedState;
5354 end;
5356 procedure TPlayer.RecallState();
5357 var
5358 i: Integer;
5359 SavedState: TPlayerSavedState;
5360 begin
5361 if(FSavedStateNum < 0) or (FSavedStateNum > High(SavedStates)) then
5362 Exit;
5364 SavedState := SavedStates[FSavedStateNum];
5365 SavedStates[FSavedStateNum].Used := False;
5366 FSavedStateNum := -1;
5368 FHealth := SavedState.Health;
5369 FArmor := SavedState.Armor;
5370 FAir := SavedState.Air;
5371 FJetFuel := SavedState.JetFuel;
5372 FCurrWeap := SavedState.CurrWeap;
5373 FNextWeap := SavedState.NextWeap;
5374 FNextWeapDelay := SavedState.NextWeapDelay;
5375 for i := Low(FWeapon) to High(FWeapon) do
5376 FWeapon[i] := SavedState.Weapon[i];
5377 for i := Low(FAmmo) to High(FAmmo) do
5378 FAmmo[i] := SavedState.Ammo[i];
5379 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5380 FMaxAmmo[i] := SavedState.MaxAmmo[i];
5381 FRulez := SavedState.Rulez;
5383 if gGameSettings.GameType = GT_SERVER then
5384 MH_SEND_PlayerStats(FUID);
5385 end;
5387 procedure TPlayer.SaveState (st: TStream);
5388 var
5389 i: Integer;
5390 b: Byte;
5391 begin
5392 // Сигнатура игрока
5393 utils.writeSign(st, 'PLYR');
5394 utils.writeInt(st, Byte(PLR_SAVE_VERSION)); // version
5395 // Бот или человек
5396 utils.writeBool(st, FIamBot);
5397 // UID игрока
5398 utils.writeInt(st, Word(FUID));
5399 // Имя игрока
5400 utils.writeStr(st, FName);
5401 // Команда
5402 utils.writeInt(st, Byte(FTeam));
5403 // Жив ли
5404 utils.writeBool(st, FAlive);
5405 // Израсходовал ли все жизни
5406 utils.writeBool(st, FNoRespawn);
5407 // Направление
5408 if FDirection = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
5409 utils.writeInt(st, Byte(b));
5410 // Здоровье
5411 utils.writeInt(st, LongInt(FHealth));
5412 // Коэффициент инвалидности
5413 utils.writeInt(st, LongInt(FHandicap));
5414 // Жизни
5415 utils.writeInt(st, Byte(FLives));
5416 // Броня
5417 utils.writeInt(st, LongInt(FArmor));
5418 // Запас воздуха
5419 utils.writeInt(st, LongInt(FAir));
5420 // Запас горючего
5421 utils.writeInt(st, LongInt(FJetFuel));
5422 // Боль
5423 utils.writeInt(st, LongInt(FPain));
5424 // Убил
5425 utils.writeInt(st, LongInt(FKills));
5426 // Убил монстров
5427 utils.writeInt(st, LongInt(FMonsterKills));
5428 // Фрагов
5429 utils.writeInt(st, LongInt(FFrags));
5430 // Фрагов подряд
5431 utils.writeInt(st, Byte(FFragCombo));
5432 // Время последнего фрага
5433 utils.writeInt(st, LongWord(FLastFrag));
5434 // Смертей
5435 utils.writeInt(st, LongInt(FDeath));
5436 // Какой флаг несет
5437 utils.writeInt(st, Byte(FFlag));
5438 // Нашел секретов
5439 utils.writeInt(st, LongInt(FSecrets));
5440 // Текущее оружие
5441 utils.writeInt(st, Byte(FCurrWeap));
5442 // Желаемое оружие
5443 utils.writeInt(st, Word(FNextWeap));
5444 // ...и пауза
5445 utils.writeInt(st, Byte(FNextWeapDelay));
5446 // Время зарядки BFG
5447 utils.writeInt(st, SmallInt(FBFGFireCounter));
5448 // Буфер урона
5449 utils.writeInt(st, LongInt(FDamageBuffer));
5450 // Последний ударивший
5451 utils.writeInt(st, Word(FLastSpawnerUID));
5452 // Тип последнего полученного урона
5453 utils.writeInt(st, Byte(FLastHit));
5454 // Объект игрока
5455 Obj_SaveState(st, @FObj);
5456 // Текущее количество патронов
5457 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FAmmo[i]));
5458 // Максимальное количество патронов
5459 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FMaxAmmo[i]));
5460 // Наличие оружия
5461 for i := WP_FIRST to WP_LAST do utils.writeBool(st, FWeapon[i]);
5462 // Время перезарядки оружия
5463 for i := WP_FIRST to WP_LAST do utils.writeInt(st, Word(FReloading[i]));
5464 // Наличие рюкзака
5465 utils.writeBool(st, (R_ITEM_BACKPACK in FRulez));
5466 // Наличие красного ключа
5467 utils.writeBool(st, (R_KEY_RED in FRulez));
5468 // Наличие зеленого ключа
5469 utils.writeBool(st, (R_KEY_GREEN in FRulez));
5470 // Наличие синего ключа
5471 utils.writeBool(st, (R_KEY_BLUE in FRulez));
5472 // Наличие берсерка
5473 utils.writeBool(st, (R_BERSERK in FRulez));
5474 // Время действия специальных предметов
5475 for i := MR_SUIT to MR_MAX do utils.writeInt(st, LongWord(FMegaRulez[i]));
5476 // Время до повторного респауна, смены оружия, исользования, захвата флага
5477 for i := T_RESPAWN to T_FLAGCAP do utils.writeInt(st, LongWord(FTime[i]));
5478 // Название модели
5479 utils.writeStr(st, FModel.GetName());
5480 // Цвет модели
5481 utils.writeInt(st, Byte(FColor.R));
5482 utils.writeInt(st, Byte(FColor.G));
5483 utils.writeInt(st, Byte(FColor.B));
5484 end;
5487 procedure TPlayer.LoadState (st: TStream);
5488 var
5489 i: Integer;
5490 str: String;
5491 b: Byte;
5492 begin
5493 assert(st <> nil);
5495 // Сигнатура игрока
5496 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
5497 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
5498 // Бот или человек:
5499 FIamBot := utils.readBool(st);
5500 // UID игрока
5501 FUID := utils.readWord(st);
5502 // Имя игрока
5503 str := utils.readStr(st);
5504 if (self <> gPlayer1) and (self <> gPlayer2) then FName := str;
5505 // Команда
5506 FTeam := utils.readByte(st);
5507 // Жив ли
5508 FAlive := utils.readBool(st);
5509 // Израсходовал ли все жизни
5510 FNoRespawn := utils.readBool(st);
5511 // Направление
5512 b := utils.readByte(st);
5513 if b = 1 then FDirection := TDirection.D_LEFT else FDirection := TDirection.D_RIGHT; // b = 2
5514 // Здоровье
5515 FHealth := utils.readLongInt(st);
5516 // Коэффициент инвалидности
5517 FHandicap := utils.readLongInt(st);
5518 // Жизни
5519 FLives := utils.readByte(st);
5520 // Броня
5521 FArmor := utils.readLongInt(st);
5522 // Запас воздуха
5523 FAir := utils.readLongInt(st);
5524 // Запас горючего
5525 FJetFuel := utils.readLongInt(st);
5526 // Боль
5527 FPain := utils.readLongInt(st);
5528 // Убил
5529 FKills := utils.readLongInt(st);
5530 // Убил монстров
5531 FMonsterKills := utils.readLongInt(st);
5532 // Фрагов
5533 FFrags := utils.readLongInt(st);
5534 // Фрагов подряд
5535 FFragCombo := utils.readByte(st);
5536 // Время последнего фрага
5537 FLastFrag := utils.readLongWord(st);
5538 // Смертей
5539 FDeath := utils.readLongInt(st);
5540 // Какой флаг несет
5541 FFlag := utils.readByte(st);
5542 // Нашел секретов
5543 FSecrets := utils.readLongInt(st);
5544 // Текущее оружие
5545 FCurrWeap := utils.readByte(st);
5546 // Желаемое оружие
5547 FNextWeap := utils.readWord(st);
5548 // ...и пауза
5549 FNextWeapDelay := utils.readByte(st);
5550 // Время зарядки BFG
5551 FBFGFireCounter := utils.readSmallInt(st);
5552 // Буфер урона
5553 FDamageBuffer := utils.readLongInt(st);
5554 // Последний ударивший
5555 FLastSpawnerUID := utils.readWord(st);
5556 // Тип последнего полученного урона
5557 FLastHit := utils.readByte(st);
5558 // Объект игрока
5559 Obj_LoadState(@FObj, st);
5560 // Текущее количество патронов
5561 for i := A_BULLETS to A_HIGH do FAmmo[i] := utils.readWord(st);
5562 // Максимальное количество патронов
5563 for i := A_BULLETS to A_HIGH do FMaxAmmo[i] := utils.readWord(st);
5564 // Наличие оружия
5565 for i := WP_FIRST to WP_LAST do FWeapon[i] := utils.readBool(st);
5566 // Время перезарядки оружия
5567 for i := WP_FIRST to WP_LAST do FReloading[i] := utils.readWord(st);
5568 // Наличие рюкзака
5569 if utils.readBool(st) then Include(FRulez, R_ITEM_BACKPACK);
5570 // Наличие красного ключа
5571 if utils.readBool(st) then Include(FRulez, R_KEY_RED);
5572 // Наличие зеленого ключа
5573 if utils.readBool(st) then Include(FRulez, R_KEY_GREEN);
5574 // Наличие синего ключа
5575 if utils.readBool(st) then Include(FRulez, R_KEY_BLUE);
5576 // Наличие берсерка
5577 if utils.readBool(st) then Include(FRulez, R_BERSERK);
5578 // Время действия специальных предметов
5579 for i := MR_SUIT to MR_MAX do FMegaRulez[i] := utils.readLongWord(st);
5580 // Время до повторного респауна, смены оружия, исользования, захвата флага
5581 for i := T_RESPAWN to T_FLAGCAP do FTime[i] := utils.readLongWord(st);
5582 // Название модели
5583 str := utils.readStr(st);
5584 // Цвет модели
5585 FColor.R := utils.readByte(st);
5586 FColor.G := utils.readByte(st);
5587 FColor.B := utils.readByte(st);
5588 if (self = gPlayer1) then
5589 begin
5590 str := gPlayer1Settings.Model;
5591 FColor := gPlayer1Settings.Color;
5592 end
5593 else if (self = gPlayer2) then
5594 begin
5595 str := gPlayer2Settings.Model;
5596 FColor := gPlayer2Settings.Color;
5597 end;
5598 // Обновляем модель игрока
5599 SetModel(str);
5600 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
5601 FModel.Color := TEAMCOLOR[FTeam]
5602 else
5603 FModel.Color := FColor;
5604 end;
5607 procedure TPlayer.AllRulez(Health: Boolean);
5608 var
5609 a: Integer;
5610 begin
5611 if Health then
5612 begin
5613 FHealth := PLAYER_HP_LIMIT;
5614 FArmor := PLAYER_AP_LIMIT;
5615 Exit;
5616 end;
5618 for a := WP_FIRST to WP_LAST do FWeapon[a] := True;
5619 for a := A_BULLETS to A_HIGH do FAmmo[a] := 30000;
5620 FRulez := FRulez+[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5621 end;
5623 procedure TPlayer.RestoreHealthArmor();
5624 begin
5625 FHealth := PLAYER_HP_LIMIT;
5626 FArmor := PLAYER_AP_LIMIT;
5627 end;
5629 procedure TPlayer.FragCombo();
5630 var
5631 Param: Integer;
5632 begin
5633 if (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) or g_Game_IsClient then
5634 Exit;
5635 if gTime - FLastFrag < FRAG_COMBO_TIME then
5636 begin
5637 if FFragCombo < 5 then
5638 Inc(FFragCombo);
5639 Param := FUID or (FFragCombo shl 16);
5640 if (FComboEvnt >= Low(gDelayedEvents)) and
5641 (FComboEvnt <= High(gDelayedEvents)) and
5642 gDelayedEvents[FComboEvnt].Pending and
5643 (gDelayedEvents[FComboEvnt].DEType = DE_KILLCOMBO) and
5644 (gDelayedEvents[FComboEvnt].DENum and $FFFF = FUID) then
5645 begin
5646 gDelayedEvents[FComboEvnt].Time := gTime + 500;
5647 gDelayedEvents[FComboEvnt].DENum := Param;
5648 end
5649 else
5650 FComboEvnt := g_Game_DelayEvent(DE_KILLCOMBO, 500, Param);
5651 end
5652 else
5653 FFragCombo := 1;
5655 FLastFrag := gTime;
5656 end;
5658 procedure TPlayer.GiveItem(ItemType: Byte);
5659 begin
5660 case ItemType of
5661 ITEM_SUIT:
5662 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
5663 begin
5664 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
5665 end;
5667 ITEM_OXYGEN:
5668 if FAir < AIR_MAX then
5669 begin
5670 FAir := AIR_MAX;
5671 end;
5673 ITEM_MEDKIT_BLACK:
5674 begin
5675 if not (R_BERSERK in FRulez) then
5676 begin
5677 Include(FRulez, R_BERSERK);
5678 if FBFGFireCounter < 1 then
5679 begin
5680 FCurrWeap := WEAPON_KASTET;
5681 resetWeaponQueue();
5682 FModel.SetWeapon(WEAPON_KASTET);
5683 end;
5684 if gFlash <> 0 then
5685 Inc(FPain, 100);
5686 FBerserk := gTime+30000;
5687 end;
5688 if FHealth < PLAYER_HP_SOFT then
5689 begin
5690 FHealth := PLAYER_HP_SOFT;
5691 FBerserk := gTime+30000;
5692 end;
5693 end;
5695 ITEM_INVUL:
5696 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
5697 begin
5698 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
5699 FSpawnInvul := 0;
5700 end;
5702 ITEM_INVIS:
5703 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
5704 begin
5705 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
5706 end;
5708 ITEM_JETPACK:
5709 if FJetFuel < JET_MAX then
5710 begin
5711 FJetFuel := JET_MAX;
5712 end;
5714 ITEM_MEDKIT_SMALL: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
5715 ITEM_MEDKIT_LARGE: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
5717 ITEM_ARMOR_GREEN: if FArmor < PLAYER_AP_SOFT then FArmor := PLAYER_AP_SOFT;
5718 ITEM_ARMOR_BLUE: if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5720 ITEM_SPHERE_BLUE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
5721 ITEM_SPHERE_WHITE:
5722 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) then
5723 begin
5724 if FHealth < PLAYER_HP_LIMIT then FHealth := PLAYER_HP_LIMIT;
5725 if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5726 end;
5728 ITEM_WEAPON_SAW: FWeapon[WEAPON_SAW] := True;
5729 ITEM_WEAPON_SHOTGUN1: FWeapon[WEAPON_SHOTGUN1] := True;
5730 ITEM_WEAPON_SHOTGUN2: FWeapon[WEAPON_SHOTGUN2] := True;
5731 ITEM_WEAPON_CHAINGUN: FWeapon[WEAPON_CHAINGUN] := True;
5732 ITEM_WEAPON_ROCKETLAUNCHER: FWeapon[WEAPON_ROCKETLAUNCHER] := True;
5733 ITEM_WEAPON_PLASMA: FWeapon[WEAPON_PLASMA] := True;
5734 ITEM_WEAPON_BFG: FWeapon[WEAPON_BFG] := True;
5735 ITEM_WEAPON_SUPERPULEMET: FWeapon[WEAPON_SUPERPULEMET] := True;
5736 ITEM_WEAPON_FLAMETHROWER: FWeapon[WEAPON_FLAMETHROWER] := True;
5738 ITEM_AMMO_BULLETS: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5739 ITEM_AMMO_BULLETS_BOX: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
5740 ITEM_AMMO_SHELLS: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5741 ITEM_AMMO_SHELLS_BOX: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
5742 ITEM_AMMO_ROCKET: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5743 ITEM_AMMO_ROCKET_BOX: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
5744 ITEM_AMMO_CELL: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5745 ITEM_AMMO_CELL_BIG: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
5746 ITEM_AMMO_FUELCAN: if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
5748 ITEM_AMMO_BACKPACK:
5749 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
5750 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
5751 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
5752 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
5753 (FMaxAmmo[A_FUEL] < AmmoLimits[1, A_FUEL]) then
5754 begin
5755 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
5756 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
5757 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
5758 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
5759 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
5761 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5762 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5763 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5764 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5766 FRulez := FRulez + [R_ITEM_BACKPACK];
5767 end;
5769 ITEM_KEY_RED: if not (R_KEY_RED in FRulez) then Include(FRulez, R_KEY_RED);
5770 ITEM_KEY_GREEN: if not (R_KEY_GREEN in FRulez) then Include(FRulez, R_KEY_GREEN);
5771 ITEM_KEY_BLUE: if not (R_KEY_BLUE in FRulez) then Include(FRulez, R_KEY_BLUE);
5773 ITEM_BOTTLE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
5774 ITEM_HELMET: if FArmor < PLAYER_AP_LIMIT then IncMax(FArmor, 5, PLAYER_AP_LIMIT);
5776 else
5777 Exit;
5778 end;
5779 if g_Game_IsNet and g_Game_IsServer then
5780 MH_SEND_PlayerStats(FUID);
5781 end;
5783 procedure TPlayer.FlySmoke(Times: DWORD = 1);
5784 var i: DWORD;
5785 begin
5786 if (Random(5) = 1) and (Times = 1) then
5787 Exit;
5789 if BodyInLiquid(0, 0) then
5790 begin
5791 {$IFDEF ENABLE_GFX}
5792 g_GFX_Bubbles(Obj.X+Obj.Rect.X+(Obj.Rect.Width div 2)+Random(3)-1,
5793 Obj.Y+Obj.Rect.Height+8, 1, 8, 4);
5794 {$ENDIF}
5795 if Random(2) = 0
5796 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
5797 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
5798 Exit;
5799 end;
5801 for i := 1 to Times do
5802 begin
5803 {$IFDEF ENABLE_GFX}
5804 g_GFX_QueueEffect(
5805 R_GFX_SMOKE_TRANS,
5806 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_SMOKE_WIDTH div 2),
5807 Obj.Y+Obj.Rect.Height-4+Random(8+Times*2)
5808 );
5809 {$ENDIF}
5810 end;
5811 end;
5813 procedure TPlayer.OnFireFlame(Times: DWORD = 1);
5814 var i: DWORD;
5815 begin
5816 if (Random(10) = 1) and (Times = 1) then
5817 Exit;
5819 for i := 1 to Times do
5820 begin
5821 {$IFDEF ENABLE_GFX}
5822 g_GFX_QueueEffect(
5823 R_GFX_FLAME,
5824 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_FLAME_WIDTH div 2),
5825 Obj.Y+8+Random(8+Times*2)
5826 );
5827 {$ENDIF}
5828 end;
5829 end;
5831 procedure TPlayer.PauseSounds(Enable: Boolean);
5832 begin
5833 FSawSound.Pause(Enable);
5834 FSawSoundIdle.Pause(Enable);
5835 FSawSoundHit.Pause(Enable);
5836 FSawSoundSelect.Pause(Enable);
5837 FFlameSoundOn.Pause(Enable);
5838 FFlameSoundOff.Pause(Enable);
5839 FFlameSoundWork.Pause(Enable);
5840 FJetSoundFly.Pause(Enable);
5841 FJetSoundOn.Pause(Enable);
5842 FJetSoundOff.Pause(Enable);
5843 end;
5845 { T C o r p s e : }
5847 constructor TCorpse.Create(X, Y: Integer; ModelName: String; aMess: Boolean);
5848 begin
5849 g_Obj_Init(@FObj);
5850 FObj.X := X;
5851 FObj.Y := Y;
5852 FObj.Rect := PLAYER_CORPSERECT;
5853 FMess := aMess;
5854 FModel := g_PlayerModel_Get(ModelName);
5856 if FMess then
5857 begin
5858 FState := CORPSE_STATE_MESS;
5859 FModel.ChangeAnimation(A_DIE2);
5860 end
5861 else
5862 begin
5863 FState := CORPSE_STATE_NORMAL;
5864 FModel.ChangeAnimation(A_DIE1);
5865 end;
5866 end;
5868 destructor TCorpse.Destroy();
5869 begin
5870 FModel.Free;
5871 inherited;
5872 end;
5874 function TCorpse.ObjPtr (): PObj; inline; begin result := @FObj; end;
5876 procedure TCorpse.positionChanged (); inline; begin end;
5878 procedure TCorpse.moveBy (dx, dy: Integer); inline;
5879 begin
5880 if (dx <> 0) or (dy <> 0) then
5881 begin
5882 FObj.X += dx;
5883 FObj.Y += dy;
5884 positionChanged();
5885 end;
5886 end;
5889 procedure TCorpse.getMapBox (out x, y, w, h: Integer); inline;
5890 begin
5891 x := FObj.X+PLAYER_CORPSERECT.X;
5892 y := FObj.Y+PLAYER_CORPSERECT.Y;
5893 w := PLAYER_CORPSERECT.Width;
5894 h := PLAYER_CORPSERECT.Height;
5895 end;
5898 procedure TCorpse.Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
5899 {$IFDEF ENABLE_GFX}
5900 var Blood: TModelBlood;
5901 {$ENDIF}
5902 begin
5903 if FState = CORPSE_STATE_REMOVEME then
5904 Exit;
5906 FDamage := FDamage + Value;
5908 if FDamage > 150 then
5909 begin
5910 if FModel <> nil then
5911 begin
5912 FState := CORPSE_STATE_REMOVEME;
5914 g_Player_CreateGibs(
5915 FObj.X + FObj.Rect.X + (FObj.Rect.Width div 2),
5916 FObj.Y + FObj.Rect.Y + (FObj.Rect.Height div 2),
5917 FModel.id,
5918 FModel.Color
5919 );
5921 // Звук мяса от трупа:
5922 FModel.PlaySound(MODELSOUND_DIE, 5, FObj.X, FObj.Y);
5924 // Зловещий смех:
5925 if (gBodyKillEvent <> -1) and gDelayedEvents[gBodyKillEvent].Pending then
5926 gDelayedEvents[gBodyKillEvent].Pending := False;
5927 gBodyKillEvent := g_Game_DelayEvent(DE_BODYKILL, 1050, SpawnerUID);
5929 FModel.Free;
5930 FModel := nil;
5931 end
5932 end
5933 else
5934 begin
5935 FObj.Vel.X := FObj.Vel.X + vx;
5936 FObj.Vel.Y := FObj.Vel.Y + vy;
5937 {$IFDEF ENABLE_GFX}
5938 Blood := FModel.GetBlood();
5939 g_GFX_Blood(FObj.X+PLAYER_CORPSERECT.X+(PLAYER_CORPSERECT.Width div 2),
5940 FObj.Y+PLAYER_CORPSERECT.Y+(PLAYER_CORPSERECT.Height div 2),
5941 Value, vx, vy, 16, (PLAYER_CORPSERECT.Height*2) div 3,
5942 Blood.R, Blood.G, Blood.B, Blood.Kind);
5943 {$ENDIF}
5944 end;
5945 end;
5947 procedure TCorpse.Update();
5948 var
5949 st: Word;
5950 begin
5951 if FState = CORPSE_STATE_REMOVEME then
5952 Exit;
5954 FObj.oldX := FObj.X;
5955 FObj.oldY := FObj.Y;
5957 if gTime mod (GAME_TICK*2) <> 0 then
5958 begin
5959 g_Obj_Move(@FObj, True, True, True);
5960 positionChanged(); // this updates spatial accelerators
5961 Exit;
5962 end;
5964 // Сопротивление воздуха для трупа:
5965 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
5967 st := g_Obj_Move(@FObj, True, True, True);
5968 positionChanged(); // this updates spatial accelerators
5970 if WordBool(st and MOVE_FALLOUT) then
5971 begin
5972 FState := CORPSE_STATE_REMOVEME;
5973 Exit;
5974 end;
5976 if FModel <> nil then
5977 FModel.Update;
5978 end;
5981 procedure TCorpse.SaveState (st: TStream);
5982 var anim: Boolean;
5983 begin
5984 assert(st <> nil);
5986 // Сигнатура трупа
5987 utils.writeSign(st, 'CORP');
5988 utils.writeInt(st, Byte(0));
5989 // Состояние
5990 utils.writeInt(st, Byte(FState));
5991 // Накопленный урон
5992 utils.writeInt(st, Byte(FDamage));
5993 // Цвет
5994 utils.writeInt(st, Byte(FModel.Color.R));
5995 utils.writeInt(st, Byte(FModel.Color.G));
5996 utils.writeInt(st, Byte(FModel.Color.B));
5997 // Объект трупа
5998 Obj_SaveState(st, @FObj);
5999 utils.writeInt(st, Word(FPlayerUID));
6000 // animation
6001 anim := (FModel <> nil);
6002 utils.writeBool(st, anim);
6003 if anim then FModel.AnimState.SaveState(st, 0, False);
6004 // animation for mask (same as animation, compat with older saves)
6005 anim := (FModel <> nil);
6006 utils.writeBool(st, anim);
6007 if anim then FModel.AnimState.SaveState(st, 0, False);
6008 end;
6011 procedure TCorpse.LoadState (st: TStream);
6012 var anim, blending: Boolean; r, g, b, alpha: Byte; stub: TAnimationState;
6013 begin
6014 assert(st <> nil);
6016 // Сигнатура трупа
6017 if not utils.checkSign(st, 'CORP') then raise XStreamError.Create('invalid corpse signature');
6018 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid corpse version');
6019 // Состояние
6020 FState := utils.readByte(st);
6021 // Накопленный урон
6022 FDamage := utils.readByte(st);
6023 // Цвет
6024 r := utils.readByte(st);
6025 g := utils.readByte(st);
6026 b := utils.readByte(st);
6027 FModel.SetColor(r, g, b);
6028 // Объект трупа
6029 Obj_LoadState(@FObj, st);
6030 FPlayerUID := utils.readWord(st);
6031 // animation
6032 stub := TAnimationState.Create(False, 0, 0);
6033 anim := utils.readBool(st);
6034 if anim then
6035 begin
6036 stub.LoadState(st, alpha, blending);
6037 FModel.AnimState.CurrentFrame := Min(stub.CurrentFrame, FModel.AnimState.Length);
6038 end
6039 else
6040 begin
6041 FModel.Free;
6042 FModel := nil
6043 end;
6044 // animation for mask (same as animation, compat with older saves)
6045 anim := utils.readBool(st);
6046 if anim then stub.LoadState(st, alpha, blending);
6047 stub.Free;
6048 end;
6050 { T B o t : }
6052 constructor TBot.Create();
6053 var
6054 a: Integer;
6055 begin
6056 inherited Create();
6058 FPhysics := True;
6059 FSpectator := False;
6060 FGhost := False;
6062 FIamBot := True;
6064 Inc(gNumBots);
6066 for a := WP_FIRST to WP_LAST do
6067 begin
6068 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
6069 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
6070 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
6071 end;
6072 end;
6074 destructor TBot.Destroy();
6075 begin
6076 Dec(gNumBots);
6077 inherited Destroy();
6078 end;
6080 procedure TBot.Respawn(Silent: Boolean; Force: Boolean = False);
6081 begin
6082 inherited Respawn(Silent, Force);
6084 FAIFlags := nil;
6085 FSelectedWeapon := FCurrWeap;
6086 resetWeaponQueue();
6087 FTargetUID := 0;
6088 end;
6090 procedure TBot.UpdateCombat();
6091 type
6092 TTarget = record
6093 UID: Word;
6094 X, Y: Integer;
6095 Rect: TRectWH;
6096 cX, cY: Integer;
6097 Dist: Word;
6098 Line: Boolean;
6099 Visible: Boolean;
6100 IsPlayer: Boolean;
6101 end;
6103 TTargetRecord = array of TTarget;
6105 function Compare(a, b: TTarget): Integer;
6106 begin
6107 if a.Line and not b.Line then // A на линии огня
6108 Result := -1
6109 else
6110 if not a.Line and b.Line then // B на линии огня
6111 Result := 1
6112 else // И A, и B на линии или не на линии огня
6113 if (a.Line and b.Line) or ((not a.Line) and (not b.Line)) then
6114 begin
6115 if a.Dist > b.Dist then // B ближе
6116 Result := 1
6117 else // A ближе или равноудаленно с B
6118 Result := -1;
6119 end
6120 else // Странно -> A
6121 Result := -1;
6122 end;
6124 var
6125 a, x1, y1, x2, y2: Integer;
6126 targets: TTargetRecord;
6127 ammo: Word;
6128 Target, BestTarget: TTarget;
6129 firew, fireh: Integer;
6130 angle: SmallInt;
6131 mon: TMonster;
6132 pla, tpla: TPlayer;
6133 vsPlayer, vsMonster, ok: Boolean;
6136 function monsUpdate (mon: TMonster): Boolean;
6137 begin
6138 result := false; // don't stop
6139 if mon.alive and (mon.MonsterType <> MONSTER_BARREL) then
6140 begin
6141 if not TargetOnScreen(mon.Obj.X+mon.Obj.Rect.X, mon.Obj.Y+mon.Obj.Rect.Y) then exit;
6143 x2 := mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2);
6144 y2 := mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2);
6146 // Если монстр на экране и не прикрыт стеной
6147 if g_TraceVector(x1, y1, x2, y2) then
6148 begin
6149 // Добавляем к списку возможных целей
6150 SetLength(targets, Length(targets)+1);
6151 with targets[High(targets)] do
6152 begin
6153 UID := mon.UID;
6154 X := mon.Obj.X;
6155 Y := mon.Obj.Y;
6156 cX := x2;
6157 cY := y2;
6158 Rect := mon.Obj.Rect;
6159 Dist := g_PatchLength(x1, y1, x2, y2);
6160 Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6161 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6162 Visible := True;
6163 IsPlayer := False;
6164 end;
6165 end;
6166 end;
6167 end;
6169 begin
6170 vsPlayer := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER);
6171 vsMonster := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER);
6173 // Если текущее оружие не то, что нужно, то меняем:
6174 if FCurrWeap <> FSelectedWeapon then
6175 NextWeapon();
6177 // Если нужно стрелять и нужное оружие, то нажать "Стрелять":
6178 if (GetAIFlag('NEEDFIRE') <> '') and (FCurrWeap = FSelectedWeapon) then
6179 begin
6180 RemoveAIFlag('NEEDFIRE');
6182 case FCurrWeap of
6183 WEAPON_PLASMA, WEAPON_SUPERPULEMET, WEAPON_CHAINGUN: PressKey(KEY_FIRE, 20);
6184 WEAPON_SAW, WEAPON_KASTET, WEAPON_FLAMETHROWER: PressKey(KEY_FIRE, 40);
6185 else PressKey(KEY_FIRE);
6186 end;
6187 end;
6189 // Координаты ствола:
6190 x1 := FObj.X + WEAPONPOINT[FDirection].X;
6191 y1 := FObj.Y + WEAPONPOINT[FDirection].Y;
6193 Target.UID := FTargetUID;
6195 ok := False;
6196 if Target.UID <> 0 then
6197 begin // Цель есть - настраиваем
6198 if (g_GetUIDType(Target.UID) = UID_PLAYER) and
6199 vsPlayer then
6200 begin // Игрок
6201 tpla := g_Player_Get(Target.UID);
6202 if tpla <> nil then
6203 with tpla do
6204 begin
6205 if (@FObj) <> nil then
6206 begin
6207 Target.X := FObj.X;
6208 Target.Y := FObj.Y;
6209 end;
6210 end;
6212 Target.cX := Target.X + PLAYER_RECT_CX;
6213 Target.cY := Target.Y + PLAYER_RECT_CY;
6214 Target.Rect := PLAYER_RECT;
6215 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6216 Target.Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6217 (y1-4 > Target.Y+PLAYER_RECT.Y);
6218 Target.IsPlayer := True;
6219 ok := True;
6220 end
6221 else
6222 if (g_GetUIDType(Target.UID) = UID_MONSTER) and
6223 vsMonster then
6224 begin // Монстр
6225 mon := g_Monsters_ByUID(Target.UID);
6226 if mon <> nil then
6227 begin
6228 Target.X := mon.Obj.X;
6229 Target.Y := mon.Obj.Y;
6231 Target.cX := Target.X + mon.Obj.Rect.X + (mon.Obj.Rect.Width div 2);
6232 Target.cY := Target.Y + mon.Obj.Rect.Y + (mon.Obj.Rect.Height div 2);
6233 Target.Rect := mon.Obj.Rect;
6234 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6235 Target.Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6236 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6237 Target.IsPlayer := False;
6238 ok := True;
6239 end;
6240 end;
6241 end;
6243 if not ok then
6244 begin // Цели нет - обнуляем
6245 Target.X := 0;
6246 Target.Y := 0;
6247 Target.cX := 0;
6248 Target.cY := 0;
6249 Target.Visible := False;
6250 Target.Line := False;
6251 Target.IsPlayer := False;
6252 end;
6254 targets := nil;
6256 // Если цель не видима или не на линии огня, то ищем все возможные цели:
6257 if (not Target.Line) or (not Target.Visible) then
6258 begin
6259 // Игроки:
6260 if vsPlayer then
6261 for a := 0 to High(gPlayers) do
6262 if (gPlayers[a] <> nil) and (gPlayers[a].alive) and
6263 (gPlayers[a].FUID <> FUID) and
6264 (not SameTeam(FUID, gPlayers[a].FUID)) and
6265 (not gPlayers[a].NoTarget) and
6266 (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
6267 begin
6268 if not TargetOnScreen(gPlayers[a].FObj.X + PLAYER_RECT.X,
6269 gPlayers[a].FObj.Y + PLAYER_RECT.Y) then
6270 Continue;
6272 x2 := gPlayers[a].FObj.X + PLAYER_RECT_CX;
6273 y2 := gPlayers[a].FObj.Y + PLAYER_RECT_CY;
6275 // Если игрок на экране и не прикрыт стеной:
6276 if g_TraceVector(x1, y1, x2, y2) then
6277 begin
6278 // Добавляем к списку возможных целей:
6279 SetLength(targets, Length(targets)+1);
6280 with targets[High(targets)] do
6281 begin
6282 UID := gPlayers[a].FUID;
6283 X := gPlayers[a].FObj.X;
6284 Y := gPlayers[a].FObj.Y;
6285 cX := x2;
6286 cY := y2;
6287 Rect := PLAYER_RECT;
6288 Dist := g_PatchLength(x1, y1, x2, y2);
6289 Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6290 (y1-4 > Target.Y+PLAYER_RECT.Y);
6291 Visible := True;
6292 IsPlayer := True;
6293 end;
6294 end;
6295 end;
6297 // Монстры:
6298 if vsMonster then g_Mons_ForEach(monsUpdate);
6299 end;
6301 // Если есть возможные цели:
6302 // (Выбираем лучшую, меняем оружие и бежим к ней/от нее)
6303 if targets <> nil then
6304 begin
6305 // Выбираем наилучшую цель:
6306 BestTarget := targets[0];
6307 if Length(targets) > 1 then
6308 for a := 1 to High(targets) do
6309 if Compare(BestTarget, targets[a]) = 1 then
6310 BestTarget := targets[a];
6312 // Если лучшая цель "виднее" текущей, то текущая := лучшая:
6313 if ((not Target.Visible) and BestTarget.Visible and (Target.UID <> BestTarget.UID)) or
6314 ((not Target.Line) and BestTarget.Line and BestTarget.Visible) then
6315 begin
6316 Target := BestTarget;
6318 if (Healthy() = 3) or ((Healthy() = 2)) then
6319 begin // Если здоровы - догоняем
6320 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6321 SetAIFlag('GORIGHT', '1');
6322 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6323 SetAIFlag('GOLEFT', '1');
6324 end
6325 else
6326 begin // Если побиты - убегаем
6327 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6328 SetAIFlag('GORIGHT', '1');
6329 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6330 SetAIFlag('GOLEFT', '1');
6331 end;
6333 // Выбираем оружие на основе расстояния и приоритетов:
6334 SelectWeapon(Abs(x1-Target.cX));
6335 end;
6336 end;
6338 // Если есть цель:
6339 // (Догоняем/убегаем, стреляем по направлению к цели)
6340 // (Если цель далеко, то хватит следить за ней)
6341 if Target.UID <> 0 then
6342 begin
6343 if not TargetOnScreen(Target.X + Target.Rect.X,
6344 Target.Y + Target.Rect.Y) then
6345 begin // Цель сбежала с "экрана"
6346 if (Healthy() = 3) or ((Healthy() = 2)) then
6347 begin // Если здоровы - догоняем
6348 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6349 SetAIFlag('GORIGHT', '1');
6350 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6351 SetAIFlag('GOLEFT', '1');
6352 end
6353 else
6354 begin // Если побиты - забываем о цели и убегаем
6355 Target.UID := 0;
6356 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6357 SetAIFlag('GORIGHT', '1');
6358 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6359 SetAIFlag('GOLEFT', '1');
6360 end;
6361 end
6362 else
6363 begin // Цель пока на "экране"
6364 // Если цель не загорожена стеной, то отмечаем, когда ее видели:
6365 if g_TraceVector(x1, y1, Target.cX, Target.cY) then
6366 FLastVisible := gTime;
6367 // Если разница высот не велика, то догоняем:
6368 if (Abs(FObj.Y-Target.Y) <= 128) then
6369 begin
6370 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6371 SetAIFlag('GORIGHT', '1');
6372 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6373 SetAIFlag('GOLEFT', '1');
6374 end;
6375 end;
6377 // Выбираем угол вверх:
6378 if FDirection = TDirection.D_LEFT then
6379 angle := ANGLE_LEFTUP
6380 else
6381 angle := ANGLE_RIGHTUP;
6383 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6384 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6386 // Если при угле вверх можно попасть в приблизительное положение цели:
6387 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6388 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128), //96
6389 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6390 Target.Rect.Width, Target.Rect.Height) and
6391 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6392 begin // то нужно стрелять вверх
6393 SetAIFlag('NEEDFIRE', '1');
6394 SetAIFlag('NEEDSEEUP', '1');
6395 end;
6397 // Выбираем угол вниз:
6398 if FDirection = TDirection.D_LEFT then
6399 angle := ANGLE_LEFTDOWN
6400 else
6401 angle := ANGLE_RIGHTDOWN;
6403 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6404 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6406 // Если при угле вниз можно попасть в приблизительное положение цели:
6407 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6408 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6409 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6410 Target.Rect.Width, Target.Rect.Height) and
6411 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6412 begin // то нужно стрелять вниз
6413 SetAIFlag('NEEDFIRE', '1');
6414 SetAIFlag('NEEDSEEDOWN', '1');
6415 end;
6417 // Если цель видно и она на такой же высоте:
6418 if Target.Visible and
6419 (y1+4 < Target.Y+Target.Rect.Y+Target.Rect.Height) and
6420 (y1-4 > Target.Y+Target.Rect.Y) then
6421 begin
6422 // Если идем в сторону цели, то надо стрелять:
6423 if ((FDirection = TDirection.D_LEFT) and (Target.X < FObj.X)) or
6424 ((FDirection = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6425 begin // то нужно стрелять вперед
6426 SetAIFlag('NEEDFIRE', '1');
6427 SetAIFlag('NEEDSEEDOWN', '');
6428 SetAIFlag('NEEDSEEUP', '');
6429 end;
6430 // Если цель в пределах "экрана" и сложность позволяет прыжки сближения:
6431 if Abs(FObj.X-Target.X) < Trunc(gPlayerScreenSize.X*0.75) then
6432 if GetRnd(FDifficult.CloseJump) then
6433 begin // то если повезет - прыгаем (особенно, если близко)
6434 if Abs(FObj.X-Target.X) < 128 then
6435 a := 4
6436 else
6437 a := 30;
6438 if Random(a) = 0 then
6439 SetAIFlag('NEEDJUMP', '1');
6440 end;
6441 end;
6443 // Если цель все еще есть:
6444 if Target.UID <> 0 then
6445 if gTime-FLastVisible > 2000 then // Если видели давно
6446 Target.UID := 0 // то забыть цель
6447 else // Если видели недавно
6448 begin // но цель убили
6449 if Target.IsPlayer then
6450 begin // Цель - игрок
6451 pla := g_Player_Get(Target.UID);
6452 if (pla = nil) or (not pla.alive) or pla.NoTarget or
6453 (pla.FMegaRulez[MR_INVIS] >= gTime) then
6454 Target.UID := 0; // то забыть цель
6455 end
6456 else
6457 begin // Цель - монстр
6458 mon := g_Monsters_ByUID(Target.UID);
6459 if (mon = nil) or (not mon.alive) then
6460 Target.UID := 0; // то забыть цель
6461 end;
6462 end;
6463 end; // if Target.UID <> 0
6465 FTargetUID := Target.UID;
6467 // Если возможных целей нет:
6468 // (Атака чего-нибудь слева или справа)
6469 if targets = nil then
6470 if GetAIFlag('ATTACKLEFT') <> '' then
6471 begin // Если нужно атаковать налево
6472 RemoveAIFlag('ATTACKLEFT');
6474 SetAIFlag('NEEDJUMP', '1');
6476 if RunDirection() = TDirection.D_RIGHT then
6477 begin // Идем не в ту сторону
6478 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6479 begin // Если здоровы, то, возможно, стреляем бежим влево и стреляем
6480 SetAIFlag('NEEDFIRE', '1');
6481 SetAIFlag('GOLEFT', '1');
6482 end;
6483 end
6484 else
6485 begin // Идем в нужную сторону
6486 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6487 SetAIFlag('NEEDFIRE', '1');
6488 if Healthy() <= 1 then // Побиты - убегаем
6489 SetAIFlag('GORIGHT', '1');
6490 end;
6491 end
6492 else
6493 if GetAIFlag('ATTACKRIGHT') <> '' then
6494 begin // Если нужно атаковать направо
6495 RemoveAIFlag('ATTACKRIGHT');
6497 SetAIFlag('NEEDJUMP', '1');
6499 if RunDirection() = TDirection.D_LEFT then
6500 begin // Идем не в ту сторону
6501 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6502 begin // Если здоровы, то, возможно, бежим вправо и стреляем
6503 SetAIFlag('NEEDFIRE', '1');
6504 SetAIFlag('GORIGHT', '1');
6505 end;
6506 end
6507 else
6508 begin
6509 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6510 SetAIFlag('NEEDFIRE', '1');
6511 if Healthy() <= 1 then // Побиты - убегаем
6512 SetAIFlag('GOLEFT', '1');
6513 end;
6514 end;
6516 //HACK! (does it belongs there?)
6517 RealizeCurrentWeapon();
6519 // Если есть возможные цели:
6520 // (Стреляем по направлению к целям)
6521 if (targets <> nil) and (GetAIFlag('NEEDFIRE') <> '') then
6522 for a := 0 to High(targets) do
6523 begin
6524 // Если можем стрелять по диагонали:
6525 if GetRnd(FDifficult.DiagFire) then
6526 begin
6527 // Ищем цель сверху и стреляем, если есть:
6528 if FDirection = TDirection.D_LEFT then
6529 angle := ANGLE_LEFTUP
6530 else
6531 angle := ANGLE_RIGHTUP;
6533 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6534 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6536 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6537 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6538 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6539 targets[a].Rect.Width, targets[a].Rect.Height) and
6540 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6541 begin
6542 SetAIFlag('NEEDFIRE', '1');
6543 SetAIFlag('NEEDSEEUP', '1');
6544 end;
6546 // Ищем цель снизу и стреляем, если есть:
6547 if FDirection = TDirection.D_LEFT then
6548 angle := ANGLE_LEFTDOWN
6549 else
6550 angle := ANGLE_RIGHTDOWN;
6552 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6553 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6555 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6556 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6557 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6558 targets[a].Rect.Width, targets[a].Rect.Height) and
6559 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6560 begin
6561 SetAIFlag('NEEDFIRE', '1');
6562 SetAIFlag('NEEDSEEDOWN', '1');
6563 end;
6564 end;
6566 // Если цель "перед носом", то стреляем:
6567 if targets[a].Line and targets[a].Visible and
6568 (((FDirection = TDirection.D_LEFT) and (targets[a].X < FObj.X)) or
6569 ((FDirection = TDirection.D_RIGHT) and (targets[a].X > FObj.X))) then
6570 begin
6571 SetAIFlag('NEEDFIRE', '1');
6572 Break;
6573 end;
6574 end;
6576 // Если летит пуля, то, возможно, подпрыгиваем:
6577 if g_Weapon_Danger(FUID, FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y,
6578 PLAYER_RECT.Width, PLAYER_RECT.Height,
6579 40+GetInterval(FDifficult.Cover, 40)) then
6580 SetAIFlag('NEEDJUMP', '1');
6582 // Если кончились паторны, то нужно сменить оружие:
6583 ammo := GetAmmoByWeapon(FCurrWeap);
6584 if ((FCurrWeap = WEAPON_SHOTGUN2) and (ammo < 2)) or
6585 ((FCurrWeap = WEAPON_BFG) and (ammo < 40)) or
6586 (ammo = 0) then
6587 SetAIFlag('SELECTWEAPON', '1');
6589 // Если нужно сменить оружие, то выбираем нужное:
6590 if GetAIFlag('SELECTWEAPON') = '1' then
6591 begin
6592 SelectWeapon(-1);
6593 RemoveAIFlag('SELECTWEAPON');
6594 end;
6595 end;
6597 procedure TBot.Update();
6598 var
6599 EnableAI: Boolean;
6600 begin
6601 if not FAlive then
6602 begin // Respawn
6603 ReleaseKeys();
6604 PressKey(KEY_UP);
6605 end
6606 else
6607 begin
6608 EnableAI := True;
6610 // Проверяем, отключён ли AI ботов
6611 if (g_debug_BotAIOff = 1) and (Team = TEAM_RED) then
6612 EnableAI := False;
6613 if (g_debug_BotAIOff = 2) and (Team = TEAM_BLUE) then
6614 EnableAI := False;
6615 if g_debug_BotAIOff = 3 then
6616 EnableAI := False;
6618 if EnableAI then
6619 begin
6620 UpdateMove();
6621 UpdateCombat();
6622 end
6623 else
6624 begin
6625 RealizeCurrentWeapon();
6626 end;
6627 end;
6629 inherited Update();
6630 end;
6632 procedure TBot.ReleaseKey(Key: Byte);
6633 begin
6634 with FKeys[Key] do
6635 begin
6636 Pressed := False;
6637 Time := 0;
6638 end;
6639 end;
6641 function TBot.KeyPressed(Key: Word): Boolean;
6642 begin
6643 Result := FKeys[Key].Pressed;
6644 end;
6646 function TBot.GetAIFlag(aName: String20): String20;
6647 var
6648 a: Integer;
6649 begin
6650 Result := '';
6652 aName := LowerCase(aName);
6654 if FAIFlags <> nil then
6655 for a := 0 to High(FAIFlags) do
6656 if LowerCase(FAIFlags[a].Name) = aName then
6657 begin
6658 Result := FAIFlags[a].Value;
6659 Break;
6660 end;
6661 end;
6663 procedure TBot.RemoveAIFlag(aName: String20);
6664 var
6665 a, b: Integer;
6666 begin
6667 if FAIFlags = nil then Exit;
6669 aName := LowerCase(aName);
6671 for a := 0 to High(FAIFlags) do
6672 if LowerCase(FAIFlags[a].Name) = aName then
6673 begin
6674 if a <> High(FAIFlags) then
6675 for b := a to High(FAIFlags)-1 do
6676 FAIFlags[b] := FAIFlags[b+1];
6678 SetLength(FAIFlags, Length(FAIFlags)-1);
6679 Break;
6680 end;
6681 end;
6683 procedure TBot.SetAIFlag(aName, fValue: String20);
6684 var
6685 a: Integer;
6686 ok: Boolean;
6687 begin
6688 a := 0;
6689 ok := False;
6691 aName := LowerCase(aName);
6693 if FAIFlags <> nil then
6694 for a := 0 to High(FAIFlags) do
6695 if LowerCase(FAIFlags[a].Name) = aName then
6696 begin
6697 ok := True;
6698 Break;
6699 end;
6701 if ok then FAIFlags[a].Value := fValue
6702 else
6703 begin
6704 SetLength(FAIFlags, Length(FAIFlags)+1);
6705 with FAIFlags[High(FAIFlags)] do
6706 begin
6707 Name := aName;
6708 Value := fValue;
6709 end;
6710 end;
6711 end;
6713 procedure TBot.UpdateMove;
6715 procedure GoLeft(Time: Word = 1);
6716 begin
6717 ReleaseKey(KEY_LEFT);
6718 ReleaseKey(KEY_RIGHT);
6719 PressKey(KEY_LEFT, Time);
6720 SetDirection(TDirection.D_LEFT);
6721 end;
6723 procedure GoRight(Time: Word = 1);
6724 begin
6725 ReleaseKey(KEY_LEFT);
6726 ReleaseKey(KEY_RIGHT);
6727 PressKey(KEY_RIGHT, Time);
6728 SetDirection(TDirection.D_RIGHT);
6729 end;
6731 function Rnd(a: Word): Boolean;
6732 begin
6733 Result := Random(a) = 0;
6734 end;
6736 procedure Turn(Time: Word = 1200);
6737 begin
6738 if RunDirection() = TDirection.D_LEFT then GoRight(Time) else GoLeft(Time);
6739 end;
6741 procedure Stop();
6742 begin
6743 ReleaseKey(KEY_LEFT);
6744 ReleaseKey(KEY_RIGHT);
6745 end;
6747 function CanRunLeft(): Boolean;
6748 begin
6749 Result := not CollideLevel(-1, 0);
6750 end;
6752 function CanRunRight(): Boolean;
6753 begin
6754 Result := not CollideLevel(1, 0);
6755 end;
6757 function CanRun(): Boolean;
6758 begin
6759 if RunDirection() = TDirection.D_LEFT then Result := CanRunLeft() else Result := CanRunRight();
6760 end;
6762 procedure Jump(Time: Word = 30);
6763 begin
6764 PressKey(KEY_JUMP, Time);
6765 end;
6767 function NearHole(): Boolean;
6768 var
6769 x, sx: Integer;
6770 begin
6771 { TODO 5 : Лестницы }
6772 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6773 for x := 1 to PLAYER_RECT.Width do
6774 if (not StayOnStep(x*sx, 0)) and
6775 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6776 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6777 begin
6778 Result := True;
6779 Exit;
6780 end;
6782 Result := False;
6783 end;
6785 function BorderHole(): Boolean;
6786 var
6787 x, sx, xx: Integer;
6788 begin
6789 { TODO 5 : Лестницы }
6790 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6791 for x := 1 to PLAYER_RECT.Width do
6792 if (not StayOnStep(x*sx, 0)) and
6793 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6794 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6795 begin
6796 for xx := x to x+32 do
6797 if CollideLevel(xx*sx, PLAYER_RECT.Height) then
6798 begin
6799 Result := True;
6800 Exit;
6801 end;
6802 end;
6804 Result := False;
6805 end;
6807 function NearDeepHole(): Boolean;
6808 var
6809 x, sx, y: Integer;
6810 begin
6811 Result := False;
6813 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6814 y := 3;
6816 for x := 1 to PLAYER_RECT.Width do
6817 if (not StayOnStep(x*sx, 0)) and
6818 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6819 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6820 begin
6821 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6822 begin
6823 if CollideLevel(x*sx, PLAYER_RECT.Height*y) then Exit;
6824 y := y+1;
6825 end;
6827 Result := True;
6828 end else Result := False;
6829 end;
6831 function OverDeepHole(): Boolean;
6832 var
6833 y: Integer;
6834 begin
6835 Result := False;
6837 y := 1;
6838 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6839 begin
6840 if CollideLevel(0, PLAYER_RECT.Height*y) then Exit;
6841 y := y+1;
6842 end;
6844 Result := True;
6845 end;
6847 function OnGround(): Boolean;
6848 begin
6849 Result := StayOnStep(0, 0) or CollideLevel(0, 1);
6850 end;
6852 function OnLadder(): Boolean;
6853 begin
6854 Result := FullInStep(0, 0);
6855 end;
6857 function BelowLadder(): Boolean;
6858 begin
6859 Result := (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) and
6860 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6861 (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) and
6862 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6863 end;
6865 function BelowLiftUp(): Boolean;
6866 begin
6867 Result := ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) = -1) and
6868 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6869 ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) = -1) and
6870 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6871 end;
6873 function OnTopLift(): Boolean;
6874 begin
6875 Result := (FullInLift(0, 0) = -1) and (FullInLift(0, -32) = 0);
6876 end;
6878 function CanJumpOver(): Boolean;
6879 var
6880 sx, y: Integer;
6881 begin
6882 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6884 Result := False;
6886 if not CollideLevel(sx, 0) then Exit;
6888 for y := 1 to BOT_MAXJUMP do
6889 if CollideLevel(0, -y) then Exit else
6890 if not CollideLevel(sx, -y) then
6891 begin
6892 Result := True;
6893 Exit;
6894 end;
6895 end;
6897 function CanJumpUp(Dist: ShortInt): Boolean;
6898 var
6899 y, yy: Integer;
6900 c: Boolean;
6901 begin
6902 Result := False;
6904 if CollideLevel(Dist, 0) then Exit;
6906 c := False;
6907 for y := 0 to BOT_MAXJUMP do
6908 if CollideLevel(Dist, -y) then
6909 begin
6910 c := True;
6911 Break;
6912 end;
6914 if not c then Exit;
6916 c := False;
6917 for yy := y+1 to BOT_MAXJUMP do
6918 if not CollideLevel(Dist, -yy) then
6919 begin
6920 c := True;
6921 Break;
6922 end;
6924 if not c then Exit;
6926 c := False;
6927 for y := 0 to BOT_MAXJUMP do
6928 if CollideLevel(0, -y) then
6929 begin
6930 c := True;
6931 Break;
6932 end;
6934 if c then Exit;
6936 if y < yy then Exit;
6938 Result := True;
6939 end;
6941 function IsSafeTrigger(): Boolean;
6942 var
6943 a: Integer;
6944 begin
6945 Result := True;
6946 if gTriggers = nil then
6947 Exit;
6948 for a := 0 to High(gTriggers) do
6949 if Collide(gTriggers[a].X,
6950 gTriggers[a].Y,
6951 gTriggers[a].Width,
6952 gTriggers[a].Height) and
6953 (gTriggers[a].TriggerType in [TRIGGER_EXIT, TRIGGER_CLOSEDOOR,
6954 TRIGGER_CLOSETRAP, TRIGGER_TRAP,
6955 TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF,
6956 TRIGGER_ONOFF, TRIGGER_SPAWNMONSTER,
6957 TRIGGER_DAMAGE, TRIGGER_SHOT]) then
6958 Result := False;
6959 end;
6961 begin
6962 // Возможно, нажимаем кнопку:
6963 if Rnd(16) and IsSafeTrigger() then
6964 PressKey(KEY_OPEN);
6966 // Если под лифтом или ступеньками, то, возможно, прыгаем:
6967 if OnLadder() or ((BelowLadder() or BelowLiftUp()) and Rnd(8)) then
6968 begin
6969 ReleaseKey(KEY_LEFT);
6970 ReleaseKey(KEY_RIGHT);
6971 Jump();
6972 end;
6974 // Идем влево, если надо было:
6975 if GetAIFlag('GOLEFT') <> '' then
6976 begin
6977 RemoveAIFlag('GOLEFT');
6978 if CanRunLeft() then
6979 GoLeft(360);
6980 end;
6982 // Идем вправо, если надо было:
6983 if GetAIFlag('GORIGHT') <> '' then
6984 begin
6985 RemoveAIFlag('GORIGHT');
6986 if CanRunRight() then
6987 GoRight(360);
6988 end;
6990 // Если вылетели за карту, то пробуем вернуться:
6991 if FObj.X < -32 then
6992 GoRight(360)
6993 else
6994 if FObj.X+32 > gMapInfo.Width then
6995 GoLeft(360);
6997 // Прыгаем, если надо было:
6998 if GetAIFlag('NEEDJUMP') <> '' then
6999 begin
7000 Jump(0);
7001 RemoveAIFlag('NEEDJUMP');
7002 end;
7004 // Смотрим вверх, если надо было:
7005 if GetAIFlag('NEEDSEEUP') <> '' then
7006 begin
7007 ReleaseKey(KEY_UP);
7008 ReleaseKey(KEY_DOWN);
7009 PressKey(KEY_UP, 20);
7010 RemoveAIFlag('NEEDSEEUP');
7011 end;
7013 // Смотрим вниз, если надо было:
7014 if GetAIFlag('NEEDSEEDOWN') <> '' then
7015 begin
7016 ReleaseKey(KEY_UP);
7017 ReleaseKey(KEY_DOWN);
7018 PressKey(KEY_DOWN, 20);
7019 RemoveAIFlag('NEEDSEEDOWN');
7020 end;
7022 // Если нужно было в дыру и мы не на земле, то покорно летим:
7023 if GetAIFlag('GOINHOLE') <> '' then
7024 if not OnGround() then
7025 begin
7026 ReleaseKey(KEY_LEFT);
7027 ReleaseKey(KEY_RIGHT);
7028 RemoveAIFlag('GOINHOLE');
7029 SetAIFlag('FALLINHOLE', '1');
7030 end;
7032 // Если падали и достигли земли, то хватит падать:
7033 if GetAIFlag('FALLINHOLE') <> '' then
7034 if OnGround() then
7035 RemoveAIFlag('FALLINHOLE');
7037 // Если летели прямо и сейчас не на лестнице или на вершине лифта, то отходим в сторону:
7038 if not (KeyPressed(KEY_LEFT) or KeyPressed(KEY_RIGHT)) then
7039 if GetAIFlag('FALLINHOLE') = '' then
7040 if (not OnLadder()) or (FObj.Vel.Y >= 0) or (OnTopLift()) then
7041 if Rnd(2) then
7042 GoLeft(360)
7043 else
7044 GoRight(360);
7046 // Если на земле и можно подпрыгнуть, то, возможно, прыгаем:
7047 if OnGround() and
7048 CanJumpUp(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*32) and
7049 Rnd(8) then
7050 Jump();
7052 // Если на земле и возле дыры (глубина > 2 ростов игрока):
7053 if OnGround() and NearHole() then
7054 if NearDeepHole() then // Если это бездна
7055 case Random(6) of
7056 0..3: Turn(); // Бежим обратно
7057 4: Jump(); // Прыгаем
7058 5: begin // Прыгаем обратно
7059 Turn();
7060 Jump();
7061 end;
7062 end
7063 else // Это не бездна и мы еще не летим туда
7064 if GetAIFlag('GOINHOLE') = '' then
7065 case Random(6) of
7066 0: Turn(); // Не нужно туда
7067 1: Jump(); // Вдруг повезет - прыгаем
7068 else // Если яма с границей, то при случае можно туда прыгнуть
7069 if BorderHole() then
7070 SetAIFlag('GOINHOLE', '1');
7071 end;
7073 // Если на земле, но некуда идти:
7074 if (not CanRun()) and OnGround() then
7075 begin
7076 // Если мы на лестнице или можно перепрыгнуть, то прыгаем:
7077 if CanJumpOver() or OnLadder() then
7078 Jump()
7079 else // иначе попытаемся в другую сторону
7080 if Random(2) = 0 then
7081 begin
7082 if IsSafeTrigger() then
7083 PressKey(KEY_OPEN);
7084 end else
7085 Turn();
7086 end;
7088 // Осталось мало воздуха:
7089 if FAir < 36 * 2 then
7090 Jump(20);
7092 // Выбираемся из кислоты, если нет костюма, обожглись, или мало здоровья:
7093 if (FMegaRulez[MR_SUIT] < gTime) and ((FLastHit = HIT_ACID) or (Healthy() <= 1)) then
7094 if BodyInAcid(0, 0) then
7095 Jump();
7096 end;
7098 function TBot.FullInStep(XInc, YInc: Integer): Boolean;
7099 begin
7100 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
7101 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_STEP, False);
7102 end;
7104 {function TBot.NeedItem(Item: Byte): Byte;
7105 begin
7106 Result := 4;
7107 end;}
7109 procedure TBot.SelectWeapon(Dist: Integer);
7110 var
7111 a: Integer;
7113 function HaveAmmo(weapon: Byte): Boolean;
7114 begin
7115 case weapon of
7116 WEAPON_PISTOL: Result := FAmmo[A_BULLETS] >= 1;
7117 WEAPON_SHOTGUN1: Result := FAmmo[A_SHELLS] >= 1;
7118 WEAPON_SHOTGUN2: Result := FAmmo[A_SHELLS] >= 2;
7119 WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS] >= 10;
7120 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS] >= 1;
7121 WEAPON_PLASMA: Result := FAmmo[A_CELLS] >= 10;
7122 WEAPON_BFG: Result := FAmmo[A_CELLS] >= 40;
7123 WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS] >= 1;
7124 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL] >= 1;
7125 else Result := True;
7126 end;
7127 end;
7129 begin
7130 if Dist = -1 then Dist := BOT_LONGDIST;
7132 if Dist > BOT_LONGDIST then
7133 begin // Дальний бой
7134 for a := 0 to 9 do
7135 if FWeapon[FDifficult.WeaponPrior[a]] and HaveAmmo(FDifficult.WeaponPrior[a]) then
7136 begin
7137 FSelectedWeapon := FDifficult.WeaponPrior[a];
7138 Break;
7139 end;
7140 end
7141 else //if Dist > BOT_UNSAFEDIST then
7142 begin // Ближний бой
7143 for a := 0 to 9 do
7144 if FWeapon[FDifficult.CloseWeaponPrior[a]] and HaveAmmo(FDifficult.CloseWeaponPrior[a]) then
7145 begin
7146 FSelectedWeapon := FDifficult.CloseWeaponPrior[a];
7147 Break;
7148 end;
7149 end;
7150 { else
7151 begin
7152 for a := 0 to 9 do
7153 if FWeapon[FDifficult.SafeWeaponPrior[a]] and HaveAmmo(FDifficult.SafeWeaponPrior[a]) then
7154 begin
7155 FSelectedWeapon := FDifficult.SafeWeaponPrior[a];
7156 Break;
7157 end;
7158 end;}
7159 end;
7161 function TBot.PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean;
7162 begin
7163 Result := inherited PickItem(ItemType, force, remove);
7165 if Result then SetAIFlag('SELECTWEAPON', '1');
7166 end;
7168 function TBot.Heal(value: Word; Soft: Boolean): Boolean;
7169 begin
7170 Result := inherited Heal(value, Soft);
7171 end;
7173 function TBot.Healthy(): Byte;
7174 begin
7175 if FMegaRulez[MR_INVUL] >= gTime then Result := 3
7176 else if (FHealth > 80) or ((FHealth > 50) and (FArmor > 20)) then Result := 3
7177 else if (FHealth > 50) then Result := 2
7178 else if (FHealth > 20) then Result := 1
7179 else Result := 0;
7180 end;
7182 function TBot.TargetOnScreen(TX, TY: Integer): Boolean;
7183 begin
7184 Result := (Abs(FObj.X-TX) <= Trunc(gPlayerScreenSize.X*0.6)) and
7185 (Abs(FObj.Y-TY) <= Trunc(gPlayerScreenSize.Y*0.6));
7186 end;
7188 procedure TBot.OnDamage(Angle: SmallInt);
7189 var
7190 pla: TPlayer;
7191 mon: TMonster;
7192 ok: Boolean;
7193 begin
7194 inherited;
7196 if (Angle = 0) or (Angle = 180) then
7197 begin
7198 ok := False;
7199 if (g_GetUIDType(FLastSpawnerUID) = UID_PLAYER) and
7200 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER) then
7201 begin // Игрок
7202 pla := g_Player_Get(FLastSpawnerUID);
7203 ok := not TargetOnScreen(pla.FObj.X + PLAYER_RECT.X,
7204 pla.FObj.Y + PLAYER_RECT.Y);
7205 end
7206 else
7207 if (g_GetUIDType(FLastSpawnerUID) = UID_MONSTER) and
7208 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER) then
7209 begin // Монстр
7210 mon := g_Monsters_ByUID(FLastSpawnerUID);
7211 ok := not TargetOnScreen(mon.Obj.X + mon.Obj.Rect.X,
7212 mon.Obj.Y + mon.Obj.Rect.Y);
7213 end;
7215 if ok then
7216 if Angle = 0 then
7217 SetAIFlag('ATTACKLEFT', '1')
7218 else
7219 SetAIFlag('ATTACKRIGHT', '1');
7220 end;
7221 end;
7223 function TBot.RunDirection(): TDirection;
7224 begin
7225 if Abs(Vel.X) >= 1 then
7226 begin
7227 if Vel.X > 0 then Result := TDirection.D_RIGHT else Result := TDirection.D_LEFT;
7228 end else
7229 Result := FDirection;
7230 end;
7232 function TBot.GetRnd(a: Byte): Boolean;
7233 begin
7234 if a = 0 then Result := False
7235 else if a = 255 then Result := True
7236 else Result := Random(256) > 255-a;
7237 end;
7239 function TBot.GetInterval(a: Byte; radius: SmallInt): SmallInt;
7240 begin
7241 Result := Round((255-a)/255*radius*(Random(2)-1));
7242 end;
7245 procedure TDifficult.save (st: TStream);
7246 begin
7247 utils.writeInt(st, Byte(DiagFire));
7248 utils.writeInt(st, Byte(InvisFire));
7249 utils.writeInt(st, Byte(DiagPrecision));
7250 utils.writeInt(st, Byte(FlyPrecision));
7251 utils.writeInt(st, Byte(Cover));
7252 utils.writeInt(st, Byte(CloseJump));
7253 st.WriteBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7254 st.WriteBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7255 end;
7257 procedure TDifficult.load (st: TStream);
7258 begin
7259 DiagFire := utils.readByte(st);
7260 InvisFire := utils.readByte(st);
7261 DiagPrecision := utils.readByte(st);
7262 FlyPrecision := utils.readByte(st);
7263 Cover := utils.readByte(st);
7264 CloseJump := utils.readByte(st);
7265 st.ReadBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7266 st.ReadBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7267 end;
7270 procedure TBot.SaveState (st: TStream);
7271 var
7272 i: Integer;
7273 dw: Integer;
7274 begin
7275 inherited SaveState(st);
7276 utils.writeSign(st, 'BOT0');
7277 // Выбранное оружие
7278 utils.writeInt(st, Byte(FSelectedWeapon));
7279 // UID цели
7280 utils.writeInt(st, Word(FTargetUID));
7281 // Время потери цели
7282 utils.writeInt(st, LongWord(FLastVisible));
7283 // Количество флагов ИИ
7284 dw := Length(FAIFlags);
7285 utils.writeInt(st, LongInt(dw));
7286 // Флаги ИИ
7287 for i := 0 to dw-1 do
7288 begin
7289 utils.writeStr(st, FAIFlags[i].Name, 20);
7290 utils.writeStr(st, FAIFlags[i].Value, 20);
7291 end;
7292 // Настройки сложности
7293 FDifficult.save(st);
7294 end;
7297 procedure TBot.LoadState (st: TStream);
7298 var
7299 i: Integer;
7300 dw: Integer;
7301 begin
7302 inherited LoadState(st);
7303 if not utils.checkSign(st, 'BOT0') then raise XStreamError.Create('invalid bot signature');
7304 // Выбранное оружие
7305 FSelectedWeapon := utils.readByte(st);
7306 // UID цели
7307 FTargetUID := utils.readWord(st);
7308 // Время потери цели
7309 FLastVisible := utils.readLongWord(st);
7310 // Количество флагов ИИ
7311 dw := utils.readLongInt(st);
7312 if (dw < 0) or (dw > 16384) then raise XStreamError.Create('invalid number of bot AI flags');
7313 SetLength(FAIFlags, dw);
7314 // Флаги ИИ
7315 for i := 0 to dw-1 do
7316 begin
7317 FAIFlags[i].Name := utils.readStr(st, 20);
7318 FAIFlags[i].Value := utils.readStr(st, 20);
7319 end;
7320 // Настройки сложности
7321 FDifficult.load(st);
7322 end;
7325 begin
7326 conRegVar('player_indicator', @gPlayerIndicator, 'Draw indicator only for current player, also for teammates, or not at all', 'Draw indicator only for current player, also for teammates, or not at all');
7327 conRegVar('player_indicator_style', @gPlayerIndicatorStyle, 'Visual appearance of indicator', 'Visual appearance of indicator');
7328 end.