DEADSOFTWARE

7bb2248c6d7ef5dad598c0fbc095cf03f019ff39
[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: TAnimation;
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: TAnimation 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 ID: DWORD;
527 MaskID: DWORD;
528 RAngle: Integer;
529 Color: TRGB;
530 Obj: TObj;
532 procedure getMapBox (out x, y, w, h: Integer); inline;
533 procedure moveBy (dx, dy: Integer); inline;
535 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
536 end;
539 PShell = ^TShell;
540 TShell = record
541 SpriteID: DWORD;
542 alive: Boolean;
543 SType: Byte;
544 RAngle: Integer;
545 Timeout: Cardinal;
546 CX, CY: Integer;
547 Obj: TObj;
549 procedure getMapBox (out x, y, w, h: Integer); inline;
550 procedure moveBy (dx, dy: Integer); inline;
552 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
553 end;
555 TCorpse = class{$IFDEF USE_MEMPOOL}(TPoolObject){$ENDIF}
556 private
557 FModelName: String;
558 FMess: Boolean;
559 FState: Byte;
560 FDamage: Byte;
561 FColor: TRGB;
562 FObj: TObj;
563 FPlayerUID: Word;
564 FAnimation: TAnimation;
565 FAnimationMask: TAnimation;
567 public
568 constructor Create(X, Y: Integer; ModelName: String; aMess: Boolean);
569 destructor Destroy(); override;
570 procedure Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
571 procedure Update();
572 procedure SaveState (st: TStream);
573 procedure LoadState (st: TStream);
575 procedure getMapBox (out x, y, w, h: Integer); inline;
576 procedure moveBy (dx, dy: Integer); inline;
578 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
580 function ObjPtr (): PObj; inline;
582 property Obj: TObj read FObj; // copies object
583 property State: Byte read FState;
584 property Mess: Boolean read FMess;
586 (* internal state *)
587 property Color: TRGB read FColor;
588 property Animation: TAnimation read FAnimation;
589 property AnimationMask: TAnimation read FAnimationMask;
590 end;
592 TTeamStat = Array [TEAM_RED..TEAM_BLUE] of
593 record
594 Score: SmallInt;
595 end;
597 var
598 gPlayers: Array of TPlayer;
599 gCorpses: Array of TCorpse;
600 gGibs: Array of TGib;
601 gShells: Array of TShell;
602 gTeamStat: TTeamStat;
603 gFly: Boolean = False;
604 gAimLine: Boolean = False;
605 gChatBubble: Integer = 0;
606 gPlayerIndicator: Integer = 1;
607 gPlayerIndicatorStyle: Integer = 0;
608 gNumBots: Word = 0;
609 gSpectLatchPID1: Word = 0;
610 gSpectLatchPID2: Word = 0;
611 MAX_RUNVEL: Integer = 8;
612 VEL_JUMP: Integer = 10;
613 SHELL_TIMEOUT: Cardinal = 60000;
615 function Lerp(X, Y, Factor: Integer): Integer;
617 procedure g_Gibs_SetMax(Count: Word);
618 function g_Gibs_GetMax(): Word;
619 procedure g_Corpses_SetMax(Count: Word);
620 function g_Corpses_GetMax(): Word;
621 procedure g_Force_Model_Set(Mode: Word);
622 function g_Force_Model_Get(): Word;
623 procedure g_Forced_Model_SetName(Model: String);
624 function g_Forced_Model_GetName(): String;
625 procedure g_Shells_SetMax(Count: Word);
626 function g_Shells_GetMax(): Word;
628 procedure g_Player_Init();
629 procedure g_Player_Free();
630 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
631 function g_Player_CreateFromState (st: TStream): Word;
632 procedure g_Player_Remove(UID: Word);
633 procedure g_Player_ResetTeams();
634 procedure g_Player_PreUpdate();
635 procedure g_Player_UpdateAll();
636 procedure g_Player_RememberAll();
637 procedure g_Player_ResetAll(Force, Silent: Boolean);
638 function g_Player_Get(UID: Word): TPlayer;
639 function g_Player_GetCount(): Byte;
640 function g_Player_GetStats(): TPlayerStatArray;
641 function g_Player_ValidName(Name: String): Boolean;
642 function g_Player_CreateCorpse(Player: TPlayer): Integer;
643 procedure g_Player_CreateGibs(fX, fY: Integer; ModelName: String; fColor: TRGB);
644 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
645 procedure g_Player_UpdatePhysicalObjects();
646 procedure g_Player_RemoveAllCorpses();
647 procedure g_Player_Corpses_SaveState (st: TStream);
648 procedure g_Player_Corpses_LoadState (st: TStream);
649 procedure g_Player_ResetReady();
650 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
651 procedure g_Bot_AddList(Team: Byte; lname: ShortString; num: Integer = -1; Handicap: Integer = 100);
652 procedure g_Bot_MixNames();
653 procedure g_Bot_RemoveAll();
654 function g_Bot_GetCount(): Integer;
656 implementation
658 uses
659 {$IFDEF ENABLE_HOLMES}
660 g_holmes,
661 {$ENDIF}
662 e_log, g_map, g_items, g_console, g_gfx, Math, r_textures, r_animations,
663 g_options, g_triggers, g_menu, g_game, g_grid, e_res,
664 wadreader, g_monsters, CONFIG, g_language,
665 g_net, g_netmsg,
666 utils, xstreams;
668 const PLR_SAVE_VERSION = 0;
670 type
671 TBotProfile = record
672 name: ShortString;
673 model: ShortString;
674 team: Byte;
675 color: TRGB;
676 diag_fire: Byte;
677 invis_fire: Byte;
678 diag_precision: Byte;
679 fly_precision: Byte;
680 cover: Byte;
681 close_jump: Byte;
682 w_prior1: Array [WP_FIRST..WP_LAST] of Byte;
683 w_prior2: Array [WP_FIRST..WP_LAST] of Byte;
684 w_prior3: Array [WP_FIRST..WP_LAST] of Byte;
685 end;
687 const
688 TIME_RESPAWN1 = 1500;
689 TIME_RESPAWN2 = 2000;
690 TIME_RESPAWN3 = 3000;
691 PLAYER_SUIT_TIME = 30000;
692 PLAYER_INVUL_TIME = 30000;
693 PLAYER_INVIS_TIME = 35000;
694 FRAG_COMBO_TIME = 3000;
695 VEL_SW = 4;
696 VEL_FLY = 6;
697 PLAYER_HEADRECT: TRectWH = (X:24; Y:12; Width:20; Height:12);
698 BOT_MAXJUMP = 84;
699 BOT_LONGDIST = 300;
700 BOT_UNSAFEDIST = 128;
701 DIFFICULT_EASY: TDifficult = (DiagFire: 32; InvisFire: 32; DiagPrecision: 32;
702 FlyPrecision: 32; Cover: 32; CloseJump: 32;
703 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
704 DIFFICULT_MEDIUM: TDifficult = (DiagFire: 127; InvisFire: 127; DiagPrecision: 127;
705 FlyPrecision: 127; Cover: 127; CloseJump: 127;
706 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
707 DIFFICULT_HARD: TDifficult = (DiagFire: 255; InvisFire: 255; DiagPrecision: 255;
708 FlyPrecision: 255; Cover: 255; CloseJump: 255;
709 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
710 WEAPON_PRIOR1: Array [WP_FIRST..WP_LAST] of Byte =
711 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
712 WEAPON_SHOTGUN2, WEAPON_SHOTGUN1,
713 WEAPON_CHAINGUN, WEAPON_PLASMA, WEAPON_ROCKETLAUNCHER,
714 WEAPON_BFG, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
715 WEAPON_PRIOR2: Array [WP_FIRST..WP_LAST] of Byte =
716 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
717 WEAPON_BFG, WEAPON_ROCKETLAUNCHER,
718 WEAPON_SHOTGUN2, WEAPON_PLASMA, WEAPON_SHOTGUN1,
719 WEAPON_CHAINGUN, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
720 //WEAPON_PRIOR3: Array [WP_FIRST..WP_LAST] of Byte =
721 // (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
722 // WEAPON_BFG, WEAPON_PLASMA, WEAPON_SHOTGUN2,
723 // WEAPON_CHAINGUN, WEAPON_SHOTGUN1, WEAPON_SAW,
724 // WEAPON_ROCKETLAUNCHER, WEAPON_PISTOL, WEAPON_KASTET);
725 WEAPON_RELOAD: Array [WP_FIRST..WP_LAST] of Byte =
726 (5, 2, 6, 18, 36, 2, 12, 2, 14, 2, 2);
728 PLAYER_SIGNATURE = $52594C50; // 'PLYR'
729 CORPSE_SIGNATURE = $50524F43; // 'CORP'
731 BOTNAMES_FILENAME = 'botnames.txt';
732 BOTLIST_FILENAME = 'botlist.txt';
734 var
735 MaxGibs: Word = 150;
736 MaxCorpses: Word = 20;
737 MaxShells: Word = 300;
738 ForceModel: Word = 0;
739 ForcedModelName: String = STD_PLAYER_MODEL;
740 CurrentGib: Integer = 0;
741 CurrentShell: Integer = 0;
742 BotNames: Array of String;
743 BotList: Array of TBotProfile;
744 SavedStates: Array of TPlayerSavedState;
747 function Lerp(X, Y, Factor: Integer): Integer;
748 begin
749 Result := X + ((Y - X) div Factor);
750 end;
752 function SameTeam(UID1, UID2: Word): Boolean;
753 begin
754 Result := False;
756 if (UID1 > UID_MAX_PLAYER) or (UID1 <= UID_MAX_GAME) or
757 (UID2 > UID_MAX_PLAYER) or (UID2 <= UID_MAX_GAME) then Exit;
759 if (g_Player_Get(UID1) = nil) or (g_Player_Get(UID2) = nil) then Exit;
761 if ((g_Player_Get(UID1).Team = TEAM_NONE) or
762 (g_Player_Get(UID2).Team = TEAM_NONE)) then Exit;
764 Result := g_Player_Get(UID1).FTeam = g_Player_Get(UID2).FTeam;
765 end;
767 procedure g_Gibs_SetMax(Count: Word);
768 begin
769 MaxGibs := Count;
770 SetLength(gGibs, Count);
772 if CurrentGib >= Count then
773 CurrentGib := 0;
774 end;
776 function g_Gibs_GetMax(): Word;
777 begin
778 Result := MaxGibs;
779 end;
781 procedure g_Shells_SetMax(Count: Word);
782 begin
783 MaxShells := Count;
784 SetLength(gShells, Count);
786 if CurrentShell >= Count then
787 CurrentShell := 0;
788 end;
790 function g_Shells_GetMax(): Word;
791 begin
792 Result := MaxShells;
793 end;
796 procedure g_Corpses_SetMax(Count: Word);
797 begin
798 MaxCorpses := Count;
799 SetLength(gCorpses, Count);
800 end;
802 function g_Corpses_GetMax(): Word;
803 begin
804 Result := MaxCorpses;
805 end;
807 procedure g_Force_Model_Set(Mode: Word);
808 begin
809 ForceModel := Mode;
810 end;
812 function g_Force_Model_Get(): Word;
813 begin
814 Result := ForceModel;
815 end;
817 procedure g_Forced_Model_SetName(Model: String);
818 begin
819 ForcedModelName := Model;
820 end;
822 function g_Forced_Model_GetName(): String;
823 begin
824 Result := ForcedModelName;
825 end;
827 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
828 var
829 a: Integer;
830 ok: Boolean;
831 begin
832 Result := 0;
834 ok := False;
835 a := 0;
837 // Есть ли место в gPlayers:
838 if gPlayers <> nil then
839 for a := 0 to High(gPlayers) do
840 if gPlayers[a] = nil then
841 begin
842 ok := True;
843 Break;
844 end;
846 // Нет места - расширяем gPlayers:
847 if not ok then
848 begin
849 SetLength(gPlayers, Length(gPlayers)+1);
850 a := High(gPlayers);
851 end;
853 // Создаем объект игрока:
854 if Bot then
855 gPlayers[a] := TBot.Create()
856 else
857 gPlayers[a] := TPlayer.Create();
860 gPlayers[a].FActualModelName := ModelName;
861 gPlayers[a].SetModel(ModelName);
862 if Bot and (g_Force_Model_Get() <> 0) then
863 gPlayers[a].SetModel(g_Forced_Model_GetName());
865 // Нет модели - создание не возможно:
866 if gPlayers[a].FModel = nil then
867 begin
868 gPlayers[a].Free();
869 gPlayers[a] := nil;
870 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], [ModelName]));
871 Exit;
872 end;
874 if not (Team in [TEAM_RED, TEAM_BLUE]) then
875 if Random(2) = 0 then
876 Team := TEAM_RED
877 else
878 Team := TEAM_BLUE;
879 gPlayers[a].FPreferredTeam := Team;
881 case gGameSettings.GameMode of
882 GM_DM: gPlayers[a].FTeam := TEAM_NONE;
883 GM_TDM,
884 GM_CTF: gPlayers[a].FTeam := gPlayers[a].FPreferredTeam;
885 GM_SINGLE,
886 GM_COOP: gPlayers[a].FTeam := TEAM_COOP;
887 end;
889 // Если командная игра - красим модель в цвет команды:
890 gPlayers[a].FColor := Color;
891 if gPlayers[a].FTeam in [TEAM_RED, TEAM_BLUE] then
892 gPlayers[a].FModel.Color := TEAMCOLOR[gPlayers[a].FTeam]
893 else
894 gPlayers[a].FModel.Color := Color;
896 gPlayers[a].FUID := g_CreateUID(UID_PLAYER);
897 gPlayers[a].FAlive := False;
899 Result := gPlayers[a].FUID;
900 end;
902 function g_Player_CreateFromState (st: TStream): Word;
903 var a: Integer; ok, Bot: Boolean; pos: Int64;
904 begin
905 assert(st <> nil);
907 // check signature and entity type
908 pos := st.Position;
909 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
910 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
911 Bot := utils.readBool(st);
912 st.Position := pos;
914 // find free player slot
915 ok := false;
916 for a := 0 to High(gPlayers) do
917 if gPlayers[a] = nil then
918 begin
919 ok := true;
920 break;
921 end;
923 // allocate player slot
924 if not ok then
925 begin
926 SetLength(gPlayers, Length(gPlayers)+1);
927 a := High(gPlayers);
928 end;
930 // create entity and load state
931 if Bot then
932 begin
933 gPlayers[a] := TBot.Create();
934 if (g_Force_Model_Get() <> 0) then
935 gPlayers[a].SetModel(g_Forced_Model_GetName());
936 end
937 else
938 gPlayers[a] := TPlayer.Create();
939 gPlayers[a].FPhysics := True; // ???
940 gPlayers[a].LoadState(st);
942 result := gPlayers[a].FUID;
943 end;
946 procedure g_Player_ResetTeams();
947 var
948 a: Integer;
949 begin
950 if g_Game_IsClient then
951 Exit;
952 if gPlayers = nil then
953 Exit;
954 for a := Low(gPlayers) to High(gPlayers) do
955 if gPlayers[a] <> nil then
956 case gGameSettings.GameMode of
957 GM_DM:
958 gPlayers[a].ChangeTeam(TEAM_NONE);
959 GM_TDM, GM_CTF:
960 if not (gPlayers[a].Team in [TEAM_RED, TEAM_BLUE]) then
961 if gPlayers[a].FPreferredTeam in [TEAM_RED, TEAM_BLUE] then
962 gPlayers[a].ChangeTeam(gPlayers[a].FPreferredTeam)
963 else
964 if a mod 2 = 0 then
965 gPlayers[a].ChangeTeam(TEAM_RED)
966 else
967 gPlayers[a].ChangeTeam(TEAM_BLUE);
968 GM_SINGLE,
969 GM_COOP:
970 gPlayers[a].ChangeTeam(TEAM_COOP);
971 end;
972 end;
974 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
975 var
976 m: SSArray;
977 _name, _model: String;
978 a, tr, tb: Integer;
979 begin
980 if not g_Game_IsServer then Exit;
982 if (g_Bot_GetCount() >= gMaxBots) then Exit;
984 // Список названий моделей:
985 m := g_PlayerModel_GetNames();
986 if m = nil then
987 Exit;
989 // Команда:
990 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
991 Team := TEAM_COOP // COOP
992 else
993 if gGameSettings.GameMode = GM_DM then
994 Team := TEAM_NONE // DM
995 else
996 if Team = TEAM_NONE then // CTF / TDM
997 begin
998 // Автобаланс команд:
999 tr := 0;
1000 tb := 0;
1002 for a := 0 to High(gPlayers) do
1003 if gPlayers[a] <> nil then
1004 begin
1005 if gPlayers[a].Team = TEAM_RED then
1006 Inc(tr)
1007 else
1008 if gPlayers[a].Team = TEAM_BLUE then
1009 Inc(tb);
1010 end;
1012 if tr > tb then
1013 Team := TEAM_BLUE
1014 else
1015 if tb > tr then
1016 Team := TEAM_RED
1017 else // tr = tb
1018 if Random(2) = 0 then
1019 Team := TEAM_RED
1020 else
1021 Team := TEAM_BLUE;
1022 end;
1024 // Выбираем боту имя:
1025 _name := '';
1026 if BotNames <> nil then
1027 for a := 0 to High(BotNames) do
1028 if g_Player_ValidName(BotNames[a]) then
1029 begin
1030 _name := BotNames[a];
1031 Break;
1032 end;
1034 // Выбираем случайную модель:
1035 _model := m[Random(Length(m))];
1037 // Создаем бота:
1038 with g_Player_Get(g_Player_Create(_model,
1039 _RGB(Min(Random(9)*32, 255),
1040 Min(Random(9)*32, 255),
1041 Min(Random(9)*32, 255)),
1042 Team, True)) as TBot do
1043 begin
1044 // Если имени нет, делаем его из UID бота
1045 if _name = '' then
1046 Name := Format('DFBOT%.5d', [UID])
1047 else
1048 Name := _name;
1050 case Difficult of
1051 1: FDifficult := DIFFICULT_EASY;
1052 2: FDifficult := DIFFICULT_MEDIUM;
1053 else FDifficult := DIFFICULT_HARD;
1054 end;
1056 for a := WP_FIRST to WP_LAST do
1057 begin
1058 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
1059 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
1060 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
1061 end;
1063 FHandicap := Handicap;
1065 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1067 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1068 if g_Game_IsServer and (gGameSettings.MaxLives > 0) then
1069 Spectate();
1070 end;
1071 end;
1073 procedure g_Bot_AddList(Team: Byte; lName: ShortString; num: Integer = -1; Handicap: Integer = 100);
1074 var
1075 m: SSArray;
1076 _name, _model: String;
1077 a: Integer;
1078 begin
1079 if not g_Game_IsServer then Exit;
1081 if (g_Bot_GetCount() >= gMaxBots) then Exit;
1083 // Список названий моделей:
1084 m := g_PlayerModel_GetNames();
1085 if m = nil then
1086 Exit;
1088 // Команда:
1089 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
1090 Team := TEAM_COOP // COOP
1091 else
1092 if gGameSettings.GameMode = GM_DM then
1093 Team := TEAM_NONE // DM
1094 else
1095 if Team = TEAM_NONE then
1096 Team := BotList[num].team; // CTF / TDM
1098 // Выбираем настройки бота из списка по номеру или имени:
1099 lName := AnsiLowerCase(lName);
1100 if (num < 0) or (num > Length(BotList)-1) then
1101 num := -1;
1102 if (num = -1) and (lName <> '') and (BotList <> nil) then
1103 for a := 0 to High(BotList) do
1104 if AnsiLowerCase(BotList[a].name) = lName then
1105 begin
1106 num := a;
1107 Break;
1108 end;
1109 if num = -1 then
1110 Exit;
1112 // Имя бота:
1113 _name := BotList[num].name;
1114 // Занято - выбираем случайное:
1115 if not g_Player_ValidName(_name) then
1116 repeat
1117 _name := Format('DFBOT%.2d', [Random(100)]);
1118 until g_Player_ValidName(_name);
1120 // Модель:
1121 _model := BotList[num].model;
1122 // Нет такой - выбираем случайную:
1123 if not InSArray(_model, m) then
1124 _model := m[Random(Length(m))];
1126 // Создаем бота:
1127 with g_Player_Get(g_Player_Create(_model, BotList[num].color, Team, True)) as TBot do
1128 begin
1129 Name := _name;
1131 FDifficult.DiagFire := BotList[num].diag_fire;
1132 FDifficult.InvisFire := BotList[num].invis_fire;
1133 FDifficult.DiagPrecision := BotList[num].diag_precision;
1134 FDifficult.FlyPrecision := BotList[num].fly_precision;
1135 FDifficult.Cover := BotList[num].cover;
1136 FDifficult.CloseJump := BotList[num].close_jump;
1138 FHandicap := Handicap;
1140 for a := WP_FIRST to WP_LAST do
1141 begin
1142 FDifficult.WeaponPrior[a] := BotList[num].w_prior1[a];
1143 FDifficult.CloseWeaponPrior[a] := BotList[num].w_prior2[a];
1144 //FDifficult.SafeWeaponPrior[a] := BotList[num].w_prior3[a];
1145 end;
1147 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1149 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1150 end;
1151 end;
1153 procedure g_Bot_RemoveAll();
1154 var
1155 a: Integer;
1156 begin
1157 if not g_Game_IsServer then Exit;
1158 if gPlayers = nil then Exit;
1160 for a := 0 to High(gPlayers) do
1161 if gPlayers[a] <> nil then
1162 if gPlayers[a] is TBot then
1163 begin
1164 gPlayers[a].Lives := 0;
1165 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
1166 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
1167 g_Player_Remove(gPlayers[a].FUID);
1168 end;
1170 g_Bot_MixNames();
1171 end;
1173 procedure g_Bot_MixNames();
1174 var
1175 s: String;
1176 a, b: Integer;
1177 begin
1178 if BotNames <> nil then
1179 for a := 0 to High(BotNames) do
1180 begin
1181 b := Random(Length(BotNames));
1182 s := BotNames[a];
1183 Botnames[a] := BotNames[b];
1184 BotNames[b] := s;
1185 end;
1186 end;
1188 procedure g_Player_Remove(UID: Word);
1189 var
1190 i: Integer;
1191 begin
1192 if gPlayers = nil then Exit;
1194 if g_Game_IsServer and g_Game_IsNet then
1195 MH_SEND_PlayerDelete(UID);
1197 for i := 0 to High(gPlayers) do
1198 if gPlayers[i] <> nil then
1199 if gPlayers[i].FUID = UID then
1200 begin
1201 if gPlayers[i] is TPlayer then
1202 TPlayer(gPlayers[i]).Free()
1203 else
1204 TBot(gPlayers[i]).Free();
1205 gPlayers[i] := nil;
1206 Exit;
1207 end;
1208 end;
1210 procedure g_Player_Init();
1211 var
1212 F: TextFile;
1213 s: String;
1214 a, b: Integer;
1215 config: TConfig;
1216 sa: SSArray;
1217 path: AnsiString;
1218 begin
1219 BotNames := nil;
1221 path := BOTNAMES_FILENAME;
1222 if e_FindResource(DataDirs, path) = false then
1223 Exit;
1225 // Читаем возможные имена ботов из файла:
1226 AssignFile(F, path);
1227 Reset(F);
1229 while not EOF(F) do
1230 begin
1231 ReadLn(F, s);
1233 s := Trim(s);
1234 if s = '' then
1235 Continue;
1237 SetLength(BotNames, Length(BotNames)+1);
1238 BotNames[High(BotNames)] := s;
1239 end;
1241 CloseFile(F);
1243 // Перемешиваем их:
1244 g_Bot_MixNames();
1246 // Читаем файл с параметрами ботов:
1247 config := TConfig.CreateFile(path);
1248 BotList := nil;
1249 a := 0;
1251 while config.SectionExists(IntToStr(a)) do
1252 begin
1253 SetLength(BotList, Length(BotList)+1);
1255 with BotList[High(BotList)] do
1256 begin
1257 // Имя бота:
1258 name := config.ReadStr(IntToStr(a), 'name', '');
1259 // Модель:
1260 model := config.ReadStr(IntToStr(a), 'model', '');
1261 // Команда:
1262 if config.ReadStr(IntToStr(a), 'team', 'red') = 'red' then
1263 team := TEAM_RED
1264 else
1265 team := TEAM_BLUE;
1266 // Цвет модели:
1267 sa := parse(config.ReadStr(IntToStr(a), 'color', ''));
1268 color.R := StrToIntDef(sa[0], 0);
1269 color.G := StrToIntDef(sa[1], 0);
1270 color.B := StrToIntDef(sa[2], 0);
1271 // Вероятность стрельбы под углом:
1272 diag_fire := config.ReadInt(IntToStr(a), 'diag_fire', 0);
1273 // Вероятность ответного огня по невидимому сопернику:
1274 invis_fire := config.ReadInt(IntToStr(a), 'invis_fire', 0);
1275 // Точность стрельбы под углом:
1276 diag_precision := config.ReadInt(IntToStr(a), 'diag_precision', 0);
1277 // Точность стрельбы в полете:
1278 fly_precision := config.ReadInt(IntToStr(a), 'fly_precision', 0);
1279 // Точность уклонения от снарядов:
1280 cover := config.ReadInt(IntToStr(a), 'cover', 0);
1281 // Вероятность прыжка при приближении соперника:
1282 close_jump := config.ReadInt(IntToStr(a), 'close_jump', 0);
1283 // Приоритеты оружия для дальнего боя:
1284 sa := parse(config.ReadStr(IntToStr(a), 'w_prior1', ''));
1285 if Length(sa) = 10 then
1286 for b := 0 to 9 do
1287 w_prior1[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1288 // Приоритеты оружия для ближнего боя:
1289 sa := parse(config.ReadStr(IntToStr(a), 'w_prior2', ''));
1290 if Length(sa) = 10 then
1291 for b := 0 to 9 do
1292 w_prior2[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1294 {sa := parse(config.ReadStr(IntToStr(a), 'w_prior3', ''));
1295 if Length(sa) = 10 then
1296 for b := 0 to 9 do
1297 w_prior3[b] := EnsureRange(StrToInt(sa[b]), 0, 9);}
1298 end;
1300 a := a + 1;
1301 end;
1303 config.Free();
1304 SetLength(SavedStates, 0);
1305 end;
1307 procedure g_Player_Free();
1308 var
1309 i: Integer;
1310 begin
1311 if gPlayers <> nil then
1312 begin
1313 for i := 0 to High(gPlayers) do
1314 if gPlayers[i] <> nil then
1315 begin
1316 if gPlayers[i] is TPlayer then
1317 TPlayer(gPlayers[i]).Free()
1318 else
1319 TBot(gPlayers[i]).Free();
1320 gPlayers[i] := nil;
1321 end;
1323 gPlayers := nil;
1324 end;
1326 gPlayer1 := nil;
1327 gPlayer2 := nil;
1328 SetLength(SavedStates, 0);
1329 end;
1331 procedure g_Player_PreUpdate();
1332 var
1333 i: Integer;
1334 begin
1335 if gPlayers = nil then Exit;
1336 for i := 0 to High(gPlayers) do
1337 if gPlayers[i] <> nil then
1338 gPlayers[i].PreUpdate();
1339 end;
1341 procedure g_Player_UpdateAll();
1342 var
1343 i: Integer;
1344 begin
1345 if gPlayers = nil then Exit;
1347 //e_WriteLog('***g_Player_UpdateAll: ENTER', MSG_WARNING);
1348 for i := 0 to High(gPlayers) do
1349 begin
1350 if gPlayers[i] <> nil then
1351 begin
1352 if gPlayers[i] is TPlayer then
1353 begin
1354 gPlayers[i].Update();
1355 gPlayers[i].RealizeCurrentWeapon(); // WARNING! DO NOT MOVE THIS INTO `Update()`!
1356 end
1357 else
1358 begin
1359 // bot updates weapons in `UpdateCombat()`
1360 TBot(gPlayers[i]).Update();
1361 end;
1362 end;
1363 end;
1364 //e_WriteLog('***g_Player_UpdateAll: EXIT', MSG_WARNING);
1365 end;
1367 function g_Player_Get(UID: Word): TPlayer;
1368 var
1369 a: Integer;
1370 begin
1371 Result := nil;
1373 if gPlayers = nil then
1374 Exit;
1376 for a := 0 to High(gPlayers) do
1377 if gPlayers[a] <> nil then
1378 if gPlayers[a].FUID = UID then
1379 begin
1380 Result := gPlayers[a];
1381 Exit;
1382 end;
1383 end;
1385 function g_Player_GetCount(): Byte;
1386 var
1387 a: Integer;
1388 begin
1389 Result := 0;
1391 if gPlayers = nil then
1392 Exit;
1394 for a := 0 to High(gPlayers) do
1395 if gPlayers[a] <> nil then
1396 Result := Result + 1;
1397 end;
1399 function g_Bot_GetCount(): Integer;
1400 var
1401 a: Integer;
1402 begin
1403 Result := 0;
1405 if gPlayers = nil then
1406 Exit;
1408 for a := 0 to High(gPlayers) do
1409 if (gPlayers[a] <> nil) and (gPlayers[a] is TBot) then
1410 Result := Result + 1;
1411 end;
1413 function g_Player_GetStats(): TPlayerStatArray;
1414 var
1415 a: Integer;
1416 begin
1417 Result := nil;
1419 if gPlayers = nil then Exit;
1421 for a := 0 to High(gPlayers) do
1422 if gPlayers[a] <> nil then
1423 begin
1424 SetLength(Result, Length(Result)+1);
1425 with Result[High(Result)] do
1426 begin
1427 Num := a;
1428 Ping := gPlayers[a].FPing;
1429 Loss := gPlayers[a].FLoss;
1430 Name := gPlayers[a].FName;
1431 Team := gPlayers[a].FTeam;
1432 Frags := gPlayers[a].FFrags;
1433 Deaths := gPlayers[a].FDeath;
1434 Kills := gPlayers[a].FKills;
1435 Color := gPlayers[a].FModel.Color;
1436 Lives := gPlayers[a].FLives;
1437 Spectator := gPlayers[a].FSpectator;
1438 UID := gPlayers[a].FUID;
1439 end;
1440 end;
1441 end;
1443 procedure g_Player_ResetReady();
1444 var
1445 a: Integer;
1446 begin
1447 if not g_Game_IsServer then Exit;
1448 if gPlayers = nil then Exit;
1450 for a := 0 to High(gPlayers) do
1451 if gPlayers[a] <> nil then
1452 begin
1453 gPlayers[a].FReady := False;
1454 if g_Game_IsNet then
1455 MH_SEND_GameEvent(NET_EV_INTER_READY, gPlayers[a].UID, 'N');
1456 end;
1457 end;
1459 procedure g_Player_RememberAll;
1460 var
1461 i: Integer;
1462 begin
1463 for i := Low(gPlayers) to High(gPlayers) do
1464 if (gPlayers[i] <> nil) and gPlayers[i].alive then
1465 gPlayers[i].RememberState;
1466 end;
1468 procedure g_Player_ResetAll(Force, Silent: Boolean);
1469 var
1470 i: Integer;
1471 begin
1472 gTeamStat[TEAM_RED].Score := 0;
1473 gTeamStat[TEAM_BLUE].Score := 0;
1475 if gPlayers <> nil then
1476 for i := 0 to High(gPlayers) do
1477 if gPlayers[i] <> nil then
1478 begin
1479 gPlayers[i].Reset(Force);
1481 if gPlayers[i] is TPlayer then
1482 begin
1483 if (not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame then
1484 gPlayers[i].Respawn(Silent)
1485 else
1486 gPlayers[i].Spectate();
1487 end
1488 else
1489 TBot(gPlayers[i]).Respawn(Silent);
1490 end;
1491 end;
1493 function g_Player_CreateCorpse(Player: TPlayer): Integer;
1494 var
1495 i: Integer;
1496 find_id: DWORD;
1497 ok: Boolean;
1498 begin
1499 Result := -1;
1501 if Player.alive then
1502 Exit;
1504 // Разрываем связь с прежним трупом:
1505 i := Player.FCorpse;
1506 if (i >= 0) and (i < Length(gCorpses)) then
1507 begin
1508 if (gCorpses[i] <> nil) and (gCorpses[i].FPlayerUID = Player.FUID) then
1509 gCorpses[i].FPlayerUID := 0;
1510 end;
1512 if Player.FObj.Y >= gMapInfo.Height+128 then
1513 Exit;
1515 with Player do
1516 begin
1517 if (FHealth >= -50) or (gGibsCount = 0) then
1518 begin
1519 if (gCorpses = nil) or (Length(gCorpses) = 0) then
1520 Exit;
1522 ok := False;
1523 for find_id := 0 to High(gCorpses) do
1524 if gCorpses[find_id] = nil then
1525 begin
1526 ok := True;
1527 Break;
1528 end;
1530 if not ok then
1531 find_id := Random(Length(gCorpses));
1533 gCorpses[find_id] := TCorpse.Create(FObj.X, FObj.Y, FModel.Name, FHealth < -20);
1534 gCorpses[find_id].FColor := FModel.Color;
1535 gCorpses[find_id].FObj.Vel := FObj.Vel;
1536 gCorpses[find_id].FObj.Accel := FObj.Accel;
1537 gCorpses[find_id].FPlayerUID := FUID;
1539 Result := find_id;
1540 end
1541 else
1542 g_Player_CreateGibs(FObj.X + PLAYER_RECT_CX,
1543 FObj.Y + PLAYER_RECT_CY,
1544 FModel.Name, FModel.Color);
1545 end;
1546 end;
1548 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
1549 var
1550 SID: DWORD;
1551 begin
1552 if (gShells = nil) or (Length(gShells) = 0) then
1553 Exit;
1555 with gShells[CurrentShell] do
1556 begin
1557 SpriteID := 0;
1558 g_Obj_Init(@Obj);
1559 Obj.Rect.X := 0;
1560 Obj.Rect.Y := 0;
1561 if T = SHELL_BULLET then
1562 begin
1563 if g_Texture_Get('TEXTURE_SHELL_BULLET', SID) then
1564 SpriteID := SID;
1565 CX := 2;
1566 CY := 1;
1567 Obj.Rect.Width := 4;
1568 Obj.Rect.Height := 2;
1569 end
1570 else
1571 begin
1572 if g_Texture_Get('TEXTURE_SHELL_SHELL', SID) then
1573 SpriteID := SID;
1574 CX := 4;
1575 CY := 2;
1576 Obj.Rect.Width := 7;
1577 Obj.Rect.Height := 3;
1578 end;
1579 SType := T;
1580 alive := True;
1581 Obj.X := fX;
1582 Obj.Y := fY;
1583 g_Obj_Push(@Obj, dX + Random(4)-Random(4), dY-Random(4));
1584 positionChanged(); // this updates spatial accelerators
1585 RAngle := Random(360);
1586 Timeout := gTime + SHELL_TIMEOUT;
1588 if CurrentShell >= High(gShells) then
1589 CurrentShell := 0
1590 else
1591 Inc(CurrentShell);
1592 end;
1593 end;
1595 procedure g_Player_CreateGibs(fX, fY: Integer; ModelName: string; fColor: TRGB);
1596 var
1597 a: Integer;
1598 GibsArray: TGibsArray;
1599 Blood: TModelBlood;
1600 begin
1601 if (gGibs = nil) or (Length(gGibs) = 0) then
1602 Exit;
1603 if not g_PlayerModel_GetGibs(ModelName, GibsArray) then
1604 Exit;
1605 Blood := g_PlayerModel_GetBlood(ModelName);
1607 for a := 0 to High(GibsArray) do
1608 with gGibs[CurrentGib] do
1609 begin
1610 Color := fColor;
1611 ID := GibsArray[a].ID;
1612 MaskID := GibsArray[a].MaskID;
1613 alive := True;
1614 g_Obj_Init(@Obj);
1615 Obj.Rect := GibsArray[a].Rect;
1616 Obj.X := fX-GibsArray[a].Rect.X-(GibsArray[a].Rect.Width div 2);
1617 Obj.Y := fY-GibsArray[a].Rect.Y-(GibsArray[a].Rect.Height div 2);
1618 g_Obj_PushA(@Obj, 25 + Random(10), Random(361));
1619 positionChanged(); // this updates spatial accelerators
1620 RAngle := Random(360);
1622 if gBloodCount > 0 then
1623 g_GFX_Blood(fX, fY, 16*gBloodCount+Random(5*gBloodCount), -16+Random(33), -16+Random(33),
1624 Random(48), Random(48), Blood.R, Blood.G, Blood.B, Blood.Kind);
1626 if CurrentGib >= High(gGibs) then
1627 CurrentGib := 0
1628 else
1629 Inc(CurrentGib);
1630 end;
1631 end;
1633 procedure g_Player_UpdatePhysicalObjects();
1634 var
1635 i: Integer;
1636 vel: TPoint2i;
1637 mr: Word;
1639 procedure ShellSound_Bounce(X, Y: Integer; T: Byte);
1640 var
1641 k: Integer;
1642 begin
1643 k := 1 + Random(2);
1644 if T = SHELL_BULLET then
1645 g_Sound_PlayExAt('SOUND_PLAYER_CASING' + IntToStr(k), X, Y)
1646 else
1647 g_Sound_PlayExAt('SOUND_PLAYER_SHELL' + IntToStr(k), X, Y);
1648 end;
1650 begin
1651 // Куски мяса:
1652 if gGibs <> nil then
1653 for i := 0 to High(gGibs) do
1654 if gGibs[i].alive then
1655 with gGibs[i] do
1656 begin
1657 Obj.oldX := Obj.X;
1658 Obj.oldY := Obj.Y;
1660 vel := Obj.Vel;
1661 mr := g_Obj_Move(@Obj, True, False, True);
1662 positionChanged(); // this updates spatial accelerators
1664 if WordBool(mr and MOVE_FALLOUT) then
1665 begin
1666 alive := False;
1667 Continue;
1668 end;
1670 // Отлетает от удара о стену/потолок/пол:
1671 if WordBool(mr and MOVE_HITWALL) then
1672 Obj.Vel.X := -(vel.X div 2);
1673 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1674 Obj.Vel.Y := -(vel.Y div 2);
1676 if (Obj.Vel.X >= 0) then
1677 begin // Clockwise
1678 RAngle := RAngle + Abs(Obj.Vel.X)*6 + Abs(Obj.Vel.Y);
1679 if RAngle >= 360 then
1680 RAngle := RAngle mod 360;
1681 end else begin // Counter-clockwise
1682 RAngle := RAngle - Abs(Obj.Vel.X)*6 - Abs(Obj.Vel.Y);
1683 if RAngle < 0 then
1684 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1685 end;
1687 // Сопротивление воздуха для куска трупа:
1688 if gTime mod (GAME_TICK*3) = 0 then
1689 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
1690 end;
1692 // Трупы:
1693 if gCorpses <> nil then
1694 for i := 0 to High(gCorpses) do
1695 if gCorpses[i] <> nil then
1696 if gCorpses[i].State = CORPSE_STATE_REMOVEME then
1697 begin
1698 gCorpses[i].Free();
1699 gCorpses[i] := nil;
1700 end
1701 else
1702 gCorpses[i].Update();
1704 // Гильзы:
1705 if gShells <> nil then
1706 for i := 0 to High(gShells) do
1707 if gShells[i].alive then
1708 with gShells[i] do
1709 begin
1710 Obj.oldX := Obj.X;
1711 Obj.oldY := Obj.Y;
1713 vel := Obj.Vel;
1714 mr := g_Obj_Move(@Obj, True, False, True);
1715 positionChanged(); // this updates spatial accelerators
1717 if WordBool(mr and MOVE_FALLOUT) or (gShells[i].Timeout < gTime) then
1718 begin
1719 alive := False;
1720 Continue;
1721 end;
1723 // Отлетает от удара о стену/потолок/пол:
1724 if WordBool(mr and MOVE_HITWALL) then
1725 begin
1726 Obj.Vel.X := -(vel.X div 2);
1727 if not WordBool(mr and MOVE_INWATER) then
1728 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1729 end;
1730 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1731 begin
1732 Obj.Vel.Y := -(vel.Y div 2);
1733 if Obj.Vel.X <> 0 then Obj.Vel.X := Obj.Vel.X div 2;
1734 if (Obj.Vel.X = 0) and (Obj.Vel.Y = 0) then
1735 begin
1736 if RAngle mod 90 <> 0 then
1737 RAngle := (RAngle div 90) * 90;
1738 end
1739 else if not WordBool(mr and MOVE_INWATER) then
1740 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1741 end;
1743 if (Obj.Vel.X >= 0) then
1744 begin // Clockwise
1745 RAngle := RAngle + Abs(Obj.Vel.X)*8 + Abs(Obj.Vel.Y);
1746 if RAngle >= 360 then
1747 RAngle := RAngle mod 360;
1748 end else begin // Counter-clockwise
1749 RAngle := RAngle - Abs(Obj.Vel.X)*8 - Abs(Obj.Vel.Y);
1750 if RAngle < 0 then
1751 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1752 end;
1753 end;
1754 end;
1757 procedure TGib.getMapBox (out x, y, w, h: Integer); inline;
1758 begin
1759 x := Obj.X+Obj.Rect.X;
1760 y := Obj.Y+Obj.Rect.Y;
1761 w := Obj.Rect.Width;
1762 h := Obj.Rect.Height;
1763 end;
1765 procedure TGib.moveBy (dx, dy: Integer); inline;
1766 begin
1767 if (dx <> 0) or (dy <> 0) then
1768 begin
1769 Obj.X += dx;
1770 Obj.Y += dy;
1771 positionChanged();
1772 end;
1773 end;
1776 procedure TShell.getMapBox (out x, y, w, h: Integer); inline;
1777 begin
1778 x := Obj.X;
1779 y := Obj.Y;
1780 w := Obj.Rect.Width;
1781 h := Obj.Rect.Height;
1782 end;
1784 procedure TShell.moveBy (dx, dy: Integer); inline;
1785 begin
1786 if (dx <> 0) or (dy <> 0) then
1787 begin
1788 Obj.X += dx;
1789 Obj.Y += dy;
1790 positionChanged();
1791 end;
1792 end;
1795 procedure TGib.positionChanged (); inline; begin end;
1796 procedure TShell.positionChanged (); inline; begin end;
1799 procedure g_Player_RemoveAllCorpses();
1800 var
1801 i: Integer;
1802 begin
1803 gGibs := nil;
1804 gShells := nil;
1805 SetLength(gGibs, MaxGibs);
1806 SetLength(gShells, MaxGibs);
1807 CurrentGib := 0;
1808 CurrentShell := 0;
1810 if gCorpses <> nil then
1811 for i := 0 to High(gCorpses) do
1812 gCorpses[i].Free();
1814 gCorpses := nil;
1815 SetLength(gCorpses, MaxCorpses);
1816 end;
1818 procedure g_Player_Corpses_SaveState (st: TStream);
1819 var
1820 count, i: Integer;
1821 begin
1822 // Считаем количество существующих трупов
1823 count := 0;
1824 for i := 0 to High(gCorpses) do if (gCorpses[i] <> nil) then Inc(count);
1826 // Количество трупов
1827 utils.writeInt(st, LongInt(count));
1829 if (count = 0) then exit;
1831 // Сохраняем трупы
1832 for i := 0 to High(gCorpses) do
1833 begin
1834 if gCorpses[i] <> nil then
1835 begin
1836 // Название модели
1837 utils.writeStr(st, gCorpses[i].FModelName);
1838 // Тип смерти
1839 utils.writeBool(st, gCorpses[i].Mess);
1840 // Сохраняем данные трупа:
1841 gCorpses[i].SaveState(st);
1842 end;
1843 end;
1844 end;
1847 procedure g_Player_Corpses_LoadState (st: TStream);
1848 var
1849 count, i: Integer;
1850 str: String;
1851 b: Boolean;
1852 begin
1853 assert(st <> nil);
1855 g_Player_RemoveAllCorpses();
1857 // Количество трупов:
1858 count := utils.readLongInt(st);
1859 if (count < 0) or (count > Length(gCorpses)) then raise XStreamError.Create('invalid number of corpses');
1861 if (count = 0) then exit;
1863 // Загружаем трупы
1864 for i := 0 to count-1 do
1865 begin
1866 // Название модели:
1867 str := utils.readStr(st);
1868 // Тип смерти
1869 b := utils.readBool(st);
1870 // Создаем труп
1871 gCorpses[i] := TCorpse.Create(0, 0, str, b);
1872 // Загружаем данные трупа
1873 gCorpses[i].LoadState(st);
1874 end;
1875 end;
1878 { T P l a y e r : }
1880 function TPlayer.isValidViewPort (): Boolean; inline; begin result := (viewPortW > 0) and (viewPortH > 0); end;
1882 procedure TPlayer.BFGHit();
1883 begin
1884 g_Weapon_BFGHit(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1885 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2));
1886 if g_Game_IsServer and g_Game_IsNet then
1887 MH_SEND_Effect(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1888 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
1889 0, NET_GFX_BFGHIT);
1890 end;
1892 procedure TPlayer.ChangeModel(ModelName: string);
1893 var
1894 locModel: TPlayerModel;
1895 begin
1896 locModel := g_PlayerModel_Get(ModelName);
1897 if locModel = nil then Exit;
1899 FModel.Free();
1900 FModel := locModel;
1901 end;
1903 procedure TPlayer.SetModel(ModelName: string);
1904 var
1905 m: TPlayerModel;
1906 begin
1907 m := g_PlayerModel_Get(ModelName);
1908 if m = nil then
1909 begin
1910 g_SimpleError(Format(_lc[I_GAME_ERROR_MODEL_FALLBACK], [ModelName]));
1911 m := g_PlayerModel_Get('doomer');
1912 if m = nil then
1913 begin
1914 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], ['doomer']));
1915 Exit;
1916 end;
1917 end;
1919 if FModel <> nil then
1920 FModel.Free();
1922 FModel := m;
1924 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1925 FModel.Color := FColor
1926 else
1927 FModel.Color := TEAMCOLOR[FTeam];
1928 FModel.SetWeapon(FCurrWeap);
1929 FModel.SetFlag(FFlag);
1930 SetDirection(FDirection);
1931 end;
1933 procedure TPlayer.SetColor(Color: TRGB);
1934 begin
1935 FColor := Color;
1936 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1937 if FModel <> nil then FModel.Color := Color;
1938 end;
1942 function TPlayer.GetColor(): TRGB;
1943 begin
1944 result := FModel.Color;
1945 end;
1947 procedure TPlayer.SetWeaponPrefs(Prefs: Array of Byte);
1948 var
1949 i: Integer;
1950 begin
1951 for i := WP_FIRST to WP_LAST + 1 do
1952 begin
1953 if (Prefs[i] > WP_LAST + 1) then
1954 FWeapPreferences[i] := 0
1955 else
1956 FWeapPreferences[i] := Prefs[i];
1957 end;
1958 end;
1960 procedure TPlayer.SetWeaponPref(Weapon, Pref: Byte);
1961 begin
1962 if (Weapon > WP_LAST + 1) then
1963 exit
1964 else if (Pref <= WP_LAST + 1) and (Weapon <= WP_LAST + 1) then
1965 FWeapPreferences[Weapon] := Pref
1966 else if (Weapon <= WP_LAST + 1) and (Pref > WP_LAST + 1) then
1967 FWeapPreferences[Weapon] := 0;
1968 end;
1970 function TPlayer.GetWeaponPref(Weapon: Byte) : Byte;
1971 begin
1972 if (Weapon > WP_LAST + 1) then
1973 result := 0
1974 else if (FWeapPreferences[Weapon] > WP_LAST + 1) then
1975 result := 0
1976 else
1977 result := FWeapPreferences[Weapon];
1978 end;
1980 function TPlayer.GetMorePrefered() : Byte;
1981 var
1982 testedWeap, i: Byte;
1983 begin
1984 testedWeap := FCurrWeap;
1985 for i := WP_FIRST to WP_LAST do
1986 if FWeapon[i] and maySwitch(i) and (FWeapPreferences[i] > FWeapPreferences[testedWeap]) then
1987 testedWeap := i;
1988 if (R_BERSERK in FRulez) and (FWeapPreferences[WP_LAST + 1] > FWeapPreferences[testedWeap]) then
1989 testedWeap := WEAPON_KASTET;
1990 result := testedWeap;
1991 end;
1993 function TPlayer.maySwitch(Weapon: Byte) : Boolean;
1994 begin
1995 result := true;
1996 if (Weapon = WEAPON_KASTET) and (FSkipFist <> 0) then
1997 begin
1998 if (FSkipFist = 1) and (not (R_BERSERK in FRulez)) then
1999 result := false;
2000 end
2001 else if (FSwitchToEmpty = 0) and (not hasAmmoForShooting(Weapon)) then
2002 result := false;
2003 end;
2005 procedure TPlayer.SwitchTeam;
2006 begin
2007 if g_Game_IsClient then
2008 Exit;
2009 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then Exit;
2011 if gGameOn and FAlive then
2012 Kill(K_SIMPLEKILL, FUID, HIT_SELF);
2014 if FTeam = TEAM_RED then
2015 begin
2016 ChangeTeam(TEAM_BLUE);
2017 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_BLUE], [FName]), True);
2018 if g_Game_IsNet then
2019 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_BLUE, FName);
2020 end
2021 else
2022 begin
2023 ChangeTeam(TEAM_RED);
2024 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_RED], [FName]), True);
2025 if g_Game_IsNet then
2026 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_RED, FName);
2027 end;
2028 FPreferredTeam := FTeam;
2029 end;
2031 procedure TPlayer.ChangeTeam(Team: Byte);
2032 var
2033 OldTeam: Byte;
2034 begin
2035 OldTeam := FTeam;
2036 FTeam := Team;
2037 case Team of
2038 TEAM_RED, TEAM_BLUE:
2039 FModel.Color := TEAMCOLOR[Team];
2040 else
2041 FModel.Color := FColor;
2042 end;
2043 if (FTeam <> OldTeam) and g_Game_IsNet and g_Game_IsServer then
2044 MH_SEND_PlayerStats(FUID);
2045 end;
2048 procedure TPlayer.CollideItem();
2049 var
2050 i: Integer;
2051 r: Boolean;
2052 begin
2053 if gItems = nil then Exit;
2054 if not FAlive then Exit;
2056 for i := 0 to High(gItems) do
2057 with gItems[i] do
2058 begin
2059 if (ItemType <> ITEM_NONE) and alive then
2060 if g_Obj_Collide(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
2061 PLAYER_RECT.Height, @Obj) then
2062 begin
2063 if not PickItem(ItemType, gItems[i].Respawnable, r) then Continue;
2065 if ItemType in [ITEM_SPHERE_BLUE, ITEM_SPHERE_WHITE, ITEM_INVUL] then
2066 g_Sound_PlayExAt('SOUND_ITEM_GETRULEZ', FObj.X, FObj.Y)
2067 else if ItemType in [ITEM_MEDKIT_SMALL, ITEM_MEDKIT_LARGE, ITEM_MEDKIT_BLACK] then
2068 g_Sound_PlayExAt('SOUND_ITEM_GETMED', FObj.X, FObj.Y)
2069 else g_Sound_PlayExAt('SOUND_ITEM_GETITEM', FObj.X, FObj.Y);
2071 // Надо убрать с карты, если это не ключ, которым нужно поделится с другим игроком:
2072 if r and not ((ItemType in [ITEM_KEY_RED, ITEM_KEY_GREEN, ITEM_KEY_BLUE]) and
2073 (gGameSettings.GameType = GT_SINGLE) and
2074 (g_Player_GetCount() > 1)) then
2075 if not Respawnable then g_Items_Remove(i) else g_Items_Pick(i);
2076 end;
2077 end;
2078 end;
2081 function TPlayer.CollideLevel(XInc, YInc: Integer): Boolean;
2082 begin
2083 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
2084 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_WALL,
2085 False);
2086 end;
2088 constructor TPlayer.Create();
2089 begin
2090 viewPortX := 0;
2091 viewPortY := 0;
2092 viewPortW := 0;
2093 viewPortH := 0;
2094 mEDamageType := HIT_SOME;
2096 FIamBot := False;
2097 FDummy := False;
2098 FSpawned := False;
2100 FSawSound := TPlayableSound.Create();
2101 FSawSoundIdle := TPlayableSound.Create();
2102 FSawSoundHit := TPlayableSound.Create();
2103 FSawSoundSelect := TPlayableSound.Create();
2104 FFlameSoundOn := TPlayableSound.Create();
2105 FFlameSoundOff := TPlayableSound.Create();
2106 FFlameSoundWork := TPlayableSound.Create();
2107 FJetSoundFly := TPlayableSound.Create();
2108 FJetSoundOn := TPlayableSound.Create();
2109 FJetSoundOff := TPlayableSound.Create();
2111 FSawSound.SetByName('SOUND_WEAPON_FIRESAW');
2112 FSawSoundIdle.SetByName('SOUND_WEAPON_IDLESAW');
2113 FSawSoundHit.SetByName('SOUND_WEAPON_HITSAW');
2114 FSawSoundSelect.SetByName('SOUND_WEAPON_SELECTSAW');
2115 FFlameSoundOn.SetByName('SOUND_WEAPON_FLAMEON');
2116 FFlameSoundOff.SetByName('SOUND_WEAPON_FLAMEOFF');
2117 FFlameSoundWork.SetByName('SOUND_WEAPON_FLAMEWORK');
2118 FJetSoundFly.SetByName('SOUND_PLAYER_JETFLY');
2119 FJetSoundOn.SetByName('SOUND_PLAYER_JETON');
2120 FJetSoundOff.SetByName('SOUND_PLAYER_JETOFF');
2122 FSpectatePlayer := -1;
2123 FClientID := -1;
2124 FPing := 0;
2125 FLoss := 0;
2126 FSavedStateNum := -1;
2127 FShellTimer := -1;
2128 FFireTime := 0;
2129 FFirePainTime := 0;
2130 FFireAttacker := 0;
2131 FHandicap := 100;
2132 FCorpse := -1;
2134 FActualModelName := 'doomer';
2136 g_Obj_Init(@FObj);
2137 FObj.Rect := PLAYER_RECT;
2139 FBFGFireCounter := -1;
2140 FJustTeleported := False;
2141 FNetTime := 0;
2143 FWaitForFirstSpawn := false;
2145 resetWeaponQueue();
2146 end;
2148 procedure TPlayer.positionChanged (); inline;
2149 begin
2150 end;
2152 procedure TPlayer.doDamage (v: Integer);
2153 begin
2154 if (v <= 0) then exit;
2155 if (v > 32767) then v := 32767;
2156 Damage(v, 0, 0, 0, mEDamageType);
2157 end;
2159 procedure TPlayer.Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte);
2160 var
2161 c: Word;
2162 begin
2163 if (not g_Game_IsClient) and (not FAlive) then
2164 Exit;
2166 FLastHit := t;
2168 // Неуязвимость не спасает от ловушек:
2169 if ((t = HIT_TRAP) or (t = HIT_SELF)) and (not FGodMode) then
2170 begin
2171 if not g_Game_IsClient then
2172 begin
2173 FArmor := 0;
2174 if t = HIT_TRAP then
2175 begin
2176 // Ловушка убивает сразу:
2177 FHealth := -100;
2178 Kill(K_EXTRAHARDKILL, SpawnerUID, t);
2179 end;
2180 if t = HIT_SELF then
2181 begin
2182 // Самоубийство:
2183 FHealth := 0;
2184 Kill(K_SIMPLEKILL, SpawnerUID, t);
2185 end;
2186 end;
2187 // Обнулить действия примочек, чтобы фон пропал
2188 FMegaRulez[MR_SUIT] := 0;
2189 FMegaRulez[MR_INVUL] := 0;
2190 FMegaRulez[MR_INVIS] := 0;
2191 FSpawnInvul := 0;
2192 FBerserk := 0;
2193 end;
2195 // Но от остального спасает:
2196 if FMegaRulez[MR_INVUL] >= gTime then
2197 Exit;
2199 // Чит-код "ГОРЕЦ":
2200 if FGodMode then
2201 Exit;
2203 // Если есть урон своим, или ранил сам себя, или тебя ранил противник:
2204 if LongBool(gGameSettings.Options and GAME_OPTION_TEAMDAMAGE) or
2205 (SpawnerUID = FUID) or
2206 (not SameTeam(FUID, SpawnerUID)) then
2207 begin
2208 FLastSpawnerUID := SpawnerUID;
2210 // Кровь (пузырьки, если в воде):
2211 if gBloodCount > 0 then
2212 begin
2213 c := Min(value, 200)*gBloodCount + Random(Min(value, 200) div 2);
2214 if value div 4 <= c then
2215 c := c - (value div 4)
2216 else
2217 c := 0;
2219 if (t = HIT_SOME) and (vx = 0) and (vy = 0) then
2220 MakeBloodSimple(c)
2221 else
2222 case t of
2223 HIT_TRAP, HIT_ACID, HIT_FLAME, HIT_SELF: MakeBloodSimple(c);
2224 HIT_BFG, HIT_ROCKET, HIT_SOME: MakeBloodVector(c, vx, vy);
2225 end;
2227 if t = HIT_WATER then
2228 begin
2229 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
2230 FObj.Y+PLAYER_RECT.Y-4, value div 2, 8, 4);
2231 if Random(2) = 0
2232 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
2233 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
2234 end;
2235 end;
2237 // Буфер урона:
2238 if FAlive then
2239 Inc(FDamageBuffer, value);
2241 // Вспышка боли:
2242 if gFlash <> 0 then
2243 FPain := FPain + value;
2244 end;
2246 if g_Game_IsServer and g_Game_IsNet then
2247 begin
2248 MH_SEND_PlayerDamage(FUID, t, SpawnerUID, value, vx, vy);
2249 MH_SEND_PlayerStats(FUID);
2250 MH_SEND_PlayerPos(False, FUID);
2251 end;
2252 end;
2254 function TPlayer.Heal(value: Word; Soft: Boolean): Boolean;
2255 begin
2256 Result := False;
2257 if g_Game_IsClient then
2258 Exit;
2259 if not FAlive then
2260 Exit;
2262 if Soft and (FHealth < PLAYER_HP_SOFT) then
2263 begin
2264 IncMax(FHealth, value, PLAYER_HP_SOFT);
2265 Result := True;
2266 end;
2267 if (not Soft) and (FHealth < PLAYER_HP_LIMIT) then
2268 begin
2269 IncMax(FHealth, value, PLAYER_HP_LIMIT);
2270 Result := True;
2271 end;
2273 if Result and g_Game_IsServer and g_Game_IsNet then
2274 MH_SEND_PlayerStats(FUID);
2275 end;
2277 destructor TPlayer.Destroy();
2278 begin
2279 if (gPlayer1 <> nil) and (gPlayer1.FUID = FUID) then
2280 gPlayer1 := nil;
2281 if (gPlayer2 <> nil) and (gPlayer2.FUID = FUID) then
2282 gPlayer2 := nil;
2284 FSawSound.Free();
2285 FSawSoundIdle.Free();
2286 FSawSoundHit.Free();
2287 FSawSoundSelect.Free();
2288 FFlameSoundOn.Free();
2289 FFlameSoundOff.Free();
2290 FFlameSoundWork.Free();
2291 FJetSoundFly.Free();
2292 FJetSoundOn.Free();
2293 FJetSoundOff.Free();
2294 FModel.Free();
2295 if FPunchAnim <> nil then
2296 FPunchAnim.Free();
2298 inherited;
2299 end;
2301 procedure TPlayer.DoPunch();
2302 var
2303 id: DWORD;
2304 st: String;
2305 begin
2306 if FPunchAnim <> nil then begin
2307 FPunchAnim.reset();
2308 FPunchAnim.Free;
2309 FPunchAnim := nil;
2310 end;
2311 st := 'FRAMES_PUNCH';
2312 if R_BERSERK in FRulez then
2313 st := st + '_BERSERK';
2314 if FKeys[KEY_UP].Pressed then
2315 st := st + '_UP'
2316 else if FKeys[KEY_DOWN].Pressed then
2317 st := st + '_DN';
2318 g_Frames_Get(id, st);
2319 FPunchAnim := TAnimation.Create(id, False, 1);
2320 end;
2322 procedure TPlayer.Fire();
2323 var
2324 f, DidFire: Boolean;
2325 wx, wy, xd, yd: Integer;
2326 locobj: TObj;
2327 begin
2328 if g_Game_IsClient then Exit;
2329 // FBFGFireCounter - время перед выстрелом (для BFG)
2330 // FReloading - время после выстрела (для всего)
2332 if FSpectator then
2333 begin
2334 Respawn(False);
2335 Exit;
2336 end;
2338 if FReloading[FCurrWeap] <> 0 then Exit;
2340 DidFire := False;
2342 f := False;
2343 wx := FObj.X+WEAPONPOINT[FDirection].X;
2344 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
2345 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
2346 yd := wy+firediry();
2348 case FCurrWeap of
2349 WEAPON_KASTET:
2350 begin
2351 DoPunch();
2352 if R_BERSERK in FRulez then
2353 begin
2354 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
2355 locobj.X := FObj.X+FObj.Rect.X;
2356 locobj.Y := FObj.Y+FObj.Rect.Y;
2357 locobj.rect.X := 0;
2358 locobj.rect.Y := 0;
2359 locobj.rect.Width := 39;
2360 locobj.rect.Height := 52;
2361 locobj.Vel.X := (xd-wx) div 2;
2362 locobj.Vel.Y := (yd-wy) div 2;
2363 locobj.Accel.X := xd-wx;
2364 locobj.Accel.y := yd-wy;
2366 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
2367 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
2368 else
2369 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
2371 if (gFlash = 1) and (FPain < 50) then FPain := min(FPain + 25, 50);
2372 end
2373 else
2374 begin
2375 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
2376 end;
2378 DidFire := True;
2379 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2380 end;
2382 WEAPON_SAW:
2383 begin
2384 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
2385 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
2386 begin
2387 FSawSoundSelect.Stop();
2388 FSawSound.Stop();
2389 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
2390 end
2391 else if not FSawSoundHit.IsPlaying() then
2392 begin
2393 FSawSoundSelect.Stop();
2394 FSawSound.PlayAt(FObj.X, FObj.Y);
2395 end;
2397 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2398 DidFire := True;
2399 f := True;
2400 end;
2402 WEAPON_PISTOL:
2403 if FAmmo[A_BULLETS] > 0 then
2404 begin
2405 g_Weapon_pistol(wx, wy, xd, yd, FUID);
2406 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2407 Dec(FAmmo[A_BULLETS]);
2408 FFireAngle := FAngle;
2409 f := True;
2410 DidFire := True;
2411 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2412 GameVelX, GameVelY-2, SHELL_BULLET);
2413 end;
2415 WEAPON_SHOTGUN1:
2416 if FAmmo[A_SHELLS] > 0 then
2417 begin
2418 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2419 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', wx, wy);
2420 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2421 Dec(FAmmo[A_SHELLS]);
2422 FFireAngle := FAngle;
2423 f := True;
2424 DidFire := True;
2425 FShellTimer := 10;
2426 FShellType := SHELL_SHELL;
2427 end;
2429 WEAPON_SHOTGUN2:
2430 if FAmmo[A_SHELLS] >= 2 then
2431 begin
2432 g_Weapon_dshotgun(wx, wy, xd, yd, FUID);
2433 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2434 Dec(FAmmo[A_SHELLS], 2);
2435 FFireAngle := FAngle;
2436 f := True;
2437 DidFire := True;
2438 FShellTimer := 13;
2439 FShellType := SHELL_DBLSHELL;
2440 end;
2442 WEAPON_CHAINGUN:
2443 if FAmmo[A_BULLETS] > 0 then
2444 begin
2445 g_Weapon_mgun(wx, wy, xd, yd, FUID);
2446 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', wx, wy);
2447 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2448 Dec(FAmmo[A_BULLETS]);
2449 FFireAngle := FAngle;
2450 f := True;
2451 DidFire := True;
2452 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2453 GameVelX, GameVelY-2, SHELL_BULLET);
2454 end;
2456 WEAPON_ROCKETLAUNCHER:
2457 if FAmmo[A_ROCKETS] > 0 then
2458 begin
2459 g_Weapon_rocket(wx, wy, xd, yd, FUID);
2460 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2461 Dec(FAmmo[A_ROCKETS]);
2462 FFireAngle := FAngle;
2463 f := True;
2464 DidFire := True;
2465 end;
2467 WEAPON_PLASMA:
2468 if FAmmo[A_CELLS] > 0 then
2469 begin
2470 g_Weapon_plasma(wx, wy, xd, yd, FUID);
2471 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2472 Dec(FAmmo[A_CELLS]);
2473 FFireAngle := FAngle;
2474 f := True;
2475 DidFire := True;
2476 end;
2478 WEAPON_BFG:
2479 if (FAmmo[A_CELLS] >= 40) and (FBFGFireCounter = -1) then
2480 begin
2481 FBFGFireCounter := 17;
2482 if not FNoReload then
2483 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', FObj.X, FObj.Y);
2484 Dec(FAmmo[A_CELLS], 40);
2485 DidFire := True;
2486 end;
2488 WEAPON_SUPERPULEMET:
2489 if FAmmo[A_SHELLS] > 0 then
2490 begin
2491 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2492 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', wx, wy);
2493 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2494 Dec(FAmmo[A_SHELLS]);
2495 FFireAngle := FAngle;
2496 f := True;
2497 DidFire := True;
2498 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2499 GameVelX, GameVelY-2, SHELL_SHELL);
2500 end;
2502 WEAPON_FLAMETHROWER:
2503 if FAmmo[A_FUEL] > 0 then
2504 begin
2505 g_Weapon_flame(wx, wy, xd, yd, FUID);
2506 FlamerOn;
2507 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2508 Dec(FAmmo[A_FUEL]);
2509 FFireAngle := FAngle;
2510 f := True;
2511 DidFire := True;
2512 end
2513 else
2514 begin
2515 FlamerOff;
2516 if g_Game_IsNet and g_Game_IsServer then MH_SEND_PlayerStats(FUID);
2517 end;
2518 end;
2520 if g_Game_IsNet then
2521 begin
2522 if DidFire then
2523 begin
2524 if FCurrWeap <> WEAPON_BFG then
2525 MH_SEND_PlayerFire(FUID, FCurrWeap, wx, wy, xd, yd, LastShotID)
2526 else
2527 if not FNoReload then
2528 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_WEAPON_STARTFIREBFG');
2529 end;
2531 MH_SEND_PlayerStats(FUID);
2532 end;
2534 if not f then Exit;
2536 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
2537 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
2538 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
2539 end;
2541 function TPlayer.GetAmmoByWeapon(Weapon: Byte): Word;
2542 begin
2543 case Weapon of
2544 WEAPON_PISTOL, WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS];
2545 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS];
2546 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS];
2547 WEAPON_PLASMA, WEAPON_BFG: Result := FAmmo[A_CELLS];
2548 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL];
2549 else Result := 0;
2550 end;
2551 end;
2553 function TPlayer.HeadInLiquid(XInc, YInc: Integer): Boolean;
2554 begin
2555 Result := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X+XInc, FObj.Y+PLAYER_HEADRECT.Y+YInc,
2556 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
2557 PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, True);
2558 end;
2560 procedure TPlayer.FlamerOn;
2561 begin
2562 FFlameSoundOff.Stop();
2563 FFlameSoundOff.SetPosition(0);
2564 if FFlaming then
2565 begin
2566 if (not FFlameSoundOn.IsPlaying()) and (not FFlameSoundWork.IsPlaying()) then
2567 FFlameSoundWork.PlayAt(FObj.X, FObj.Y);
2568 end
2569 else
2570 begin
2571 FFlameSoundOn.PlayAt(FObj.X, FObj.Y);
2572 FFlaming := True;
2573 end;
2574 end;
2576 procedure TPlayer.FlamerOff;
2577 begin
2578 if FFlaming then
2579 begin
2580 FFlameSoundOn.Stop();
2581 FFlameSoundOn.SetPosition(0);
2582 FFlameSoundWork.Stop();
2583 FFlameSoundWork.SetPosition(0);
2584 FFlameSoundOff.PlayAt(FObj.X, FObj.Y);
2585 FFlaming := False;
2586 end;
2587 end;
2589 procedure TPlayer.JetpackOn;
2590 begin
2591 FJetSoundFly.Stop;
2592 FJetSoundOff.Stop;
2593 FJetSoundOn.SetPosition(0);
2594 FJetSoundOn.PlayAt(FObj.X, FObj.Y);
2595 FlySmoke(8);
2596 end;
2598 procedure TPlayer.JetpackOff;
2599 begin
2600 FJetSoundFly.Stop;
2601 FJetSoundOn.Stop;
2602 FJetSoundOff.SetPosition(0);
2603 FJetSoundOff.PlayAt(FObj.X, FObj.Y);
2604 end;
2606 procedure TPlayer.CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
2607 begin
2608 if Timeout <= 0 then
2609 exit;
2610 if (FMegaRulez[MR_SUIT] > gTime) or (FMegaRulez[MR_INVUL] > gTime) then
2611 exit; // Не загораемся когда есть защита
2612 if g_Obj_CollidePanel(@FObj, 0, 0, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2) then
2613 exit; // Не подгораем в воде на всякий случай
2614 if FFireTime <= 0 then
2615 g_Sound_PlayExAt('SOUND_IGNITE', FObj.X, FObj.Y);
2616 FFireTime := Timeout;
2617 FFireAttacker := Attacker;
2618 if g_Game_IsNet and g_Game_IsServer then
2619 MH_SEND_PlayerStats(FUID);
2620 end;
2622 procedure TPlayer.Jump();
2623 begin
2624 if gFly or FJetpack then
2625 begin
2626 // Полет (чит-код или джетпак):
2627 if FObj.Vel.Y > -VEL_FLY then
2628 FObj.Vel.Y := FObj.Vel.Y - 3;
2629 if FJetpack then
2630 begin
2631 if FJetFuel > 0 then
2632 Dec(FJetFuel);
2633 if (FJetFuel < 1) and g_Game_IsServer then
2634 begin
2635 FJetpack := False;
2636 JetpackOff;
2637 if g_Game_IsNet then
2638 MH_SEND_PlayerStats(FUID);
2639 end;
2640 end;
2641 Exit;
2642 end;
2644 // Не включать джетпак в режиме прохождения сквозь стены
2645 if FGhost then
2646 FCanJetpack := False;
2648 // Прыгаем или всплываем:
2649 if (CollideLevel(0, 1) or
2650 g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y+36, PLAYER_RECT.Width,
2651 PLAYER_RECT.Height-33, PANEL_STEP, False)
2652 ) and (FObj.Accel.Y = 0) then // Не прыгать, если есть вертикальное ускорение
2653 begin
2654 FObj.Vel.Y := -VEL_JUMP;
2655 FCanJetpack := False;
2656 end
2657 else
2658 begin
2659 if BodyInLiquid(0, 0) then
2660 FObj.Vel.Y := -VEL_SW
2661 else if (FJetFuel > 0) and FCanJetpack and
2662 g_Game_IsServer and (not g_Obj_CollideLiquid(@FObj, 0, 0)) then
2663 begin
2664 FJetpack := True;
2665 JetpackOn;
2666 if g_Game_IsNet then
2667 MH_SEND_PlayerStats(FUID);
2668 end;
2669 end;
2670 end;
2672 procedure TPlayer.Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
2673 var
2674 a, i, k, ab, ar: Byte;
2675 s: String;
2676 mon: TMonster;
2677 plr: TPlayer;
2678 srv, netsrv: Boolean;
2679 DoFrags: Boolean;
2680 OldLR: Byte;
2681 KP: TPlayer;
2682 it: PItem;
2684 procedure PushItem(t: Byte);
2685 var
2686 id: DWORD;
2687 begin
2688 id := g_Items_Create(FObj.X, FObj.Y, t, True, False);
2689 it := g_Items_ByIdx(id);
2690 if KillType = K_EXTRAHARDKILL then // -7..+7; -8..0
2691 begin
2692 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-7+Random(15),
2693 (FObj.Vel.Y div 2)-Random(9));
2694 it.positionChanged(); // this updates spatial accelerators
2695 end
2696 else
2697 begin
2698 if KillType = K_HARDKILL then // -5..+5; -5..0
2699 begin
2700 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-5+Random(11),
2701 (FObj.Vel.Y div 2)-Random(6));
2702 end
2703 else // -3..+3; -3..0
2704 begin
2705 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-3+Random(7),
2706 (FObj.Vel.Y div 2)-Random(4));
2707 end;
2708 it.positionChanged(); // this updates spatial accelerators
2709 end;
2711 if g_Game_IsNet and g_Game_IsServer then
2712 MH_SEND_ItemSpawn(True, id);
2713 end;
2715 begin
2716 DoFrags := (gGameSettings.MaxLives = 0) or (gGameSettings.GameMode = GM_COOP);
2717 Srv := g_Game_IsServer;
2718 Netsrv := g_Game_IsServer and g_Game_IsNet;
2719 if Srv then FDeath := FDeath + 1;
2720 if FAlive then
2721 begin
2722 if FGhost then
2723 FGhost := False;
2724 if not FPhysics then
2725 FPhysics := True;
2726 FAlive := False;
2727 end;
2728 FShellTimer := -1;
2730 if (gGameSettings.MaxLives > 0) and Srv and (gLMSRespawn = LMS_RESPAWN_NONE) then
2731 begin
2732 if FLives > 0 then FLives := FLives - 1;
2733 if FLives = 0 then FNoRespawn := True;
2734 end;
2736 // Номер типа смерти:
2737 a := 1;
2738 case KillType of
2739 K_SIMPLEKILL: a := 1;
2740 K_HARDKILL: a := 2;
2741 K_EXTRAHARDKILL: a := 3;
2742 K_FALLKILL: a := 4;
2743 end;
2745 // Звук смерти:
2746 if not FModel.PlaySound(MODELSOUND_DIE, a, FObj.X, FObj.Y) then
2747 for i := 1 to 3 do
2748 if FModel.PlaySound(MODELSOUND_DIE, i, FObj.X, FObj.Y) then
2749 Break;
2751 // Время респауна:
2752 if Srv then
2753 case KillType of
2754 K_SIMPLEKILL:
2755 FTime[T_RESPAWN] := gTime + TIME_RESPAWN1;
2756 K_HARDKILL:
2757 FTime[T_RESPAWN] := gTime + TIME_RESPAWN2;
2758 K_EXTRAHARDKILL, K_FALLKILL:
2759 FTime[T_RESPAWN] := gTime + TIME_RESPAWN3;
2760 end;
2762 // Переключаем состояние:
2763 case KillType of
2764 K_SIMPLEKILL:
2765 SetAction(A_DIE1);
2766 K_HARDKILL, K_EXTRAHARDKILL:
2767 SetAction(A_DIE2);
2768 end;
2770 // Реакция монстров на смерть игрока:
2771 if (KillType <> K_FALLKILL) and (Srv) then
2772 g_Monsters_killedp();
2774 if SpawnerUID = FUID then
2775 begin // Самоубился
2776 if Srv then
2777 begin
2778 if gGameSettings.GameMode = GM_TDM then
2779 Dec(gTeamStat[FTeam].Score);
2780 if DoFrags or (gGameSettings.GameMode = GM_TDM) then
2781 begin
2782 Dec(FFrags);
2783 FLastFrag := 0;
2784 end;
2785 end;
2786 g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2787 end
2788 else
2789 if g_GetUIDType(SpawnerUID) = UID_PLAYER then
2790 begin // Убит другим игроком
2791 KP := g_Player_Get(SpawnerUID);
2792 if (KP <> nil) and Srv then
2793 begin
2794 if (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2795 if SameTeam(FUID, SpawnerUID) then
2796 begin
2797 Dec(KP.FFrags);
2798 KP.FLastFrag := 0;
2799 end else
2800 begin
2801 Inc(KP.FFrags);
2802 KP.FragCombo();
2803 end;
2805 if (gGameSettings.GameMode = GM_TDM) and DoFrags then
2806 Inc(gTeamStat[KP.Team].Score,
2807 IfThen(SameTeam(FUID, SpawnerUID), -1, 1));
2809 if netsrv then MH_SEND_PlayerStats(SpawnerUID);
2810 end;
2812 plr := g_Player_Get(SpawnerUID);
2813 if plr = nil then
2814 s := '?'
2815 else
2816 s := plr.FName;
2818 case KillType of
2819 K_HARDKILL:
2820 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2821 [FName, s]),
2822 gShowKillMsg);
2823 K_EXTRAHARDKILL:
2824 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2825 [FName, s]),
2826 gShowKillMsg);
2827 else
2828 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2829 [FName, s]),
2830 gShowKillMsg);
2831 end;
2832 end
2833 else if g_GetUIDType(SpawnerUID) = UID_MONSTER then
2834 begin // Убит монстром
2835 mon := g_Monsters_ByUID(SpawnerUID);
2836 if mon = nil then
2837 s := '?'
2838 else
2839 s := g_Mons_GetKilledByTypeId(mon.MonsterType);
2841 case KillType of
2842 K_HARDKILL:
2843 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2844 [FName, s]),
2845 gShowKillMsg);
2846 K_EXTRAHARDKILL:
2847 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2848 [FName, s]),
2849 gShowKillMsg);
2850 else
2851 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2852 [FName, s]),
2853 gShowKillMsg);
2854 end;
2855 end
2856 else // Особые типы смерти
2857 case t of
2858 HIT_DISCON: ;
2859 HIT_SELF: g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2860 HIT_FALL: g_Console_Add(Format(_lc[I_PLAYER_KILL_FALL], [FName]), True);
2861 HIT_WATER: g_Console_Add(Format(_lc[I_PLAYER_KILL_WATER], [FName]), True);
2862 HIT_ACID: g_Console_Add(Format(_lc[I_PLAYER_KILL_ACID], [FName]), True);
2863 HIT_TRAP: g_Console_Add(Format(_lc[I_PLAYER_KILL_TRAP], [FName]), True);
2864 else g_Console_Add(Format(_lc[I_PLAYER_DIED], [FName]), True);
2865 end;
2867 if Srv then
2868 begin
2869 // Выброс оружия:
2870 for a := WP_FIRST to WP_LAST do
2871 if FWeapon[a] then
2872 begin
2873 case a of
2874 WEAPON_SAW: i := ITEM_WEAPON_SAW;
2875 WEAPON_SHOTGUN1: i := ITEM_WEAPON_SHOTGUN1;
2876 WEAPON_SHOTGUN2: i := ITEM_WEAPON_SHOTGUN2;
2877 WEAPON_CHAINGUN: i := ITEM_WEAPON_CHAINGUN;
2878 WEAPON_ROCKETLAUNCHER: i := ITEM_WEAPON_ROCKETLAUNCHER;
2879 WEAPON_PLASMA: i := ITEM_WEAPON_PLASMA;
2880 WEAPON_BFG: i := ITEM_WEAPON_BFG;
2881 WEAPON_SUPERPULEMET: i := ITEM_WEAPON_SUPERPULEMET;
2882 WEAPON_FLAMETHROWER: i := ITEM_WEAPON_FLAMETHROWER;
2883 else i := 0;
2884 end;
2886 if i <> 0 then
2887 PushItem(i);
2888 end;
2890 // Выброс рюкзака:
2891 if R_ITEM_BACKPACK in FRulez then
2892 PushItem(ITEM_AMMO_BACKPACK);
2894 // Выброс ракетного ранца:
2895 if FJetFuel > 0 then
2896 PushItem(ITEM_JETPACK);
2898 // Выброс ключей:
2899 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) or
2900 (not LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS)) then
2901 begin
2902 if R_KEY_RED in FRulez then
2903 PushItem(ITEM_KEY_RED);
2905 if R_KEY_GREEN in FRulez then
2906 PushItem(ITEM_KEY_GREEN);
2908 if R_KEY_BLUE in FRulez then
2909 PushItem(ITEM_KEY_BLUE);
2910 end;
2912 // Выброс флага:
2913 DropFlag(KillType = K_FALLKILL);
2914 end;
2916 FCorpse := g_Player_CreateCorpse(Self);
2918 if Srv and (gGameSettings.MaxLives > 0) and FNoRespawn and
2919 (gLMSRespawn = LMS_RESPAWN_NONE) then
2920 begin
2921 a := 0;
2922 k := 0;
2923 ar := 0;
2924 ab := 0;
2925 for i := Low(gPlayers) to High(gPlayers) do
2926 begin
2927 if gPlayers[i] = nil then continue;
2928 if (not gPlayers[i].FNoRespawn) and (not gPlayers[i].FSpectator) then
2929 begin
2930 Inc(a);
2931 if gPlayers[i].FTeam = TEAM_RED then Inc(ar)
2932 else if gPlayers[i].FTeam = TEAM_BLUE then Inc(ab);
2933 k := i;
2934 end;
2935 end;
2937 OldLR := gLMSRespawn;
2938 if (gGameSettings.GameMode = GM_COOP) then
2939 begin
2940 if (a = 0) then
2941 begin
2942 // everyone is dead, restart the map
2943 g_Game_Message(_lc[I_MESSAGE_LMS_LOSE], 144);
2944 if Netsrv then
2945 MH_SEND_GameEvent(NET_EV_LMS_LOSE);
2946 gLMSRespawn := LMS_RESPAWN_FINAL;
2947 gLMSRespawnTime := gTime + 5000;
2948 end
2949 else if (a = 1) then
2950 begin
2951 if (gPlayers[k] <> nil) and not (gPlayers[k] is TBot) then
2952 if (gPlayers[k] = gPlayer1) or
2953 (gPlayers[k] = gPlayer2) then
2954 g_Console_Add('*** ' + _lc[I_MESSAGE_LMS_SURVIVOR] + ' ***', True)
2955 else if Netsrv and (gPlayers[k].FClientID >= 0) then
2956 MH_SEND_GameEvent(NET_EV_LMS_SURVIVOR, 0, 'N', gPlayers[k].FClientID);
2957 end;
2958 end
2959 else if (gGameSettings.GameMode = GM_TDM) then
2960 begin
2961 if (ab = 0) and (ar <> 0) then
2962 begin
2963 // blu team ded
2964 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 144);
2965 if Netsrv then
2966 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_RED);
2967 Inc(gTeamStat[TEAM_RED].Score);
2968 gLMSRespawn := LMS_RESPAWN_FINAL;
2969 gLMSRespawnTime := gTime + 5000;
2970 end
2971 else if (ar = 0) and (ab <> 0) then
2972 begin
2973 // red team ded
2974 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 144);
2975 if Netsrv then
2976 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_BLUE);
2977 Inc(gTeamStat[TEAM_BLUE].Score);
2978 gLMSRespawn := LMS_RESPAWN_FINAL;
2979 gLMSRespawnTime := gTime + 5000;
2980 end
2981 else if (ar = 0) and (ab = 0) then
2982 begin
2983 // everyone ded
2984 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2985 if Netsrv then
2986 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2987 gLMSRespawn := LMS_RESPAWN_FINAL;
2988 gLMSRespawnTime := gTime + 5000;
2989 end;
2990 end
2991 else if (gGameSettings.GameMode = GM_DM) then
2992 begin
2993 if (a = 1) then
2994 begin
2995 if gPlayers[k] <> nil then
2996 with gPlayers[k] do
2997 begin
2998 // survivor is the winner
2999 g_Game_Message(Format(_lc[I_MESSAGE_LMS_WIN], [AnsiUpperCase(FName)]), 144);
3000 if Netsrv then
3001 MH_SEND_GameEvent(NET_EV_LMS_WIN, 0, FName);
3002 Inc(FFrags);
3003 end;
3004 gLMSRespawn := LMS_RESPAWN_FINAL;
3005 gLMSRespawnTime := gTime + 5000;
3006 end
3007 else if (a = 0) then
3008 begin
3009 // everyone is dead, restart the map
3010 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
3011 if Netsrv then
3012 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
3013 gLMSRespawn := LMS_RESPAWN_FINAL;
3014 gLMSRespawnTime := gTime + 5000;
3015 end;
3016 end;
3017 if srv and (OldLR = LMS_RESPAWN_NONE) and (gLMSRespawn > LMS_RESPAWN_NONE) then
3018 begin
3019 if NetMode = NET_SERVER then
3020 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime)
3021 else
3022 g_Console_Add(Format(_lc[I_MSG_WARMUP_START], [(gLMSRespawnTime - gTime) div 1000]), True);
3023 end;
3024 end;
3026 if Netsrv then
3027 begin
3028 MH_SEND_PlayerStats(FUID);
3029 MH_SEND_PlayerDeath(FUID, KillType, t, SpawnerUID);
3030 if gGameSettings.GameMode = GM_TDM then MH_SEND_GameStats;
3031 end;
3033 if srv and FNoRespawn then Spectate(True);
3034 FWantsInGame := True;
3035 end;
3037 function TPlayer.BodyInLiquid(XInc, YInc: Integer): Boolean;
3038 begin
3039 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3040 PLAYER_RECT.Height-20, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, False);
3041 end;
3043 function TPlayer.BodyInAcid(XInc, YInc: Integer): Boolean;
3044 begin
3045 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3046 PLAYER_RECT.Height-20, PANEL_ACID1 or PANEL_ACID2, False);
3047 end;
3049 procedure TPlayer.MakeBloodSimple(Count: Word);
3050 begin
3051 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)+8,
3052 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3053 Count div 2, 3, -1, 16, (PLAYER_RECT.Height*2 div 3),
3054 FModel.Blood.R, FModel.Blood.G, FModel.Blood.B, FModel.Blood.Kind);
3055 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-8,
3056 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3057 Count div 2, -3, -1, 16, (PLAYER_RECT.Height*2) div 3,
3058 FModel.Blood.R, FModel.Blood.G, FModel.Blood.B, FModel.Blood.Kind);
3059 end;
3061 procedure TPlayer.MakeBloodVector(Count: Word; VelX, VelY: Integer);
3062 begin
3063 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
3064 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3065 Count, VelX, VelY, 16, (PLAYER_RECT.Height*2) div 3,
3066 FModel.Blood.R, FModel.Blood.G, FModel.Blood.B, FModel.Blood.Kind);
3067 end;
3069 procedure TPlayer.ProcessWeaponAction(Action: Byte);
3070 begin
3071 if g_Game_IsClient then Exit;
3072 case Action of
3073 WP_PREV: PrevWeapon();
3074 WP_NEXT: NextWeapon();
3075 end;
3076 end;
3078 procedure TPlayer.QueueWeaponSwitch(Weapon: Byte);
3079 begin
3080 if g_Game_IsClient then Exit;
3081 if Weapon > High(FWeapon) then Exit;
3082 FNextWeap := FNextWeap or (1 shl Weapon);
3083 end;
3085 procedure TPlayer.resetWeaponQueue ();
3086 begin
3087 FNextWeap := 0;
3088 FNextWeapDelay := 0;
3089 end;
3091 function TPlayer.hasAmmoForWeapon (weapon: Byte): Boolean;
3092 begin
3093 result := false;
3094 case weapon of
3095 WEAPON_KASTET, WEAPON_SAW: result := true;
3096 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3097 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3098 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3099 WEAPON_PLASMA, WEAPON_BFG: result := (FAmmo[A_CELLS] > 0);
3100 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3101 else result := (weapon < length(FWeapon));
3102 end;
3103 end;
3105 function TPlayer.hasAmmoForShooting (weapon: Byte): Boolean;
3106 begin
3107 result := false;
3108 case weapon of
3109 WEAPON_KASTET, WEAPON_SAW: result := true;
3110 WEAPON_SHOTGUN1, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3111 WEAPON_SHOTGUN2: result := (FAmmo[A_SHELLS] > 1);
3112 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3113 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3114 WEAPON_PLASMA: result := (FAmmo[A_CELLS] > 0);
3115 WEAPON_BFG: result := (FAmmo[A_CELLS] >= 40);
3116 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3117 else result := (weapon < length(FWeapon));
3118 end;
3119 end;
3121 function TPlayer.shouldSwitch (weapon: Byte; hadWeapon: Boolean): Boolean;
3122 begin
3123 result := false;
3124 if (weapon > WP_LAST + 1) then
3125 begin
3126 result := false;
3127 exit;
3128 end;
3129 if (FWeapSwitchMode = 1) and not hadWeapon then
3130 result := true
3131 else if (FWeapSwitchMode = 2) then
3132 result := (FWeapPreferences[weapon] > FWeapPreferences[FCurrWeap]);
3133 end;
3135 // return 255 for "no switch"
3136 function TPlayer.getNextWeaponIndex (): Byte;
3137 var
3138 i: Word;
3139 wantThisWeapon: array[0..64] of Boolean;
3140 wwc: Integer = 0; //HACK!
3141 dir, cwi: Integer;
3142 begin
3143 result := 255; // default result: "no switch"
3144 //e_LogWriteFln('FSWITCHTOEMPTY: %s', [FSwitchToEmpty], TMsgType.Notify);
3145 // had weapon cycling on previous frame? remove that flag
3146 if (FNextWeap and $2000) <> 0 then
3147 begin
3148 FNextWeap := FNextWeap and $1FFF;
3149 FNextWeapDelay := 0;
3150 end;
3151 // cycling has priority
3152 if (FNextWeap and $C000) <> 0 then
3153 begin
3154 if (FNextWeap and $8000) <> 0 then
3155 dir := 1
3156 else
3157 dir := -1;
3158 FNextWeap := FNextWeap or $2000; // we need this
3159 if FNextWeapDelay > 0 then
3160 exit; // cooldown time
3161 cwi := FCurrWeap;
3162 for i := 0 to High(FWeapon) do
3163 begin
3164 cwi := (cwi+length(FWeapon)+dir) mod length(FWeapon);
3165 if FWeapon[cwi] and maySwitch(cwi) then
3166 begin
3167 //e_LogWriteFln(' SWITCH: cur=%d; new=%d %s %s', [FCurrWeap, cwi, FSwitchToEmpty, hasAmmoForWeapon(cwi)], TMsgType.Notify);
3168 result := Byte(cwi);
3169 FNextWeapDelay := WEAPON_DELAY;
3170 exit;
3171 end;
3172 end;
3173 resetWeaponQueue();
3174 exit;
3175 end;
3176 // no cycling
3177 for i := 0 to High(wantThisWeapon) do
3178 wantThisWeapon[i] := false;
3179 for i := 0 to High(FWeapon) do
3180 if (FNextWeap and (1 shl i)) <> 0 then
3181 begin
3182 wantThisWeapon[i] := true;
3183 Inc(wwc);
3184 end;
3186 // exclude currently selected weapon from the set
3187 wantThisWeapon[FCurrWeap] := false;
3188 // slow down alterations a little
3189 if wwc > 1 then
3190 begin
3191 //e_WriteLog(Format(' FNextWeap=%x; delay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3192 // more than one weapon requested, assume "alteration" and check alteration delay
3193 if FNextWeapDelay > 0 then
3194 begin
3195 FNextWeap := 0;
3196 exit;
3197 end; // yeah
3198 end;
3199 // do not reset weapon queue, it will be done in `RealizeCurrentWeapon()`
3200 // but clear all counters if no weapon should be switched
3201 if wwc < 1 then
3202 begin
3203 resetWeaponQueue();
3204 exit;
3205 end;
3206 //e_WriteLog(Format('wwc=%d', [wwc]), MSG_WARNING);
3207 // try weapons in descending order
3208 for i := High(FWeapon) downto 0 do
3209 begin
3210 if wantThisWeapon[i] and FWeapon[i] and ((wwc = 1) or hasAmmoForWeapon(i)) then
3211 begin
3212 // i found her!
3213 result := Byte(i);
3214 resetWeaponQueue();
3215 FNextWeapDelay := WEAPON_DELAY * 2; // anyway, 'cause why not
3216 //e_LogWriteFln('FOUND %s %s %s', [result, FSwitchToEmpty, hasAmmoForWeapon(i)], TMsgType.Notify);
3217 exit;
3218 end;
3219 end;
3220 // no suitable weapon found, so reset the queue, to avoid accidental "queuing" of weapon w/o ammo
3221 resetWeaponQueue();
3222 end;
3224 procedure TPlayer.RealizeCurrentWeapon();
3225 function switchAllowed (): Boolean;
3226 var
3227 i: Byte;
3228 begin
3229 result := false;
3230 if FBFGFireCounter <> -1 then
3231 exit;
3232 if FTime[T_SWITCH] > gTime then
3233 exit;
3234 for i := WP_FIRST to WP_LAST do
3235 if FReloading[i] > 0 then
3236 exit;
3237 result := true;
3238 end;
3240 var
3241 nw: Byte;
3242 begin
3243 //e_WriteLog(Format('***RealizeCurrentWeapon: FNextWeap=%x; FNextWeapDelay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3244 //FNextWeap := FNextWeap and $1FFF;
3245 if FNextWeapDelay > 0 then Dec(FNextWeapDelay); // "alteration delay"
3247 if not switchAllowed then
3248 begin
3249 //HACK for weapon cycling
3250 if (FNextWeap and $E000) <> 0 then FNextWeap := 0;
3251 exit;
3252 end;
3254 nw := getNextWeaponIndex();
3255 //
3256 if nw = 255 then exit; // don't reset anything here
3257 if nw > High(FWeapon) then
3258 begin
3259 // don't forget to reset queue here!
3260 //e_WriteLog(' RealizeCurrentWeapon: WUTAFUUUU', MSG_WARNING);
3261 resetWeaponQueue();
3262 exit;
3263 end;
3265 if FWeapon[nw] then
3266 begin
3267 FCurrWeap := nw;
3268 FTime[T_SWITCH] := gTime+156;
3269 if FCurrWeap = WEAPON_SAW then FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3270 FModel.SetWeapon(FCurrWeap);
3271 if g_Game_IsNet then MH_SEND_PlayerStats(FUID);
3272 end;
3273 end;
3275 procedure TPlayer.NextWeapon();
3276 begin
3277 if g_Game_IsClient then Exit;
3278 FNextWeap := $8000;
3279 end;
3281 procedure TPlayer.PrevWeapon();
3282 begin
3283 if g_Game_IsClient then Exit;
3284 FNextWeap := $4000;
3285 end;
3287 procedure TPlayer.SetWeapon(W: Byte);
3288 begin
3289 if FCurrWeap <> W then
3290 if W = WEAPON_SAW then
3291 FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3293 FCurrWeap := W;
3294 FModel.SetWeapon(CurrWeap);
3295 resetWeaponQueue();
3296 end;
3298 function TPlayer.PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean;
3299 var
3300 a: Boolean;
3301 switchWeapon: Byte = 255;
3302 hadWeapon: Boolean = False;
3303 begin
3304 Result := False;
3305 if g_Game_IsClient then Exit;
3307 // a = true - место спавна предмета:
3308 a := LongBool(gGameSettings.Options and GAME_OPTION_WEAPONSTAY) and arespawn;
3309 remove := not a;
3310 case ItemType of
3311 ITEM_MEDKIT_SMALL:
3312 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3313 begin
3314 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
3315 Result := True;
3316 remove := True;
3317 FFireTime := 0;
3318 if gFlash = 2 then Inc(FPickup, 5);
3319 end;
3321 ITEM_MEDKIT_LARGE:
3322 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3323 begin
3324 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
3325 Result := True;
3326 remove := True;
3327 FFireTime := 0;
3328 if gFlash = 2 then Inc(FPickup, 5);
3329 end;
3331 ITEM_ARMOR_GREEN:
3332 if FArmor < PLAYER_AP_SOFT then
3333 begin
3334 FArmor := PLAYER_AP_SOFT;
3335 Result := True;
3336 remove := True;
3337 if gFlash = 2 then Inc(FPickup, 5);
3338 end;
3340 ITEM_ARMOR_BLUE:
3341 if FArmor < PLAYER_AP_LIMIT then
3342 begin
3343 FArmor := PLAYER_AP_LIMIT;
3344 Result := True;
3345 remove := True;
3346 if gFlash = 2 then Inc(FPickup, 5);
3347 end;
3349 ITEM_SPHERE_BLUE:
3350 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3351 begin
3352 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
3353 Result := True;
3354 remove := True;
3355 FFireTime := 0;
3356 if gFlash = 2 then Inc(FPickup, 5);
3357 end;
3359 ITEM_SPHERE_WHITE:
3360 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) or (FFireTime > 0) then
3361 begin
3362 if FHealth < PLAYER_HP_LIMIT then
3363 FHealth := PLAYER_HP_LIMIT;
3364 if FArmor < PLAYER_AP_LIMIT then
3365 FArmor := PLAYER_AP_LIMIT;
3366 Result := True;
3367 remove := True;
3368 FFireTime := 0;
3369 if gFlash = 2 then Inc(FPickup, 5);
3370 end;
3372 ITEM_WEAPON_SAW:
3373 if (not FWeapon[WEAPON_SAW]) or ((not arespawn) and (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) then
3374 begin
3375 hadWeapon := FWeapon[WEAPON_SAW];
3376 switchWeapon := WEAPON_SAW;
3377 FWeapon[WEAPON_SAW] := True;
3378 Result := True;
3379 if gFlash = 2 then Inc(FPickup, 5);
3380 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3381 end;
3383 ITEM_WEAPON_SHOTGUN1:
3384 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN1] then
3385 begin
3386 // Нужно, чтобы не взять все пули сразу:
3387 if a and FWeapon[WEAPON_SHOTGUN1] then Exit;
3388 hadWeapon := FWeapon[WEAPON_SHOTGUN1];
3389 switchWeapon := WEAPON_SHOTGUN1;
3390 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3391 FWeapon[WEAPON_SHOTGUN1] := True;
3392 Result := True;
3393 if gFlash = 2 then Inc(FPickup, 5);
3394 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3395 end;
3397 ITEM_WEAPON_SHOTGUN2:
3398 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN2] then
3399 begin
3400 if a and FWeapon[WEAPON_SHOTGUN2] then Exit;
3401 hadWeapon := FWeapon[WEAPON_SHOTGUN2];
3402 switchWeapon := WEAPON_SHOTGUN2;
3403 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3404 FWeapon[WEAPON_SHOTGUN2] := True;
3405 Result := True;
3406 if gFlash = 2 then Inc(FPickup, 5);
3407 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3408 end;
3410 ITEM_WEAPON_CHAINGUN:
3411 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or not FWeapon[WEAPON_CHAINGUN] then
3412 begin
3413 if a and FWeapon[WEAPON_CHAINGUN] then Exit;
3414 hadWeapon := FWeapon[WEAPON_CHAINGUN];
3415 switchWeapon := WEAPON_CHAINGUN;
3416 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3417 FWeapon[WEAPON_CHAINGUN] := True;
3418 Result := True;
3419 if gFlash = 2 then Inc(FPickup, 5);
3420 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3421 end;
3423 ITEM_WEAPON_ROCKETLAUNCHER:
3424 if (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or not FWeapon[WEAPON_ROCKETLAUNCHER] then
3425 begin
3426 if a and FWeapon[WEAPON_ROCKETLAUNCHER] then Exit;
3427 switchWeapon := WEAPON_ROCKETLAUNCHER;
3428 hadWeapon := FWeapon[WEAPON_ROCKETLAUNCHER];
3429 IncMax(FAmmo[A_ROCKETS], 2, FMaxAmmo[A_ROCKETS]);
3430 FWeapon[WEAPON_ROCKETLAUNCHER] := True;
3431 Result := True;
3432 if gFlash = 2 then Inc(FPickup, 5);
3433 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3434 end;
3436 ITEM_WEAPON_PLASMA:
3437 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_PLASMA] then
3438 begin
3439 if a and FWeapon[WEAPON_PLASMA] then Exit;
3440 switchWeapon := WEAPON_PLASMA;
3441 hadWeapon := FWeapon[WEAPON_PLASMA];
3442 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3443 FWeapon[WEAPON_PLASMA] := True;
3444 Result := True;
3445 if gFlash = 2 then Inc(FPickup, 5);
3446 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3447 end;
3449 ITEM_WEAPON_BFG:
3450 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_BFG] then
3451 begin
3452 if a and FWeapon[WEAPON_BFG] then Exit;
3453 switchWeapon := WEAPON_BFG;
3454 hadWeapon := FWeapon[WEAPON_BFG];
3455 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3456 FWeapon[WEAPON_BFG] := True;
3457 Result := True;
3458 if gFlash = 2 then Inc(FPickup, 5);
3459 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3460 end;
3462 ITEM_WEAPON_SUPERPULEMET:
3463 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SUPERPULEMET] then
3464 begin
3465 if a and FWeapon[WEAPON_SUPERPULEMET] then Exit;
3466 switchWeapon := WEAPON_SUPERPULEMET;
3467 hadWeapon := FWeapon[WEAPON_SUPERPULEMET];
3468 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3469 FWeapon[WEAPON_SUPERPULEMET] := True;
3470 Result := True;
3471 if gFlash = 2 then Inc(FPickup, 5);
3472 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3473 end;
3475 ITEM_WEAPON_FLAMETHROWER:
3476 if (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) or not FWeapon[WEAPON_FLAMETHROWER] then
3477 begin
3478 if a and FWeapon[WEAPON_FLAMETHROWER] then Exit;
3479 switchWeapon := WEAPON_FLAMETHROWER;
3480 hadWeapon := FWeapon[WEAPON_FLAMETHROWER];
3481 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3482 FWeapon[WEAPON_FLAMETHROWER] := True;
3483 Result := True;
3484 if gFlash = 2 then Inc(FPickup, 5);
3485 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3486 end;
3488 ITEM_AMMO_BULLETS:
3489 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3490 begin
3491 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3492 Result := True;
3493 remove := True;
3494 if gFlash = 2 then Inc(FPickup, 5);
3495 end;
3497 ITEM_AMMO_BULLETS_BOX:
3498 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3499 begin
3500 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3501 Result := True;
3502 remove := True;
3503 if gFlash = 2 then Inc(FPickup, 5);
3504 end;
3506 ITEM_AMMO_SHELLS:
3507 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3508 begin
3509 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3510 Result := True;
3511 remove := True;
3512 if gFlash = 2 then Inc(FPickup, 5);
3513 end;
3515 ITEM_AMMO_SHELLS_BOX:
3516 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3517 begin
3518 IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
3519 Result := True;
3520 remove := True;
3521 if gFlash = 2 then Inc(FPickup, 5);
3522 end;
3524 ITEM_AMMO_ROCKET:
3525 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3526 begin
3527 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3528 Result := True;
3529 remove := True;
3530 if gFlash = 2 then Inc(FPickup, 5);
3531 end;
3533 ITEM_AMMO_ROCKET_BOX:
3534 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3535 begin
3536 IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
3537 Result := True;
3538 remove := True;
3539 if gFlash = 2 then Inc(FPickup, 5);
3540 end;
3542 ITEM_AMMO_CELL:
3543 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3544 begin
3545 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3546 Result := True;
3547 remove := True;
3548 if gFlash = 2 then Inc(FPickup, 5);
3549 end;
3551 ITEM_AMMO_CELL_BIG:
3552 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3553 begin
3554 IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
3555 Result := True;
3556 remove := True;
3557 if gFlash = 2 then Inc(FPickup, 5);
3558 end;
3560 ITEM_AMMO_FUELCAN:
3561 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3562 begin
3563 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3564 Result := True;
3565 remove := True;
3566 if gFlash = 2 then Inc(FPickup, 5);
3567 end;
3569 ITEM_AMMO_BACKPACK:
3570 if not(R_ITEM_BACKPACK in FRulez) or
3571 (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
3572 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
3573 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
3574 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
3575 (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) then
3576 begin
3577 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
3578 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
3579 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
3580 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
3581 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
3583 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3584 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3585 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3586 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3587 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3588 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3589 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3590 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3591 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3592 IncMax(FAmmo[A_FUEL], 50, FMaxAmmo[A_FUEL]);
3594 FRulez := FRulez + [R_ITEM_BACKPACK];
3595 Result := True;
3596 remove := True;
3597 if gFlash = 2 then Inc(FPickup, 5);
3598 end;
3600 ITEM_KEY_RED:
3601 if not(R_KEY_RED in FRulez) then
3602 begin
3603 Include(FRulez, R_KEY_RED);
3604 Result := True;
3605 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3606 if gFlash = 2 then Inc(FPickup, 5);
3607 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3608 end;
3610 ITEM_KEY_GREEN:
3611 if not(R_KEY_GREEN in FRulez) then
3612 begin
3613 Include(FRulez, R_KEY_GREEN);
3614 Result := True;
3615 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3616 if gFlash = 2 then Inc(FPickup, 5);
3617 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3618 end;
3620 ITEM_KEY_BLUE:
3621 if not(R_KEY_BLUE in FRulez) then
3622 begin
3623 Include(FRulez, R_KEY_BLUE);
3624 Result := True;
3625 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3626 if gFlash = 2 then Inc(FPickup, 5);
3627 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3628 end;
3630 ITEM_SUIT:
3631 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
3632 begin
3633 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
3634 Result := True;
3635 remove := True;
3636 FFireTime := 0;
3637 if gFlash = 2 then Inc(FPickup, 5);
3638 end;
3640 ITEM_OXYGEN:
3641 if FAir < AIR_MAX then
3642 begin
3643 FAir := AIR_MAX;
3644 Result := True;
3645 remove := True;
3646 if gFlash = 2 then Inc(FPickup, 5);
3647 end;
3649 ITEM_MEDKIT_BLACK:
3650 begin
3651 if not (R_BERSERK in FRulez) then
3652 begin
3653 Include(FRulez, R_BERSERK);
3654 if (FBFGFireCounter = -1) then
3655 begin
3656 FCurrWeap := WEAPON_KASTET;
3657 resetWeaponQueue();
3658 FModel.SetWeapon(WEAPON_KASTET);
3659 end;
3660 if gFlash <> 0 then
3661 begin
3662 Inc(FPain, 100);
3663 if gFlash = 2 then Inc(FPickup, 5);
3664 end;
3665 FBerserk := gTime+30000;
3666 Result := True;
3667 remove := True;
3668 FFireTime := 0;
3669 end;
3670 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3671 begin
3672 if FHealth < PLAYER_HP_SOFT then FHealth := PLAYER_HP_SOFT;
3673 FBerserk := gTime+30000;
3674 Result := True;
3675 remove := True;
3676 FFireTime := 0;
3677 end;
3678 end;
3680 ITEM_INVUL:
3681 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
3682 begin
3683 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
3684 FSpawnInvul := 0;
3685 Result := True;
3686 remove := True;
3687 if gFlash = 2 then Inc(FPickup, 5);
3688 end;
3690 ITEM_BOTTLE:
3691 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3692 begin
3693 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
3694 Result := True;
3695 remove := True;
3696 FFireTime := 0;
3697 if gFlash = 2 then Inc(FPickup, 5);
3698 end;
3700 ITEM_HELMET:
3701 if FArmor < PLAYER_AP_LIMIT then
3702 begin
3703 IncMax(FArmor, 5, PLAYER_AP_LIMIT);
3704 Result := True;
3705 remove := True;
3706 if gFlash = 2 then Inc(FPickup, 5);
3707 end;
3709 ITEM_JETPACK:
3710 if FJetFuel < JET_MAX then
3711 begin
3712 FJetFuel := JET_MAX;
3713 Result := True;
3714 remove := True;
3715 if gFlash = 2 then Inc(FPickup, 5);
3716 end;
3718 ITEM_INVIS:
3719 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
3720 begin
3721 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
3722 Result := True;
3723 remove := True;
3724 if gFlash = 2 then Inc(FPickup, 5);
3725 end;
3726 end;
3728 if (shouldSwitch(switchWeapon, hadWeapon)) then
3729 QueueWeaponSwitch(switchWeapon);
3730 end;
3732 procedure TPlayer.Touch();
3733 begin
3734 if not FAlive then
3735 Exit;
3736 //FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
3737 if FIamBot then
3738 begin
3739 // Бросить флаг товарищу:
3740 if gGameSettings.GameMode = GM_CTF then
3741 DropFlag();
3742 end;
3743 end;
3745 procedure TPlayer.Push(vx, vy: Integer);
3746 begin
3747 if (not FPhysics) and FGhost then
3748 Exit;
3749 FObj.Accel.X := FObj.Accel.X + vx;
3750 FObj.Accel.Y := FObj.Accel.Y + vy;
3751 if g_Game_IsNet and g_Game_IsServer then
3752 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3753 end;
3755 procedure TPlayer.Reset(Force: Boolean);
3756 begin
3757 if Force then
3758 FAlive := False;
3760 FSpawned := False;
3761 FTime[T_RESPAWN] := 0;
3762 FTime[T_FLAGCAP] := 0;
3763 FGodMode := False;
3764 FNoTarget := False;
3765 FNoReload := False;
3766 FFrags := 0;
3767 FLastFrag := 0;
3768 FComboEvnt := -1;
3769 FKills := 0;
3770 FMonsterKills := 0;
3771 FDeath := 0;
3772 FSecrets := 0;
3773 FSpawnInvul := 0;
3774 FCorpse := -1;
3775 FReady := False;
3776 if FNoRespawn then
3777 begin
3778 FSpectator := False;
3779 FGhost := False;
3780 FPhysics := True;
3781 FSpectatePlayer := -1;
3782 FNoRespawn := False;
3783 end;
3784 FLives := gGameSettings.MaxLives;
3786 SetFlag(FLAG_NONE);
3787 end;
3789 procedure TPlayer.SoftReset();
3790 begin
3791 ReleaseKeys();
3793 FDamageBuffer := 0;
3794 FSlopeOld := 0;
3795 FIncCamOld := 0;
3796 FIncCam := 0;
3797 FBFGFireCounter := -1;
3798 FShellTimer := -1;
3799 FPain := 0;
3800 FLastHit := 0;
3801 FLastFrag := 0;
3802 FComboEvnt := -1;
3804 SetFlag(FLAG_NONE);
3805 SetAction(A_STAND, True);
3806 end;
3808 function TPlayer.GetRespawnPoint(): Byte;
3809 var
3810 c: Byte;
3811 begin
3812 Result := 255;
3813 // На будущее: FSpawn - игрок уже играл и перерождается
3815 // Одиночная игра/кооператив
3816 if gGameSettings.GameMode in [GM_COOP, GM_SINGLE] then
3817 begin
3818 if Self = gPlayer1 then
3819 begin
3820 // player 1 should try to spawn on the player 1 point
3821 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3822 Exit(RESPAWNPOINT_PLAYER1)
3823 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3824 Exit(RESPAWNPOINT_PLAYER2);
3825 end
3826 else if Self = gPlayer2 then
3827 begin
3828 // player 2 should try to spawn on the player 2 point
3829 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3830 Exit(RESPAWNPOINT_PLAYER2)
3831 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3832 Exit(RESPAWNPOINT_PLAYER1);
3833 end
3834 else
3835 begin
3836 // other players randomly pick either the first or the second point
3837 c := IfThen((Random(2) = 0), RESPAWNPOINT_PLAYER1, RESPAWNPOINT_PLAYER2);
3838 if g_Map_GetPointCount(c) > 0 then
3839 Exit(c);
3840 // try the other one
3841 c := IfThen((c = RESPAWNPOINT_PLAYER1), RESPAWNPOINT_PLAYER2, RESPAWNPOINT_PLAYER1);
3842 if g_Map_GetPointCount(c) > 0 then
3843 Exit(c);
3844 end;
3845 end;
3847 // Мясоповал
3848 if gGameSettings.GameMode = GM_DM then
3849 begin
3850 // try DM points first
3851 if g_Map_GetPointCount(RESPAWNPOINT_DM) > 0 then
3852 Exit(RESPAWNPOINT_DM);
3853 end;
3855 // Командные
3856 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3857 begin
3858 // try team points first
3859 c := RESPAWNPOINT_DM;
3860 if FTeam = TEAM_RED then
3861 c := RESPAWNPOINT_RED
3862 else if FTeam = TEAM_BLUE then
3863 c := RESPAWNPOINT_BLUE;
3864 if g_Map_GetPointCount(c) > 0 then
3865 Exit(c);
3866 end;
3868 // still haven't found a spawnpoint, try random shit
3869 Result := g_Map_GetRandomPointType();
3870 end;
3872 procedure TPlayer.Respawn(Silent: Boolean; Force: Boolean = False);
3873 var
3874 RespawnPoint: TRespawnPoint;
3875 a, b, c: Byte;
3876 Anim: TAnimation;
3877 ID: DWORD;
3878 begin
3879 FSlopeOld := 0;
3880 FIncCamOld := 0;
3881 FIncCam := 0;
3882 FBFGFireCounter := -1;
3883 FShellTimer := -1;
3884 FPain := 0;
3885 FLastHit := 0;
3886 FSpawnInvul := 0;
3887 FCorpse := -1;
3889 if not g_Game_IsServer then
3890 Exit;
3891 if FDummy then
3892 Exit;
3893 FWantsInGame := True;
3894 FJustTeleported := True;
3895 if Force then
3896 begin
3897 FTime[T_RESPAWN] := 0;
3898 FAlive := False;
3899 end;
3900 FNetTime := 0;
3901 // if server changes MaxLives we gotta be ready
3902 if gGameSettings.MaxLives = 0 then FNoRespawn := False;
3904 // Еще нельзя возродиться:
3905 if FTime[T_RESPAWN] > gTime then
3906 Exit;
3908 // Просрал все жизни:
3909 if FNoRespawn then
3910 begin
3911 if not FSpectator then Spectate(True);
3912 FWantsInGame := True;
3913 Exit;
3914 end;
3916 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.GameMode <> GM_COOP) then
3917 begin // "Своя игра"
3918 // Берсерк не сохраняется между уровнями:
3919 FRulez := FRulez-[R_BERSERK];
3920 end
3921 else // "Одиночная игра"/"Кооп"
3922 begin
3923 // Берсерк и ключи не сохраняются между уровнями:
3924 FRulez := FRulez-[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE, R_BERSERK];
3925 end;
3927 // Получаем точку спауна игрока:
3928 c := GetRespawnPoint();
3930 ReleaseKeys();
3931 SetFlag(FLAG_NONE);
3933 // Воскрешение без оружия:
3934 if not FAlive then
3935 begin
3936 FHealth := Round(PLAYER_HP_SOFT * (FHandicap / 100));
3937 FArmor := 0;
3938 FAlive := True;
3939 FAir := AIR_DEF;
3940 FJetFuel := 0;
3942 for a := WP_FIRST to WP_LAST do
3943 begin
3944 FWeapon[a] := False;
3945 FReloading[a] := 0;
3946 end;
3948 FWeapon[WEAPON_PISTOL] := True;
3949 FWeapon[WEAPON_KASTET] := True;
3950 FCurrWeap := WEAPON_PISTOL;
3951 resetWeaponQueue();
3953 FModel.SetWeapon(FCurrWeap);
3955 for b := A_BULLETS to A_HIGH do
3956 FAmmo[b] := 0;
3958 FAmmo[A_BULLETS] := 50;
3960 FMaxAmmo[A_BULLETS] := AmmoLimits[0, A_BULLETS];
3961 FMaxAmmo[A_SHELLS] := AmmoLimits[0, A_SHELLS];
3962 FMaxAmmo[A_ROCKETS] := AmmoLimits[0, A_SHELLS];
3963 FMaxAmmo[A_CELLS] := AmmoLimits[0, A_CELLS];
3964 FMaxAmmo[A_FUEL] := AmmoLimits[0, A_FUEL];
3966 if (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) and
3967 LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS) then
3968 FRulez := [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE]
3969 else
3970 FRulez := [];
3971 end;
3973 // Получаем координаты точки возрождения:
3974 if not g_Map_GetPoint(c, RespawnPoint) then
3975 begin
3976 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3977 Exit;
3978 end;
3980 // Установка координат и сброс всех параметров:
3981 FObj.X := RespawnPoint.X-PLAYER_RECT.X;
3982 FObj.Y := RespawnPoint.Y-PLAYER_RECT.Y;
3983 FObj.oldX := FObj.X; // don't interpolate after respawn
3984 FObj.oldY := FObj.Y;
3985 FObj.Vel.X := 0;
3986 FObj.Vel.Y := 0;
3987 FObj.Accel.X := 0;
3988 FObj.Accel.Y := 0;
3990 FDirection := RespawnPoint.Direction;
3991 if FDirection = TDirection.D_LEFT then
3992 FAngle := 180
3993 else
3994 FAngle := 0;
3996 SetAction(A_STAND, True);
3997 FModel.Direction := FDirection;
3999 for a := Low(FTime) to High(FTime) do
4000 FTime[a] := 0;
4002 for a := Low(FMegaRulez) to High(FMegaRulez) do
4003 FMegaRulez[a] := 0;
4005 // Respawn invulnerability
4006 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.SpawnInvul > 0) then
4007 begin
4008 FMegaRulez[MR_INVUL] := gTime + gGameSettings.SpawnInvul * 1000;
4009 FSpawnInvul := FMegaRulez[MR_INVUL];
4010 end;
4012 FDamageBuffer := 0;
4013 FJetpack := False;
4014 FCanJetpack := False;
4015 FFlaming := False;
4016 FFireTime := 0;
4017 FFirePainTime := 0;
4018 FFireAttacker := 0;
4020 // Анимация возрождения:
4021 if (not gLoadGameMode) and (not Silent) then
4022 if g_Frames_Get(ID, 'FRAMES_TELEPORT') then
4023 begin
4024 Anim := TAnimation.Create(ID, False, 3);
4025 g_GFX_OnceAnim(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4026 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, Anim);
4027 Anim.Free();
4028 end;
4030 FSpectator := False;
4031 FGhost := False;
4032 FPhysics := True;
4033 FSpectatePlayer := -1;
4034 FSpawned := True;
4036 if (gPlayer1 = nil) and (gSpectLatchPID1 = FUID) then
4037 gPlayer1 := self;
4038 if (gPlayer2 = nil) and (gSpectLatchPID2 = FUID) then
4039 gPlayer2 := self;
4041 if g_Game_IsNet then
4042 begin
4043 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
4044 MH_SEND_PlayerStats(FUID, NET_EVERYONE);
4045 if not Silent then
4046 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4047 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32,
4048 0, NET_GFX_TELE);
4049 end;
4050 end;
4052 procedure TPlayer.Spectate(NoMove: Boolean = False);
4053 begin
4054 if FAlive then
4055 Kill(K_EXTRAHARDKILL, FUID, HIT_SOME)
4056 else if (not NoMove) then
4057 begin
4058 GameX := gMapInfo.Width div 2;
4059 GameY := gMapInfo.Height div 2;
4060 end;
4061 FXTo := GameX;
4062 FYTo := GameY;
4064 FAlive := False;
4065 FSpectator := True;
4066 FGhost := True;
4067 FPhysics := False;
4068 FWantsInGame := False;
4069 FSpawned := False;
4070 FCorpse := -1;
4072 if FNoRespawn then
4073 begin
4074 if Self = gPlayer1 then
4075 begin
4076 gSpectLatchPID1 := FUID;
4077 gPlayer1 := nil;
4078 end
4079 else if Self = gPlayer2 then
4080 begin
4081 gSpectLatchPID2 := FUID;
4082 gPlayer2 := nil;
4083 end;
4084 end;
4086 if g_Game_IsNet then
4087 MH_SEND_PlayerStats(FUID);
4088 end;
4090 procedure TPlayer.SwitchNoClip;
4091 begin
4092 if not FAlive then
4093 Exit;
4094 FGhost := not FGhost;
4095 FPhysics := not FGhost;
4096 if FGhost then
4097 begin
4098 FXTo := FObj.X;
4099 FYTo := FObj.Y;
4100 end else
4101 begin
4102 FObj.Accel.X := 0;
4103 FObj.Accel.Y := 0;
4104 end;
4105 end;
4107 procedure TPlayer.Run(Direction: TDirection);
4108 var
4109 a, b: Integer;
4110 begin
4111 if MAX_RUNVEL > 8 then
4112 FlySmoke();
4114 // Бежим:
4115 if Direction = TDirection.D_LEFT then
4116 begin
4117 if FObj.Vel.X > -MAX_RUNVEL then
4118 FObj.Vel.X := FObj.Vel.X - (MAX_RUNVEL shr 3);
4119 end
4120 else
4121 if FObj.Vel.X < MAX_RUNVEL then
4122 FObj.Vel.X := FObj.Vel.X + (MAX_RUNVEL shr 3);
4124 // Возможно, пинаем куски:
4125 if (FObj.Vel.X <> 0) and (gGibs <> nil) then
4126 begin
4127 b := Abs(FObj.Vel.X);
4128 if b > 1 then b := b * (Random(8 div b) + 1);
4129 for a := 0 to High(gGibs) do
4130 begin
4131 if gGibs[a].alive and
4132 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
4133 FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
4134 begin
4135 // Пинаем куски
4136 if FObj.Vel.X < 0 then
4137 begin
4138 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)+120) // налево
4139 end
4140 else
4141 begin
4142 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)); // направо
4143 end;
4144 gGibs[a].positionChanged(); // this updates spatial accelerators
4145 end;
4146 end;
4147 end;
4149 SetAction(A_WALK);
4150 end;
4152 procedure TPlayer.SeeDown();
4153 begin
4154 SetAction(A_SEEDOWN);
4156 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTDOWN else FAngle := ANGLE_RIGHTDOWN;
4158 if FIncCam > -120 then DecMin(FIncCam, 5, -120);
4159 end;
4161 procedure TPlayer.SeeUp();
4162 begin
4163 SetAction(A_SEEUP);
4165 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTUP else FAngle := ANGLE_RIGHTUP;
4167 if FIncCam < 120 then IncMax(FIncCam, 5, 120);
4168 end;
4170 procedure TPlayer.SetAction(Action: Byte; Force: Boolean = False);
4171 var
4172 Prior: Byte;
4173 begin
4174 case Action of
4175 A_WALK: Prior := 3;
4176 A_DIE1: Prior := 5;
4177 A_DIE2: Prior := 5;
4178 A_ATTACK: Prior := 2;
4179 A_SEEUP: Prior := 1;
4180 A_SEEDOWN: Prior := 1;
4181 A_ATTACKUP: Prior := 2;
4182 A_ATTACKDOWN: Prior := 2;
4183 A_PAIN: Prior := 4;
4184 else Prior := 0;
4185 end;
4187 if (Prior > FActionPrior) or Force then
4188 if not ((Prior = 2) and (FCurrWeap = WEAPON_SAW)) then
4189 begin
4190 FActionPrior := Prior;
4191 FActionAnim := Action;
4192 FActionForce := Force;
4193 FActionChanged := True;
4194 end;
4196 if Action in [A_ATTACK, A_ATTACKUP, A_ATTACKDOWN] then FModel.SetFire(True);
4197 end;
4199 function TPlayer.StayOnStep(XInc, YInc: Integer): Boolean;
4200 begin
4201 Result := not g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height-1,
4202 PLAYER_RECT.Width, 1, PANEL_STEP, False)
4203 and g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height,
4204 PLAYER_RECT.Width, 1, PANEL_STEP, False);
4205 end;
4207 function TPlayer.TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
4208 var
4209 Anim: TAnimation;
4210 ID: DWORD;
4211 begin
4212 Result := False;
4214 if g_CollideLevel(X, Y, PLAYER_RECT.Width, PLAYER_RECT.Height) then
4215 begin
4216 g_Sound_PlayExAt('SOUND_GAME_NOTELEPORT', FObj.X, FObj.Y);
4217 if g_Game_IsServer and g_Game_IsNet then
4218 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_GAME_NOTELEPORT');
4219 Exit;
4220 end;
4222 FJustTeleported := True;
4224 Anim := nil;
4225 if not silent then
4226 begin
4227 if g_Frames_Get(ID, 'FRAMES_TELEPORT') then
4228 begin
4229 Anim := TAnimation.Create(ID, False, 3);
4230 end;
4232 g_Sound_PlayExAt('SOUND_GAME_TELEPORT', FObj.X, FObj.Y);
4233 g_GFX_OnceAnim(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4234 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, Anim);
4235 if g_Game_IsServer and g_Game_IsNet then
4236 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4237 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 1,
4238 NET_GFX_TELE);
4239 end;
4241 FObj.X := X-PLAYER_RECT.X;
4242 FObj.Y := Y-PLAYER_RECT.Y;
4243 FObj.oldX := FObj.X; // don't interpolate after respawn
4244 FObj.oldY := FObj.Y;
4245 if FAlive and FGhost then
4246 begin
4247 FXTo := FObj.X;
4248 FYTo := FObj.Y;
4249 end;
4251 if not g_Game_IsNet then
4252 begin
4253 if dir = 1 then
4254 begin
4255 SetDirection(TDirection.D_LEFT);
4256 FAngle := 180;
4257 end
4258 else
4259 if dir = 2 then
4260 begin
4261 SetDirection(TDirection.D_RIGHT);
4262 FAngle := 0;
4263 end
4264 else
4265 if dir = 3 then
4266 begin // обратное
4267 if FDirection = TDirection.D_RIGHT then
4268 begin
4269 SetDirection(TDirection.D_LEFT);
4270 FAngle := 180;
4271 end
4272 else
4273 begin
4274 SetDirection(TDirection.D_RIGHT);
4275 FAngle := 0;
4276 end;
4277 end;
4278 end;
4280 if not silent and (Anim <> nil) then
4281 begin
4282 g_GFX_OnceAnim(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4283 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, Anim);
4284 Anim.Free();
4286 if g_Game_IsServer and g_Game_IsNet then
4287 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4288 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 0,
4289 NET_GFX_TELE);
4290 end;
4292 Result := True;
4293 end;
4295 function nonz(a: Single): Single;
4296 begin
4297 if a <> 0 then
4298 Result := a
4299 else
4300 Result := 1;
4301 end;
4303 function TPlayer.refreshCorpse(): Boolean;
4304 var
4305 i: Integer;
4306 begin
4307 Result := False;
4308 FCorpse := -1;
4309 if FAlive or FSpectator then
4310 Exit;
4311 if (gCorpses = nil) or (Length(gCorpses) = 0) then
4312 Exit;
4313 for i := 0 to High(gCorpses) do
4314 if gCorpses[i] <> nil then
4315 if gCorpses[i].FPlayerUID = FUID then
4316 begin
4317 Result := True;
4318 FCorpse := i;
4319 break;
4320 end;
4321 end;
4323 function TPlayer.getCameraObj(): TObj;
4324 begin
4325 if (not FAlive) and (not FSpectator) and
4326 (FCorpse >= 0) and (FCorpse < Length(gCorpses)) and
4327 (gCorpses[FCorpse] <> nil) and (gCorpses[FCorpse].FPlayerUID = FUID) then
4328 begin
4329 gCorpses[FCorpse].FObj.slopeUpLeft := FObj.slopeUpLeft;
4330 Result := gCorpses[FCorpse].FObj;
4331 end
4332 else
4333 begin
4334 Result := FObj;
4335 end;
4336 end;
4338 procedure TPlayer.PreUpdate();
4339 begin
4340 FSlopeOld := FObj.slopeUpLeft;
4341 FIncCamOld := FIncCam;
4342 FObj.oldX := FObj.X;
4343 FObj.oldY := FObj.Y;
4344 end;
4346 procedure TPlayer.Update();
4347 var
4348 b: Byte;
4349 i, ii, wx, wy, xd, yd, k: Integer;
4350 blockmon, headwater, dospawn: Boolean;
4351 NetServer: Boolean;
4352 AnyServer: Boolean;
4353 SetSpect: Boolean;
4354 begin
4355 NetServer := g_Game_IsNet and g_Game_IsServer;
4356 AnyServer := g_Game_IsServer;
4358 if g_Game_IsClient and (NetInterpLevel > 0) then
4359 DoLerp(NetInterpLevel + 1)
4360 else
4361 if FGhost then
4362 DoLerp(4);
4364 if NetServer then
4365 if (FClientID >= 0) and (NetClients[FClientID].Peer <> nil) then
4366 begin
4367 FPing := NetClients[FClientID].Peer^.lastRoundTripTime;
4368 if NetClients[FClientID].Peer^.packetsSent > 0 then
4369 FLoss := Round(100*NetClients[FClientID].Peer^.packetsLost/NetClients[FClientID].Peer^.packetsSent)
4370 else
4371 FLoss := 0;
4372 end else
4373 begin
4374 FPing := 0;
4375 FLoss := 0;
4376 end;
4378 if FAlive and (FPunchAnim <> nil) then
4379 FPunchAnim.Update();
4381 if FAlive and (gFly or FJetpack) then
4382 FlySmoke();
4384 if FDirection = TDirection.D_LEFT then
4385 FAngle := 180
4386 else
4387 FAngle := 0;
4389 if FAlive and (not FGhost) then
4390 begin
4391 if FKeys[KEY_UP].Pressed then
4392 SeeUp();
4393 if FKeys[KEY_DOWN].Pressed then
4394 SeeDown();
4395 end;
4397 if (not (FKeys[KEY_UP].Pressed or FKeys[KEY_DOWN].Pressed)) and
4398 (FIncCam <> 0) then
4399 begin
4400 i := g_basic.Sign(FIncCam);
4401 FIncCam := Abs(FIncCam);
4402 DecMin(FIncCam, 5, 0);
4403 FIncCam := FIncCam*i;
4404 end;
4406 if gTime mod (GAME_TICK*2) <> 0 then
4407 begin
4408 if (FObj.Vel.X = 0) and FAlive then
4409 begin
4410 if FKeys[KEY_LEFT].Pressed then
4411 Run(TDirection.D_LEFT);
4412 if FKeys[KEY_RIGHT].Pressed then
4413 Run(TDirection.D_RIGHT);
4414 end;
4416 if FPhysics then
4417 begin
4418 g_Obj_Move(@FObj, True, True, True);
4419 positionChanged(); // this updates spatial accelerators
4420 end;
4422 Exit;
4423 end;
4425 FActionChanged := False;
4427 if FAlive then
4428 begin
4429 // Let alive player do some actions
4430 if FKeys[KEY_LEFT].Pressed then Run(TDirection.D_LEFT);
4431 if FKeys[KEY_RIGHT].Pressed then Run(TDirection.D_RIGHT);
4432 if FKeys[KEY_FIRE].Pressed and AnyServer then Fire()
4433 else
4434 begin
4435 if AnyServer then
4436 begin
4437 FlamerOff;
4438 if NetServer then MH_SEND_PlayerStats(FUID);
4439 end;
4440 end;
4441 if FKeys[KEY_OPEN].Pressed and AnyServer then Use();
4442 if FKeys[KEY_JUMP].Pressed then Jump()
4443 else
4444 begin
4445 if AnyServer and FJetpack then
4446 begin
4447 FJetpack := False;
4448 JetpackOff;
4449 if NetServer then MH_SEND_PlayerStats(FUID);
4450 end;
4451 FCanJetpack := True;
4452 end;
4453 end
4454 else // Dead
4455 begin
4456 dospawn := False;
4457 if not FGhost then
4458 for k := Low(FKeys) to KEY_CHAT-1 do
4459 begin
4460 if FKeys[k].Pressed then
4461 begin
4462 dospawn := True;
4463 break;
4464 end;
4465 end;
4466 if dospawn then
4467 begin
4468 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
4469 Respawn(False)
4470 else // Single
4471 if (FTime[T_RESPAWN] <= gTime) and
4472 gGameOn and (not FAlive) then
4473 begin
4474 if (g_Player_GetCount() > 1) then
4475 Respawn(False)
4476 else
4477 begin
4478 gExit := EXIT_RESTART;
4479 Exit;
4480 end;
4481 end;
4482 end;
4483 // Dead spectator actions
4484 if FGhost then
4485 begin
4486 if FKeys[KEY_OPEN].Pressed and AnyServer then Fire();
4487 if FKeys[KEY_FIRE].Pressed and AnyServer then
4488 begin
4489 if FSpectator then
4490 begin
4491 if (FSpectatePlayer >= High(gPlayers)) then
4492 FSpectatePlayer := -1
4493 else
4494 begin
4495 SetSpect := False;
4496 for I := FSpectatePlayer + 1 to High(gPlayers) do
4497 if gPlayers[I] <> nil then
4498 if gPlayers[I].alive then
4499 if gPlayers[I].UID <> FUID then
4500 begin
4501 FSpectatePlayer := I;
4502 SetSpect := True;
4503 break;
4504 end;
4506 if not SetSpect then FSpectatePlayer := -1;
4507 end;
4509 ReleaseKeys;
4510 end;
4511 end;
4512 end;
4513 end;
4514 // No clipping
4515 if FGhost then
4516 begin
4517 if FKeys[KEY_UP].Pressed or FKeys[KEY_JUMP].Pressed then
4518 begin
4519 FYTo := FObj.Y - 32;
4520 FSpectatePlayer := -1;
4521 end;
4522 if FKeys[KEY_DOWN].Pressed then
4523 begin
4524 FYTo := FObj.Y + 32;
4525 FSpectatePlayer := -1;
4526 end;
4527 if FKeys[KEY_LEFT].Pressed then
4528 begin
4529 FXTo := FObj.X - 32;
4530 FSpectatePlayer := -1;
4531 end;
4532 if FKeys[KEY_RIGHT].Pressed then
4533 begin
4534 FXTo := FObj.X + 32;
4535 FSpectatePlayer := -1;
4536 end;
4538 if (FXTo < -64) then
4539 FXTo := -64
4540 else if (FXTo > gMapInfo.Width + 32) then
4541 FXTo := gMapInfo.Width + 32;
4542 if (FYTo < -72) then
4543 FYTo := -72
4544 else if (FYTo > gMapInfo.Height + 32) then
4545 FYTo := gMapInfo.Height + 32;
4546 end;
4548 if FPhysics then
4549 begin
4550 g_Obj_Move(@FObj, True, True, True);
4551 positionChanged(); // this updates spatial accelerators
4552 end
4553 else
4554 begin
4555 FObj.Vel.X := 0;
4556 FObj.Vel.Y := 0;
4557 if FSpectator then
4558 if (FSpectatePlayer <= High(gPlayers)) and (FSpectatePlayer >= 0) then
4559 if gPlayers[FSpectatePlayer] <> nil then
4560 if gPlayers[FSpectatePlayer].alive then
4561 begin
4562 FXTo := gPlayers[FSpectatePlayer].GameX;
4563 FYTo := gPlayers[FSpectatePlayer].GameY;
4564 end;
4565 end;
4567 blockmon := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X, FObj.Y+PLAYER_HEADRECT.Y,
4568 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
4569 PANEL_BLOCKMON, True);
4570 headwater := HeadInLiquid(0, 0);
4572 // Сопротивление воздуха:
4573 if (not FAlive) or not (FKeys[KEY_LEFT].Pressed or FKeys[KEY_RIGHT].Pressed) then
4574 if FObj.Vel.X <> 0 then
4575 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
4577 if (FLastHit = HIT_TRAP) and (FPain > 90) then FPain := 90;
4578 DecMin(FPain, 5, 0);
4579 DecMin(FPickup, 1, 0);
4581 if FAlive and (FObj.Y > Integer(gMapInfo.Height)+128) and AnyServer then
4582 begin
4583 // Обнулить действия примочек, чтобы фон пропал
4584 FMegaRulez[MR_SUIT] := 0;
4585 FMegaRulez[MR_INVUL] := 0;
4586 FMegaRulez[MR_INVIS] := 0;
4587 Kill(K_FALLKILL, 0, HIT_FALL);
4588 end;
4590 i := 9;
4592 if FAlive then
4593 begin
4594 if FCurrWeap = WEAPON_SAW then
4595 if not (FSawSound.IsPlaying() or FSawSoundHit.IsPlaying() or
4596 FSawSoundSelect.IsPlaying()) then
4597 FSawSoundIdle.PlayAt(FObj.X, FObj.Y);
4599 if FJetpack then
4600 if (not FJetSoundFly.IsPlaying()) and (not FJetSoundOn.IsPlaying()) and
4601 (not FJetSoundOff.IsPlaying()) then
4602 begin
4603 FJetSoundFly.SetPosition(0);
4604 FJetSoundFly.PlayAt(FObj.X, FObj.Y);
4605 end;
4607 for b := WP_FIRST to WP_LAST do
4608 if FReloading[b] > 0 then
4609 if FNoReload then
4610 FReloading[b] := 0
4611 else
4612 Dec(FReloading[b]);
4614 if FShellTimer > -1 then
4615 if FShellTimer = 0 then
4616 begin
4617 if FShellType = SHELL_SHELL then
4618 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4619 GameVelX, GameVelY-2, SHELL_SHELL)
4620 else if FShellType = SHELL_DBLSHELL then
4621 begin
4622 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4623 GameVelX+1, GameVelY-2, SHELL_SHELL);
4624 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4625 GameVelX-1, GameVelY-2, SHELL_SHELL);
4626 end;
4627 FShellTimer := -1;
4628 end else Dec(FShellTimer);
4630 if (FBFGFireCounter > -1) then
4631 if FBFGFireCounter = 0 then
4632 begin
4633 if AnyServer then
4634 begin
4635 wx := FObj.X+WEAPONPOINT[FDirection].X;
4636 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
4637 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
4638 yd := wy+firediry();
4639 g_Weapon_bfgshot(wx, wy, xd, yd, FUID);
4640 if NetServer then MH_SEND_PlayerFire(FUID, WEAPON_BFG, wx, wy, xd, yd);
4641 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4642 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4643 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4644 end;
4646 FReloading[WEAPON_BFG] := WEAPON_RELOAD[WEAPON_BFG];
4647 FBFGFireCounter := -1;
4648 end else
4649 if FNoReload then
4650 FBFGFireCounter := 0
4651 else
4652 Dec(FBFGFireCounter);
4654 if (FMegaRulez[MR_SUIT] < gTime) and AnyServer then
4655 begin
4656 b := g_GetAcidHit(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width, PLAYER_RECT.Height);
4658 if (b > 0) and (gTime mod (15*GAME_TICK) = 0) then Damage(b, 0, 0, 0, HIT_ACID);
4659 end;
4661 if (headwater or blockmon) then
4662 begin
4663 Dec(FAir);
4665 if FAir < -9 then
4666 begin
4667 if AnyServer then Damage(10, 0, 0, 0, HIT_WATER);
4668 FAir := 0;
4669 end
4670 else if (FAir mod 31 = 0) and not blockmon then
4671 begin
4672 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2), FObj.Y+PLAYER_RECT.Y-4, 5+Random(6), 8, 4);
4673 if Random(2) = 0
4674 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
4675 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
4676 end;
4677 end else if FAir < AIR_DEF then
4678 FAir := AIR_DEF;
4680 if FFireTime > 0 then
4681 begin
4682 if BodyInLiquid(0, 0) then
4683 begin
4684 FFireTime := 0;
4685 FFirePainTime := 0;
4686 end
4687 else if FMegaRulez[MR_SUIT] >= gTime then
4688 begin
4689 if FMegaRulez[MR_SUIT] = gTime then
4690 FFireTime := 1;
4691 FFirePainTime := 0;
4692 end
4693 else
4694 begin
4695 OnFireFlame(1);
4696 if FFirePainTime <= 0 then
4697 begin
4698 if g_Game_IsServer then
4699 Damage(2, FFireAttacker, 0, 0, HIT_FLAME);
4700 FFirePainTime := 12 - FFireTime div 12;
4701 end;
4702 FFirePainTime := FFirePainTime - 1;
4703 FFireTime := FFireTime - 1;
4704 if ((FFireTime mod 33) = 0) and (FMegaRulez[MR_INVUL] < gTime) then
4705 FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
4706 if (FFireTime = 0) and g_Game_IsNet and g_Game_IsServer then
4707 MH_SEND_PlayerStats(FUID);
4708 end;
4709 end;
4711 if FDamageBuffer > 0 then
4712 begin
4713 if FDamageBuffer >= 9 then
4714 begin
4715 SetAction(A_PAIN);
4717 if FDamageBuffer < 30 then i := 9
4718 else if FDamageBuffer < 100 then i := 18
4719 else i := 27;
4720 end;
4722 ii := Round(FDamageBuffer*FHealth / nonz(FArmor*(3/4)+FHealth));
4723 FArmor := FArmor-(FDamageBuffer-ii);
4724 FHealth := FHealth-ii;
4725 if FArmor < 0 then
4726 begin
4727 FHealth := FHealth+FArmor;
4728 FArmor := 0;
4729 end;
4731 if AnyServer then
4732 if FHealth <= 0 then
4733 if FHealth > -30 then Kill(K_SIMPLEKILL, FLastSpawnerUID, FLastHit)
4734 else if FHealth > -50 then Kill(K_HARDKILL, FLastSpawnerUID, FLastHit)
4735 else Kill(K_EXTRAHARDKILL, FLastSpawnerUID, FLastHit);
4737 if FAlive and ((FLastHit <> HIT_FLAME) or (FFireTime <= 0)) then
4738 begin
4739 if FDamageBuffer <= 20 then FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y)
4740 else if FDamageBuffer <= 55 then FModel.PlaySound(MODELSOUND_PAIN, 2, FObj.X, FObj.Y)
4741 else if FDamageBuffer <= 120 then FModel.PlaySound(MODELSOUND_PAIN, 3, FObj.X, FObj.Y)
4742 else FModel.PlaySound(MODELSOUND_PAIN, 4, FObj.X, FObj.Y);
4743 end;
4745 FDamageBuffer := 0;
4746 end;
4748 {CollideItem();}
4749 end; // if FAlive then ...
4751 if (FActionAnim = A_PAIN) and (FModel.Animation <> A_PAIN) then
4752 begin
4753 FModel.ChangeAnimation(FActionAnim, FActionForce);
4754 FModel.GetCurrentAnimation.MinLength := i;
4755 FModel.GetCurrentAnimationMask.MinLength := i;
4756 end else FModel.ChangeAnimation(FActionAnim, FActionForce and (FModel.Animation <> A_STAND));
4758 if (FModel.GetCurrentAnimation.Played or ((not FActionChanged) and (FModel.Animation = A_WALK)))
4759 then SetAction(A_STAND, True);
4761 if not ((FModel.Animation = A_WALK) and (Abs(FObj.Vel.X) < 4) and not FModel.Fire) then FModel.Update;
4763 for b := Low(FKeys) to High(FKeys) do
4764 if FKeys[b].Time = 0 then FKeys[b].Pressed := False else Dec(FKeys[b].Time);
4765 end;
4768 procedure TPlayer.getMapBox (out x, y, w, h: Integer); inline;
4769 begin
4770 x := FObj.X+PLAYER_RECT.X;
4771 y := FObj.Y+PLAYER_RECT.Y;
4772 w := PLAYER_RECT.Width;
4773 h := PLAYER_RECT.Height;
4774 end;
4777 procedure TPlayer.moveBy (dx, dy: Integer); inline;
4778 begin
4779 if (dx <> 0) or (dy <> 0) then
4780 begin
4781 FObj.X += dx;
4782 FObj.Y += dy;
4783 positionChanged();
4784 end;
4785 end;
4788 function TPlayer.Collide(X, Y: Integer; Width, Height: Word): Boolean;
4789 begin
4790 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4791 FObj.Y+PLAYER_RECT.Y,
4792 PLAYER_RECT.Width,
4793 PLAYER_RECT.Height,
4794 X, Y,
4795 Width, Height);
4796 end;
4798 function TPlayer.Collide(Panel: TPanel): Boolean;
4799 begin
4800 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4801 FObj.Y+PLAYER_RECT.Y,
4802 PLAYER_RECT.Width,
4803 PLAYER_RECT.Height,
4804 Panel.X, Panel.Y,
4805 Panel.Width, Panel.Height);
4806 end;
4808 function TPlayer.Collide(X, Y: Integer): Boolean;
4809 begin
4810 X := X-FObj.X-PLAYER_RECT.X;
4811 Y := Y-FObj.Y-PLAYER_RECT.Y;
4812 Result := (x >= 0) and (x <= PLAYER_RECT.Width) and
4813 (y >= 0) and (y <= PLAYER_RECT.Height);
4814 end;
4816 function g_Player_ValidName(Name: string): Boolean;
4817 var
4818 a: Integer;
4819 begin
4820 Result := True;
4822 if gPlayers = nil then Exit;
4824 for a := 0 to High(gPlayers) do
4825 if gPlayers[a] <> nil then
4826 if LowerCase(Name) = LowerCase(gPlayers[a].FName) then
4827 begin
4828 Result := False;
4829 Exit;
4830 end;
4831 end;
4833 procedure TPlayer.SetDirection(Direction: TDirection);
4834 var
4835 d: TDirection;
4836 begin
4837 d := FModel.Direction;
4839 FModel.Direction := Direction;
4840 if d <> Direction then FModel.ChangeAnimation(FModel.Animation, True);
4842 FDirection := Direction;
4843 end;
4845 function TPlayer.GetKeys(): Byte;
4846 begin
4847 Result := 0;
4849 if R_KEY_RED in FRulez then Result := KEY_RED;
4850 if R_KEY_GREEN in FRulez then Result := Result or KEY_GREEN;
4851 if R_KEY_BLUE in FRulez then Result := Result or KEY_BLUE;
4853 if FTeam = TEAM_RED then Result := Result or KEY_REDTEAM;
4854 if FTeam = TEAM_BLUE then Result := Result or KEY_BLUETEAM;
4855 end;
4857 procedure TPlayer.Use();
4858 var
4859 a: Integer;
4860 begin
4861 if FTime[T_USE] > gTime then Exit;
4863 g_Triggers_PressR(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
4864 PLAYER_RECT.Height, FUID, ACTIVATE_PLAYERPRESS);
4866 for a := 0 to High(gPlayers) do
4867 if (gPlayers[a] <> nil) and (gPlayers[a] <> Self) and
4868 gPlayers[a].alive and SameTeam(FUID, gPlayers[a].FUID) and
4869 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4870 FObj.Rect.Width, FObj.Rect.Height, @gPlayers[a].FObj) then
4871 begin
4872 gPlayers[a].Touch();
4873 if g_Game_IsNet and g_Game_IsServer then
4874 MH_SEND_GameEvent(NET_EV_PLAYER_TOUCH, gPlayers[a].FUID);
4875 end;
4877 FTime[T_USE] := gTime+120;
4878 end;
4880 procedure TPlayer.NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
4881 var
4882 locObj: TObj;
4883 visible: Boolean = True;
4884 WX, WY, XD, YD: Integer;
4885 begin
4886 WX := X;
4887 WY := Y;
4888 XD := AX;
4889 YD := AY;
4891 case FCurrWeap of
4892 WEAPON_KASTET:
4893 begin
4894 visible := False;
4895 DoPunch();
4896 if R_BERSERK in FRulez then
4897 begin
4898 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
4899 locobj.X := FObj.X+FObj.Rect.X;
4900 locobj.Y := FObj.Y+FObj.Rect.Y;
4901 locobj.rect.X := 0;
4902 locobj.rect.Y := 0;
4903 locobj.rect.Width := 39;
4904 locobj.rect.Height := 52;
4905 locobj.Vel.X := (xd-wx) div 2;
4906 locobj.Vel.Y := (yd-wy) div 2;
4907 locobj.Accel.X := xd-wx;
4908 locobj.Accel.y := yd-wy;
4910 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
4911 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
4912 else
4913 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
4915 if gFlash = 1 then
4916 if FPain < 50 then
4917 FPain := min(FPain + 25, 50);
4918 end else
4919 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
4920 end;
4922 WEAPON_SAW:
4923 begin
4924 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4925 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
4926 begin
4927 FSawSoundSelect.Stop();
4928 FSawSound.Stop();
4929 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
4930 end
4931 else if not FSawSoundHit.IsPlaying() then
4932 begin
4933 FSawSoundSelect.Stop();
4934 FSawSound.PlayAt(FObj.X, FObj.Y);
4935 end;
4936 end;
4938 WEAPON_PISTOL:
4939 begin
4940 g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', GameX, Gamey);
4941 FFireAngle := FAngle;
4942 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4943 GameVelX, GameVelY-2, SHELL_BULLET);
4944 end;
4946 WEAPON_SHOTGUN1:
4947 begin
4948 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4949 FFireAngle := FAngle;
4950 FShellTimer := 10;
4951 FShellType := SHELL_SHELL;
4952 end;
4954 WEAPON_SHOTGUN2:
4955 begin
4956 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN2', Gamex, Gamey);
4957 FFireAngle := FAngle;
4958 FShellTimer := 13;
4959 FShellType := SHELL_DBLSHELL;
4960 end;
4962 WEAPON_CHAINGUN:
4963 begin
4964 g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', Gamex, Gamey);
4965 FFireAngle := FAngle;
4966 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4967 GameVelX, GameVelY-2, SHELL_BULLET);
4968 end;
4970 WEAPON_ROCKETLAUNCHER:
4971 begin
4972 g_Weapon_Rocket(wx, wy, xd, yd, FUID, WID);
4973 FFireAngle := FAngle;
4974 end;
4976 WEAPON_PLASMA:
4977 begin
4978 g_Weapon_Plasma(wx, wy, xd, yd, FUID, WID);
4979 FFireAngle := FAngle;
4980 end;
4982 WEAPON_BFG:
4983 begin
4984 g_Weapon_BFGShot(wx, wy, xd, yd, FUID, WID);
4985 FFireAngle := FAngle;
4986 end;
4988 WEAPON_SUPERPULEMET:
4989 begin
4990 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4991 FFireAngle := FAngle;
4992 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4993 GameVelX, GameVelY-2, SHELL_SHELL);
4994 end;
4996 WEAPON_FLAMETHROWER:
4997 begin
4998 g_Weapon_flame(wx, wy, xd, yd, FUID, WID);
4999 FlamerOn;
5000 FFireAngle := FAngle;
5001 end;
5002 end;
5004 if not visible then Exit;
5006 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
5007 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
5008 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
5009 end;
5011 procedure TPlayer.DoLerp(Level: Integer = 2);
5012 begin
5013 if FObj.X <> FXTo then FObj.X := Lerp(FObj.X, FXTo, Level);
5014 if FObj.Y <> FYTo then FObj.Y := Lerp(FObj.Y, FYTo, Level);
5015 end;
5017 procedure TPlayer.SetLerp(XTo, YTo: Integer);
5018 var
5019 AX, AY: Integer;
5020 begin
5021 FXTo := XTo;
5022 FYTo := YTo;
5023 if FJustTeleported or (NetInterpLevel < 1) then
5024 begin
5025 FObj.X := XTo;
5026 FObj.Y := YTo;
5027 if FJustTeleported then
5028 begin
5029 FObj.oldX := FObj.X;
5030 FObj.oldY := FObj.Y;
5031 end;
5032 end
5033 else
5034 begin
5035 AX := Abs(FXTo - FObj.X);
5036 AY := Abs(FYTo - FObj.Y);
5037 if (AX > 32) or (AX <= NetInterpLevel) then
5038 FObj.X := FXTo;
5039 if (AY > 32) or (AY <= NetInterpLevel) then
5040 FObj.Y := FYTo;
5041 end;
5042 end;
5044 function TPlayer.FullInLift(XInc, YInc: Integer): Integer;
5045 begin
5046 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5047 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5048 PANEL_LIFTUP, False) then Result := -1
5049 else
5050 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5051 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5052 PANEL_LIFTDOWN, False) then Result := 1
5053 else Result := 0;
5054 end;
5056 function TPlayer.GetFlag(Flag: Byte): Boolean;
5057 var
5058 s, ts: String;
5059 evtype, a: Byte;
5060 begin
5061 Result := False;
5063 if Flag = FLAG_NONE then
5064 Exit;
5066 if not g_Game_IsServer then Exit;
5068 // Принес чужой флаг на свою базу:
5069 if (Flag = FTeam) and
5070 (gFlags[Flag].State = FLAG_STATE_NORMAL) and
5071 (FFlag <> FLAG_NONE) then
5072 begin
5073 if FFlag = FLAG_RED then
5074 s := _lc[I_PLAYER_FLAG_RED]
5075 else
5076 s := _lc[I_PLAYER_FLAG_BLUE];
5078 evtype := FLAG_STATE_SCORED;
5080 ts := Format('%.4d', [gFlags[FFlag].CaptureTime]);
5081 Insert('.', ts, Length(ts) + 1 - 3);
5082 g_Console_Add(Format(_lc[I_PLAYER_FLAG_CAPTURE], [FName, s, ts]), True);
5084 g_Map_ResetFlag(FFlag);
5085 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_CAPTURE], [AnsiUpperCase(s)]), 144);
5087 if ((Self = gPlayer1) or (Self = gPlayer2)
5088 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5089 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5090 a := 0
5091 else
5092 a := 1;
5094 if not sound_cap_flag[a].IsPlaying() then
5095 sound_cap_flag[a].Play();
5097 gTeamStat[FTeam].Score += 1;
5099 Result := True;
5100 if g_Game_IsNet then
5101 begin
5102 MH_SEND_FlagEvent(evtype, FFlag, FUID, False);
5103 MH_SEND_GameStats;
5104 end;
5106 gFlags[FFlag].CaptureTime := 0;
5107 SetFlag(FLAG_NONE);
5108 Exit;
5109 end;
5111 // Подобрал свой флаг - вернул его на базу:
5112 if (Flag = FTeam) and
5113 (gFlags[Flag].State = FLAG_STATE_DROPPED) then
5114 begin
5115 if Flag = FLAG_RED then
5116 s := _lc[I_PLAYER_FLAG_RED]
5117 else
5118 s := _lc[I_PLAYER_FLAG_BLUE];
5120 evtype := FLAG_STATE_RETURNED;
5121 gFlags[Flag].CaptureTime := 0;
5123 g_Console_Add(Format(_lc[I_PLAYER_FLAG_RETURN], [FName, s]), True);
5125 g_Map_ResetFlag(Flag);
5126 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
5128 if ((Self = gPlayer1) or (Self = gPlayer2)
5129 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5130 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5131 a := 0
5132 else
5133 a := 1;
5135 if not sound_ret_flag[a].IsPlaying() then
5136 sound_ret_flag[a].Play();
5138 Result := True;
5139 if g_Game_IsNet then
5140 begin
5141 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5142 MH_SEND_GameStats;
5143 end;
5144 Exit;
5145 end;
5147 // Подобрал чужой флаг:
5148 if (Flag <> FTeam) and (FTime[T_FLAGCAP] <= gTime) then
5149 begin
5150 SetFlag(Flag);
5152 if Flag = FLAG_RED then
5153 s := _lc[I_PLAYER_FLAG_RED]
5154 else
5155 s := _lc[I_PLAYER_FLAG_BLUE];
5157 evtype := FLAG_STATE_CAPTURED;
5159 g_Console_Add(Format(_lc[I_PLAYER_FLAG_GET], [FName, s]), True);
5161 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_GET], [AnsiUpperCase(s)]), 144);
5163 gFlags[Flag].State := FLAG_STATE_CAPTURED;
5165 if ((Self = gPlayer1) or (Self = gPlayer2)
5166 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5167 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5168 a := 0
5169 else
5170 a := 1;
5172 if not sound_get_flag[a].IsPlaying() then
5173 sound_get_flag[a].Play();
5175 Result := True;
5176 if g_Game_IsNet then
5177 begin
5178 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5179 MH_SEND_GameStats;
5180 end;
5181 end;
5182 end;
5184 procedure TPlayer.SetFlag(Flag: Byte);
5185 begin
5186 FFlag := Flag;
5187 if FModel <> nil then
5188 FModel.SetFlag(FFlag);
5189 end;
5191 function TPlayer.TryDropFlag(): Boolean;
5192 begin
5193 if LongBool(gGameSettings.Options and GAME_OPTION_ALLOWDROPFLAG) then
5194 Result := DropFlag(False, LongBool(gGameSettings.Options and GAME_OPTION_THROWFLAG))
5195 else
5196 Result := False;
5197 end;
5199 function TPlayer.DropFlag(Silent: Boolean = True; DoThrow: Boolean = False): Boolean;
5200 var
5201 s: String;
5202 a: Byte;
5203 xv, yv: Integer;
5204 begin
5205 Result := False;
5206 if (not g_Game_IsServer) or (FFlag = FLAG_NONE) then
5207 Exit;
5208 FTime[T_FLAGCAP] := gTime + 2000;
5209 with gFlags[FFlag] do
5210 begin
5211 Obj.X := FObj.X;
5212 Obj.Y := FObj.Y;
5213 Direction := FDirection;
5214 State := FLAG_STATE_DROPPED;
5215 Count := FLAG_TIME;
5216 if DoThrow then
5217 begin
5218 xv := FObj.Vel.X + IfThen(Direction = TDirection.D_RIGHT, 10, -10);
5219 yv := FObj.Vel.Y - 2;
5220 end
5221 else
5222 begin
5223 xv := (FObj.Vel.X div 2);
5224 yv := (FObj.Vel.Y div 2) - 2;
5225 end;
5226 g_Obj_Push(@Obj, xv, yv);
5228 positionChanged(); // this updates spatial accelerators
5230 if FFlag = FLAG_RED then
5231 s := _lc[I_PLAYER_FLAG_RED]
5232 else
5233 s := _lc[I_PLAYER_FLAG_BLUE];
5235 g_Console_Add(Format(_lc[I_PLAYER_FLAG_DROP], [FName, s]), True);
5236 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_DROP], [AnsiUpperCase(s)]), 144);
5238 if ((Self = gPlayer1) or (Self = gPlayer2)
5239 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5240 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5241 a := 0
5242 else
5243 a := 1;
5245 if (not Silent) and (not sound_lost_flag[a].IsPlaying()) then
5246 sound_lost_flag[a].Play();
5248 if g_Game_IsNet then
5249 MH_SEND_FlagEvent(FLAG_STATE_DROPPED, Flag, FUID, False);
5250 end;
5251 SetFlag(FLAG_NONE);
5252 Result := True;
5253 end;
5255 procedure TPlayer.GetSecret();
5256 begin
5257 if (self = gPlayer1) or (self = gPlayer2) then
5258 begin
5259 g_Console_Add(Format(_lc[I_PLAYER_SECRET], [FName]), True);
5260 g_Sound_PlayEx('SOUND_GAME_SECRET');
5261 end;
5262 Inc(FSecrets);
5263 end;
5265 procedure TPlayer.PressKey(Key: Byte; Time: Word = 1);
5266 begin
5267 Assert(Key <= High(FKeys));
5269 FKeys[Key].Pressed := True;
5270 FKeys[Key].Time := Time;
5271 end;
5273 function TPlayer.IsKeyPressed(K: Byte): Boolean;
5274 begin
5275 Result := FKeys[K].Pressed;
5276 end;
5278 procedure TPlayer.ReleaseKeys();
5279 var
5280 a: Integer;
5281 begin
5282 for a := Low(FKeys) to High(FKeys) do
5283 begin
5284 FKeys[a].Pressed := False;
5285 FKeys[a].Time := 0;
5286 end;
5287 end;
5289 procedure TPlayer.OnDamage(Angle: SmallInt);
5290 begin
5291 end;
5293 function TPlayer.firediry(): Integer;
5294 begin
5295 if FKeys[KEY_UP].Pressed then Result := -42
5296 else if FKeys[KEY_DOWN].Pressed then Result := 19
5297 else Result := 0;
5298 end;
5300 procedure TPlayer.RememberState();
5301 var
5302 i: Integer;
5303 SavedState: TPlayerSavedState;
5304 begin
5305 SavedState.Health := FHealth;
5306 SavedState.Armor := FArmor;
5307 SavedState.Air := FAir;
5308 SavedState.JetFuel := FJetFuel;
5309 SavedState.CurrWeap := FCurrWeap;
5310 SavedState.NextWeap := FNextWeap;
5311 SavedState.NextWeapDelay := FNextWeapDelay;
5312 for i := Low(FWeapon) to High(FWeapon) do
5313 SavedState.Weapon[i] := FWeapon[i];
5314 for i := Low(FAmmo) to High(FAmmo) do
5315 SavedState.Ammo[i] := FAmmo[i];
5316 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5317 SavedState.MaxAmmo[i] := FMaxAmmo[i];
5318 SavedState.Rulez := FRulez - [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5320 FSavedStateNum := -1;
5321 for i := Low(SavedStates) to High(SavedStates) do
5322 if not SavedStates[i].Used then
5323 begin
5324 FSavedStateNum := i;
5325 break;
5326 end;
5327 if FSavedStateNum < 0 then
5328 begin
5329 SetLength(SavedStates, Length(SavedStates) + 1);
5330 FSavedStateNum := High(SavedStates);
5331 end;
5333 SavedState.Used := True;
5334 SavedStates[FSavedStateNum] := SavedState;
5335 end;
5337 procedure TPlayer.RecallState();
5338 var
5339 i: Integer;
5340 SavedState: TPlayerSavedState;
5341 begin
5342 if(FSavedStateNum < 0) or (FSavedStateNum > High(SavedStates)) then
5343 Exit;
5345 SavedState := SavedStates[FSavedStateNum];
5346 SavedStates[FSavedStateNum].Used := False;
5347 FSavedStateNum := -1;
5349 FHealth := SavedState.Health;
5350 FArmor := SavedState.Armor;
5351 FAir := SavedState.Air;
5352 FJetFuel := SavedState.JetFuel;
5353 FCurrWeap := SavedState.CurrWeap;
5354 FNextWeap := SavedState.NextWeap;
5355 FNextWeapDelay := SavedState.NextWeapDelay;
5356 for i := Low(FWeapon) to High(FWeapon) do
5357 FWeapon[i] := SavedState.Weapon[i];
5358 for i := Low(FAmmo) to High(FAmmo) do
5359 FAmmo[i] := SavedState.Ammo[i];
5360 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5361 FMaxAmmo[i] := SavedState.MaxAmmo[i];
5362 FRulez := SavedState.Rulez;
5364 if gGameSettings.GameType = GT_SERVER then
5365 MH_SEND_PlayerStats(FUID);
5366 end;
5368 procedure TPlayer.SaveState (st: TStream);
5369 var
5370 i: Integer;
5371 b: Byte;
5372 begin
5373 // Сигнатура игрока
5374 utils.writeSign(st, 'PLYR');
5375 utils.writeInt(st, Byte(PLR_SAVE_VERSION)); // version
5376 // Бот или человек
5377 utils.writeBool(st, FIamBot);
5378 // UID игрока
5379 utils.writeInt(st, Word(FUID));
5380 // Имя игрока
5381 utils.writeStr(st, FName);
5382 // Команда
5383 utils.writeInt(st, Byte(FTeam));
5384 // Жив ли
5385 utils.writeBool(st, FAlive);
5386 // Израсходовал ли все жизни
5387 utils.writeBool(st, FNoRespawn);
5388 // Направление
5389 if FDirection = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
5390 utils.writeInt(st, Byte(b));
5391 // Здоровье
5392 utils.writeInt(st, LongInt(FHealth));
5393 // Коэффициент инвалидности
5394 utils.writeInt(st, LongInt(FHandicap));
5395 // Жизни
5396 utils.writeInt(st, Byte(FLives));
5397 // Броня
5398 utils.writeInt(st, LongInt(FArmor));
5399 // Запас воздуха
5400 utils.writeInt(st, LongInt(FAir));
5401 // Запас горючего
5402 utils.writeInt(st, LongInt(FJetFuel));
5403 // Боль
5404 utils.writeInt(st, LongInt(FPain));
5405 // Убил
5406 utils.writeInt(st, LongInt(FKills));
5407 // Убил монстров
5408 utils.writeInt(st, LongInt(FMonsterKills));
5409 // Фрагов
5410 utils.writeInt(st, LongInt(FFrags));
5411 // Фрагов подряд
5412 utils.writeInt(st, Byte(FFragCombo));
5413 // Время последнего фрага
5414 utils.writeInt(st, LongWord(FLastFrag));
5415 // Смертей
5416 utils.writeInt(st, LongInt(FDeath));
5417 // Какой флаг несет
5418 utils.writeInt(st, Byte(FFlag));
5419 // Нашел секретов
5420 utils.writeInt(st, LongInt(FSecrets));
5421 // Текущее оружие
5422 utils.writeInt(st, Byte(FCurrWeap));
5423 // Желаемое оружие
5424 utils.writeInt(st, Word(FNextWeap));
5425 // ...и пауза
5426 utils.writeInt(st, Byte(FNextWeapDelay));
5427 // Время зарядки BFG
5428 utils.writeInt(st, SmallInt(FBFGFireCounter));
5429 // Буфер урона
5430 utils.writeInt(st, LongInt(FDamageBuffer));
5431 // Последний ударивший
5432 utils.writeInt(st, Word(FLastSpawnerUID));
5433 // Тип последнего полученного урона
5434 utils.writeInt(st, Byte(FLastHit));
5435 // Объект игрока
5436 Obj_SaveState(st, @FObj);
5437 // Текущее количество патронов
5438 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FAmmo[i]));
5439 // Максимальное количество патронов
5440 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FMaxAmmo[i]));
5441 // Наличие оружия
5442 for i := WP_FIRST to WP_LAST do utils.writeBool(st, FWeapon[i]);
5443 // Время перезарядки оружия
5444 for i := WP_FIRST to WP_LAST do utils.writeInt(st, Word(FReloading[i]));
5445 // Наличие рюкзака
5446 utils.writeBool(st, (R_ITEM_BACKPACK in FRulez));
5447 // Наличие красного ключа
5448 utils.writeBool(st, (R_KEY_RED in FRulez));
5449 // Наличие зеленого ключа
5450 utils.writeBool(st, (R_KEY_GREEN in FRulez));
5451 // Наличие синего ключа
5452 utils.writeBool(st, (R_KEY_BLUE in FRulez));
5453 // Наличие берсерка
5454 utils.writeBool(st, (R_BERSERK in FRulez));
5455 // Время действия специальных предметов
5456 for i := MR_SUIT to MR_MAX do utils.writeInt(st, LongWord(FMegaRulez[i]));
5457 // Время до повторного респауна, смены оружия, исользования, захвата флага
5458 for i := T_RESPAWN to T_FLAGCAP do utils.writeInt(st, LongWord(FTime[i]));
5459 // Название модели
5460 utils.writeStr(st, FModel.Name);
5461 // Цвет модели
5462 utils.writeInt(st, Byte(FColor.R));
5463 utils.writeInt(st, Byte(FColor.G));
5464 utils.writeInt(st, Byte(FColor.B));
5465 end;
5468 procedure TPlayer.LoadState (st: TStream);
5469 var
5470 i: Integer;
5471 str: String;
5472 b: Byte;
5473 begin
5474 assert(st <> nil);
5476 // Сигнатура игрока
5477 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
5478 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
5479 // Бот или человек:
5480 FIamBot := utils.readBool(st);
5481 // UID игрока
5482 FUID := utils.readWord(st);
5483 // Имя игрока
5484 str := utils.readStr(st);
5485 if (self <> gPlayer1) and (self <> gPlayer2) then FName := str;
5486 // Команда
5487 FTeam := utils.readByte(st);
5488 // Жив ли
5489 FAlive := utils.readBool(st);
5490 // Израсходовал ли все жизни
5491 FNoRespawn := utils.readBool(st);
5492 // Направление
5493 b := utils.readByte(st);
5494 if b = 1 then FDirection := TDirection.D_LEFT else FDirection := TDirection.D_RIGHT; // b = 2
5495 // Здоровье
5496 FHealth := utils.readLongInt(st);
5497 // Коэффициент инвалидности
5498 FHandicap := utils.readLongInt(st);
5499 // Жизни
5500 FLives := utils.readByte(st);
5501 // Броня
5502 FArmor := utils.readLongInt(st);
5503 // Запас воздуха
5504 FAir := utils.readLongInt(st);
5505 // Запас горючего
5506 FJetFuel := utils.readLongInt(st);
5507 // Боль
5508 FPain := utils.readLongInt(st);
5509 // Убил
5510 FKills := utils.readLongInt(st);
5511 // Убил монстров
5512 FMonsterKills := utils.readLongInt(st);
5513 // Фрагов
5514 FFrags := utils.readLongInt(st);
5515 // Фрагов подряд
5516 FFragCombo := utils.readByte(st);
5517 // Время последнего фрага
5518 FLastFrag := utils.readLongWord(st);
5519 // Смертей
5520 FDeath := utils.readLongInt(st);
5521 // Какой флаг несет
5522 FFlag := utils.readByte(st);
5523 // Нашел секретов
5524 FSecrets := utils.readLongInt(st);
5525 // Текущее оружие
5526 FCurrWeap := utils.readByte(st);
5527 // Желаемое оружие
5528 FNextWeap := utils.readWord(st);
5529 // ...и пауза
5530 FNextWeapDelay := utils.readByte(st);
5531 // Время зарядки BFG
5532 FBFGFireCounter := utils.readSmallInt(st);
5533 // Буфер урона
5534 FDamageBuffer := utils.readLongInt(st);
5535 // Последний ударивший
5536 FLastSpawnerUID := utils.readWord(st);
5537 // Тип последнего полученного урона
5538 FLastHit := utils.readByte(st);
5539 // Объект игрока
5540 Obj_LoadState(@FObj, st);
5541 // Текущее количество патронов
5542 for i := A_BULLETS to A_HIGH do FAmmo[i] := utils.readWord(st);
5543 // Максимальное количество патронов
5544 for i := A_BULLETS to A_HIGH do FMaxAmmo[i] := utils.readWord(st);
5545 // Наличие оружия
5546 for i := WP_FIRST to WP_LAST do FWeapon[i] := utils.readBool(st);
5547 // Время перезарядки оружия
5548 for i := WP_FIRST to WP_LAST do FReloading[i] := utils.readWord(st);
5549 // Наличие рюкзака
5550 if utils.readBool(st) then Include(FRulez, R_ITEM_BACKPACK);
5551 // Наличие красного ключа
5552 if utils.readBool(st) then Include(FRulez, R_KEY_RED);
5553 // Наличие зеленого ключа
5554 if utils.readBool(st) then Include(FRulez, R_KEY_GREEN);
5555 // Наличие синего ключа
5556 if utils.readBool(st) then Include(FRulez, R_KEY_BLUE);
5557 // Наличие берсерка
5558 if utils.readBool(st) then Include(FRulez, R_BERSERK);
5559 // Время действия специальных предметов
5560 for i := MR_SUIT to MR_MAX do FMegaRulez[i] := utils.readLongWord(st);
5561 // Время до повторного респауна, смены оружия, исользования, захвата флага
5562 for i := T_RESPAWN to T_FLAGCAP do FTime[i] := utils.readLongWord(st);
5563 // Название модели
5564 str := utils.readStr(st);
5565 // Цвет модели
5566 FColor.R := utils.readByte(st);
5567 FColor.G := utils.readByte(st);
5568 FColor.B := utils.readByte(st);
5569 if (self = gPlayer1) then
5570 begin
5571 str := gPlayer1Settings.Model;
5572 FColor := gPlayer1Settings.Color;
5573 end
5574 else if (self = gPlayer2) then
5575 begin
5576 str := gPlayer2Settings.Model;
5577 FColor := gPlayer2Settings.Color;
5578 end;
5579 // Обновляем модель игрока
5580 SetModel(str);
5581 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
5582 FModel.Color := TEAMCOLOR[FTeam]
5583 else
5584 FModel.Color := FColor;
5585 end;
5588 procedure TPlayer.AllRulez(Health: Boolean);
5589 var
5590 a: Integer;
5591 begin
5592 if Health then
5593 begin
5594 FHealth := PLAYER_HP_LIMIT;
5595 FArmor := PLAYER_AP_LIMIT;
5596 Exit;
5597 end;
5599 for a := WP_FIRST to WP_LAST do FWeapon[a] := True;
5600 for a := A_BULLETS to A_HIGH do FAmmo[a] := 30000;
5601 FRulez := FRulez+[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5602 end;
5604 procedure TPlayer.RestoreHealthArmor();
5605 begin
5606 FHealth := PLAYER_HP_LIMIT;
5607 FArmor := PLAYER_AP_LIMIT;
5608 end;
5610 procedure TPlayer.FragCombo();
5611 var
5612 Param: Integer;
5613 begin
5614 if (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) or g_Game_IsClient then
5615 Exit;
5616 if gTime - FLastFrag < FRAG_COMBO_TIME then
5617 begin
5618 if FFragCombo < 5 then
5619 Inc(FFragCombo);
5620 Param := FUID or (FFragCombo shl 16);
5621 if (FComboEvnt >= Low(gDelayedEvents)) and
5622 (FComboEvnt <= High(gDelayedEvents)) and
5623 gDelayedEvents[FComboEvnt].Pending and
5624 (gDelayedEvents[FComboEvnt].DEType = DE_KILLCOMBO) and
5625 (gDelayedEvents[FComboEvnt].DENum and $FFFF = FUID) then
5626 begin
5627 gDelayedEvents[FComboEvnt].Time := gTime + 500;
5628 gDelayedEvents[FComboEvnt].DENum := Param;
5629 end
5630 else
5631 FComboEvnt := g_Game_DelayEvent(DE_KILLCOMBO, 500, Param);
5632 end
5633 else
5634 FFragCombo := 1;
5636 FLastFrag := gTime;
5637 end;
5639 procedure TPlayer.GiveItem(ItemType: Byte);
5640 begin
5641 case ItemType of
5642 ITEM_SUIT:
5643 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
5644 begin
5645 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
5646 end;
5648 ITEM_OXYGEN:
5649 if FAir < AIR_MAX then
5650 begin
5651 FAir := AIR_MAX;
5652 end;
5654 ITEM_MEDKIT_BLACK:
5655 begin
5656 if not (R_BERSERK in FRulez) then
5657 begin
5658 Include(FRulez, R_BERSERK);
5659 if FBFGFireCounter < 1 then
5660 begin
5661 FCurrWeap := WEAPON_KASTET;
5662 resetWeaponQueue();
5663 FModel.SetWeapon(WEAPON_KASTET);
5664 end;
5665 if gFlash <> 0 then
5666 Inc(FPain, 100);
5667 FBerserk := gTime+30000;
5668 end;
5669 if FHealth < PLAYER_HP_SOFT then
5670 begin
5671 FHealth := PLAYER_HP_SOFT;
5672 FBerserk := gTime+30000;
5673 end;
5674 end;
5676 ITEM_INVUL:
5677 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
5678 begin
5679 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
5680 FSpawnInvul := 0;
5681 end;
5683 ITEM_INVIS:
5684 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
5685 begin
5686 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
5687 end;
5689 ITEM_JETPACK:
5690 if FJetFuel < JET_MAX then
5691 begin
5692 FJetFuel := JET_MAX;
5693 end;
5695 ITEM_MEDKIT_SMALL: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
5696 ITEM_MEDKIT_LARGE: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
5698 ITEM_ARMOR_GREEN: if FArmor < PLAYER_AP_SOFT then FArmor := PLAYER_AP_SOFT;
5699 ITEM_ARMOR_BLUE: if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5701 ITEM_SPHERE_BLUE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
5702 ITEM_SPHERE_WHITE:
5703 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) then
5704 begin
5705 if FHealth < PLAYER_HP_LIMIT then FHealth := PLAYER_HP_LIMIT;
5706 if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5707 end;
5709 ITEM_WEAPON_SAW: FWeapon[WEAPON_SAW] := True;
5710 ITEM_WEAPON_SHOTGUN1: FWeapon[WEAPON_SHOTGUN1] := True;
5711 ITEM_WEAPON_SHOTGUN2: FWeapon[WEAPON_SHOTGUN2] := True;
5712 ITEM_WEAPON_CHAINGUN: FWeapon[WEAPON_CHAINGUN] := True;
5713 ITEM_WEAPON_ROCKETLAUNCHER: FWeapon[WEAPON_ROCKETLAUNCHER] := True;
5714 ITEM_WEAPON_PLASMA: FWeapon[WEAPON_PLASMA] := True;
5715 ITEM_WEAPON_BFG: FWeapon[WEAPON_BFG] := True;
5716 ITEM_WEAPON_SUPERPULEMET: FWeapon[WEAPON_SUPERPULEMET] := True;
5717 ITEM_WEAPON_FLAMETHROWER: FWeapon[WEAPON_FLAMETHROWER] := True;
5719 ITEM_AMMO_BULLETS: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5720 ITEM_AMMO_BULLETS_BOX: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
5721 ITEM_AMMO_SHELLS: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5722 ITEM_AMMO_SHELLS_BOX: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
5723 ITEM_AMMO_ROCKET: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5724 ITEM_AMMO_ROCKET_BOX: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
5725 ITEM_AMMO_CELL: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5726 ITEM_AMMO_CELL_BIG: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
5727 ITEM_AMMO_FUELCAN: if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
5729 ITEM_AMMO_BACKPACK:
5730 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
5731 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
5732 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
5733 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
5734 (FMaxAmmo[A_FUEL] < AmmoLimits[1, A_FUEL]) then
5735 begin
5736 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
5737 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
5738 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
5739 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
5740 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
5742 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5743 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5744 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5745 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5747 FRulez := FRulez + [R_ITEM_BACKPACK];
5748 end;
5750 ITEM_KEY_RED: if not (R_KEY_RED in FRulez) then Include(FRulez, R_KEY_RED);
5751 ITEM_KEY_GREEN: if not (R_KEY_GREEN in FRulez) then Include(FRulez, R_KEY_GREEN);
5752 ITEM_KEY_BLUE: if not (R_KEY_BLUE in FRulez) then Include(FRulez, R_KEY_BLUE);
5754 ITEM_BOTTLE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
5755 ITEM_HELMET: if FArmor < PLAYER_AP_LIMIT then IncMax(FArmor, 5, PLAYER_AP_LIMIT);
5757 else
5758 Exit;
5759 end;
5760 if g_Game_IsNet and g_Game_IsServer then
5761 MH_SEND_PlayerStats(FUID);
5762 end;
5764 procedure TPlayer.FlySmoke(Times: DWORD = 1);
5765 var
5766 id, i: DWORD;
5767 Anim: TAnimation;
5768 begin
5769 if (Random(5) = 1) and (Times = 1) then
5770 Exit;
5772 if BodyInLiquid(0, 0) then
5773 begin
5774 g_GFX_Bubbles(Obj.X+Obj.Rect.X+(Obj.Rect.Width div 2)+Random(3)-1,
5775 Obj.Y+Obj.Rect.Height+8, 1, 8, 4);
5776 if Random(2) = 0
5777 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
5778 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
5779 Exit;
5780 end;
5782 if g_Frames_Get(id, 'FRAMES_SMOKE') then
5783 begin
5784 for i := 1 to Times do
5785 begin
5786 Anim := TAnimation.Create(id, False, 3);
5787 Anim.Alpha := 150;
5788 g_GFX_OnceAnim(Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(Anim.Width div 2),
5789 Obj.Y+Obj.Rect.Height-4+Random(8+Times*2), Anim, ONCEANIM_SMOKE);
5790 Anim.Free();
5791 end;
5792 end;
5793 end;
5795 procedure TPlayer.OnFireFlame(Times: DWORD = 1);
5796 var
5797 id, i: DWORD;
5798 Anim: TAnimation;
5799 begin
5800 if (Random(10) = 1) and (Times = 1) then
5801 Exit;
5803 if g_Frames_Get(id, 'FRAMES_FLAME') then
5804 begin
5805 for i := 1 to Times do
5806 begin
5807 Anim := TAnimation.Create(id, False, 3);
5808 Anim.Alpha := 0;
5809 g_GFX_OnceAnim(Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(Anim.Width div 2),
5810 Obj.Y+8+Random(8+Times*2), Anim, ONCEANIM_SMOKE);
5811 Anim.Free();
5812 end;
5813 end;
5814 end;
5816 procedure TPlayer.PauseSounds(Enable: Boolean);
5817 begin
5818 FSawSound.Pause(Enable);
5819 FSawSoundIdle.Pause(Enable);
5820 FSawSoundHit.Pause(Enable);
5821 FSawSoundSelect.Pause(Enable);
5822 FFlameSoundOn.Pause(Enable);
5823 FFlameSoundOff.Pause(Enable);
5824 FFlameSoundWork.Pause(Enable);
5825 FJetSoundFly.Pause(Enable);
5826 FJetSoundOn.Pause(Enable);
5827 FJetSoundOff.Pause(Enable);
5828 end;
5830 { T C o r p s e : }
5832 constructor TCorpse.Create(X, Y: Integer; ModelName: String; aMess: Boolean);
5833 begin
5834 g_Obj_Init(@FObj);
5835 FObj.X := X;
5836 FObj.Y := Y;
5837 FObj.Rect := PLAYER_CORPSERECT;
5838 FModelName := ModelName;
5839 FMess := aMess;
5841 if FMess then
5842 begin
5843 FState := CORPSE_STATE_MESS;
5844 g_PlayerModel_GetAnim(ModelName, A_DIE2, FAnimation, FAnimationMask);
5845 end
5846 else
5847 begin
5848 FState := CORPSE_STATE_NORMAL;
5849 g_PlayerModel_GetAnim(ModelName, A_DIE1, FAnimation, FAnimationMask);
5850 end;
5851 end;
5853 destructor TCorpse.Destroy();
5854 begin
5855 FAnimation.Free();
5857 inherited;
5858 end;
5860 function TCorpse.ObjPtr (): PObj; inline; begin result := @FObj; end;
5862 procedure TCorpse.positionChanged (); inline; begin end;
5864 procedure TCorpse.moveBy (dx, dy: Integer); inline;
5865 begin
5866 if (dx <> 0) or (dy <> 0) then
5867 begin
5868 FObj.X += dx;
5869 FObj.Y += dy;
5870 positionChanged();
5871 end;
5872 end;
5875 procedure TCorpse.getMapBox (out x, y, w, h: Integer); inline;
5876 begin
5877 x := FObj.X+PLAYER_CORPSERECT.X;
5878 y := FObj.Y+PLAYER_CORPSERECT.Y;
5879 w := PLAYER_CORPSERECT.Width;
5880 h := PLAYER_CORPSERECT.Height;
5881 end;
5884 procedure TCorpse.Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
5885 var
5886 pm: TPlayerModel;
5887 Blood: TModelBlood;
5888 begin
5889 if FState = CORPSE_STATE_REMOVEME then
5890 Exit;
5892 FDamage := FDamage + Value;
5894 if FDamage > 150 then
5895 begin
5896 if FAnimation <> nil then
5897 begin
5898 FAnimation.Free();
5899 FAnimation := nil;
5901 FState := CORPSE_STATE_REMOVEME;
5903 g_Player_CreateGibs(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
5904 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
5905 FModelName, FColor);
5906 // Звук мяса от трупа:
5907 pm := g_PlayerModel_Get(FModelName);
5908 pm.PlaySound(MODELSOUND_DIE, 5, FObj.X, FObj.Y);
5909 pm.Free;
5911 // Зловещий смех:
5912 if (gBodyKillEvent <> -1)
5913 and gDelayedEvents[gBodyKillEvent].Pending then
5914 gDelayedEvents[gBodyKillEvent].Pending := False;
5915 gBodyKillEvent := g_Game_DelayEvent(DE_BODYKILL, 1050, SpawnerUID);
5916 end;
5917 end
5918 else
5919 begin
5920 Blood := g_PlayerModel_GetBlood(FModelName);
5921 FObj.Vel.X := FObj.Vel.X + vx;
5922 FObj.Vel.Y := FObj.Vel.Y + vy;
5923 g_GFX_Blood(FObj.X+PLAYER_CORPSERECT.X+(PLAYER_CORPSERECT.Width div 2),
5924 FObj.Y+PLAYER_CORPSERECT.Y+(PLAYER_CORPSERECT.Height div 2),
5925 Value, vx, vy, 16, (PLAYER_CORPSERECT.Height*2) div 3,
5926 Blood.R, Blood.G, Blood.B, Blood.Kind);
5927 end;
5928 end;
5930 procedure TCorpse.Update();
5931 var
5932 st: Word;
5933 begin
5934 if FState = CORPSE_STATE_REMOVEME then
5935 Exit;
5937 FObj.oldX := FObj.X;
5938 FObj.oldY := FObj.Y;
5940 if gTime mod (GAME_TICK*2) <> 0 then
5941 begin
5942 g_Obj_Move(@FObj, True, True, True);
5943 positionChanged(); // this updates spatial accelerators
5944 Exit;
5945 end;
5947 // Сопротивление воздуха для трупа:
5948 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
5950 st := g_Obj_Move(@FObj, True, True, True);
5951 positionChanged(); // this updates spatial accelerators
5953 if WordBool(st and MOVE_FALLOUT) then
5954 begin
5955 FState := CORPSE_STATE_REMOVEME;
5956 Exit;
5957 end;
5959 if FAnimation <> nil then
5960 FAnimation.Update();
5961 if FAnimationMask <> nil then
5962 FAnimationMask.Update();
5963 end;
5966 procedure TCorpse.SaveState (st: TStream);
5967 var
5968 anim: Boolean;
5969 begin
5970 assert(st <> nil);
5972 // Сигнатура трупа
5973 utils.writeSign(st, 'CORP');
5974 utils.writeInt(st, Byte(0));
5975 // Состояние
5976 utils.writeInt(st, Byte(FState));
5977 // Накопленный урон
5978 utils.writeInt(st, Byte(FDamage));
5979 // Цвет
5980 utils.writeInt(st, Byte(FColor.R));
5981 utils.writeInt(st, Byte(FColor.G));
5982 utils.writeInt(st, Byte(FColor.B));
5983 // Объект трупа
5984 Obj_SaveState(st, @FObj);
5985 utils.writeInt(st, Word(FPlayerUID));
5986 // Есть ли анимация
5987 anim := (FAnimation <> nil);
5988 utils.writeBool(st, anim);
5989 // Если есть - сохраняем
5990 if anim then FAnimation.SaveState(st);
5991 // Есть ли маска анимации
5992 anim := (FAnimationMask <> nil);
5993 utils.writeBool(st, anim);
5994 // Если есть - сохраняем
5995 if anim then FAnimationMask.SaveState(st);
5996 end;
5999 procedure TCorpse.LoadState (st: TStream);
6000 var
6001 anim: Boolean;
6002 begin
6003 assert(st <> nil);
6005 // Сигнатура трупа
6006 if not utils.checkSign(st, 'CORP') then raise XStreamError.Create('invalid corpse signature');
6007 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid corpse version');
6008 // Состояние
6009 FState := utils.readByte(st);
6010 // Накопленный урон
6011 FDamage := utils.readByte(st);
6012 // Цвет
6013 FColor.R := utils.readByte(st);
6014 FColor.G := utils.readByte(st);
6015 FColor.B := utils.readByte(st);
6016 // Объект трупа
6017 Obj_LoadState(@FObj, st);
6018 FPlayerUID := utils.readWord(st);
6019 // Есть ли анимация
6020 anim := utils.readBool(st);
6021 // Если есть - загружаем
6022 if anim then
6023 begin
6024 Assert(FAnimation <> nil, 'TCorpse.LoadState: no FAnimation');
6025 FAnimation.LoadState(st);
6026 end;
6027 // Есть ли маска анимации
6028 anim := utils.readBool(st);
6029 // Если есть - загружаем
6030 if anim then
6031 begin
6032 Assert(FAnimationMask <> nil, 'TCorpse.LoadState: no FAnimationMask');
6033 FAnimationMask.LoadState(st);
6034 end;
6035 end;
6037 { T B o t : }
6039 constructor TBot.Create();
6040 var
6041 a: Integer;
6042 begin
6043 inherited Create();
6045 FPhysics := True;
6046 FSpectator := False;
6047 FGhost := False;
6049 FIamBot := True;
6051 Inc(gNumBots);
6053 for a := WP_FIRST to WP_LAST do
6054 begin
6055 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
6056 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
6057 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
6058 end;
6059 end;
6061 destructor TBot.Destroy();
6062 begin
6063 Dec(gNumBots);
6064 inherited Destroy();
6065 end;
6067 procedure TBot.Respawn(Silent: Boolean; Force: Boolean = False);
6068 begin
6069 inherited Respawn(Silent, Force);
6071 FAIFlags := nil;
6072 FSelectedWeapon := FCurrWeap;
6073 resetWeaponQueue();
6074 FTargetUID := 0;
6075 end;
6077 procedure TBot.UpdateCombat();
6078 type
6079 TTarget = record
6080 UID: Word;
6081 X, Y: Integer;
6082 Rect: TRectWH;
6083 cX, cY: Integer;
6084 Dist: Word;
6085 Line: Boolean;
6086 Visible: Boolean;
6087 IsPlayer: Boolean;
6088 end;
6090 TTargetRecord = array of TTarget;
6092 function Compare(a, b: TTarget): Integer;
6093 begin
6094 if a.Line and not b.Line then // A на линии огня
6095 Result := -1
6096 else
6097 if not a.Line and b.Line then // B на линии огня
6098 Result := 1
6099 else // И A, и B на линии или не на линии огня
6100 if (a.Line and b.Line) or ((not a.Line) and (not b.Line)) then
6101 begin
6102 if a.Dist > b.Dist then // B ближе
6103 Result := 1
6104 else // A ближе или равноудаленно с B
6105 Result := -1;
6106 end
6107 else // Странно -> A
6108 Result := -1;
6109 end;
6111 var
6112 a, x1, y1, x2, y2: Integer;
6113 targets: TTargetRecord;
6114 ammo: Word;
6115 Target, BestTarget: TTarget;
6116 firew, fireh: Integer;
6117 angle: SmallInt;
6118 mon: TMonster;
6119 pla, tpla: TPlayer;
6120 vsPlayer, vsMonster, ok: Boolean;
6123 function monsUpdate (mon: TMonster): Boolean;
6124 begin
6125 result := false; // don't stop
6126 if mon.alive and (mon.MonsterType <> MONSTER_BARREL) then
6127 begin
6128 if not TargetOnScreen(mon.Obj.X+mon.Obj.Rect.X, mon.Obj.Y+mon.Obj.Rect.Y) then exit;
6130 x2 := mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2);
6131 y2 := mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2);
6133 // Если монстр на экране и не прикрыт стеной
6134 if g_TraceVector(x1, y1, x2, y2) then
6135 begin
6136 // Добавляем к списку возможных целей
6137 SetLength(targets, Length(targets)+1);
6138 with targets[High(targets)] do
6139 begin
6140 UID := mon.UID;
6141 X := mon.Obj.X;
6142 Y := mon.Obj.Y;
6143 cX := x2;
6144 cY := y2;
6145 Rect := mon.Obj.Rect;
6146 Dist := g_PatchLength(x1, y1, x2, y2);
6147 Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6148 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6149 Visible := True;
6150 IsPlayer := False;
6151 end;
6152 end;
6153 end;
6154 end;
6156 begin
6157 vsPlayer := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER);
6158 vsMonster := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER);
6160 // Если текущее оружие не то, что нужно, то меняем:
6161 if FCurrWeap <> FSelectedWeapon then
6162 NextWeapon();
6164 // Если нужно стрелять и нужное оружие, то нажать "Стрелять":
6165 if (GetAIFlag('NEEDFIRE') <> '') and (FCurrWeap = FSelectedWeapon) then
6166 begin
6167 RemoveAIFlag('NEEDFIRE');
6169 case FCurrWeap of
6170 WEAPON_PLASMA, WEAPON_SUPERPULEMET, WEAPON_CHAINGUN: PressKey(KEY_FIRE, 20);
6171 WEAPON_SAW, WEAPON_KASTET, WEAPON_FLAMETHROWER: PressKey(KEY_FIRE, 40);
6172 else PressKey(KEY_FIRE);
6173 end;
6174 end;
6176 // Координаты ствола:
6177 x1 := FObj.X + WEAPONPOINT[FDirection].X;
6178 y1 := FObj.Y + WEAPONPOINT[FDirection].Y;
6180 Target.UID := FTargetUID;
6182 ok := False;
6183 if Target.UID <> 0 then
6184 begin // Цель есть - настраиваем
6185 if (g_GetUIDType(Target.UID) = UID_PLAYER) and
6186 vsPlayer then
6187 begin // Игрок
6188 tpla := g_Player_Get(Target.UID);
6189 if tpla <> nil then
6190 with tpla do
6191 begin
6192 if (@FObj) <> nil then
6193 begin
6194 Target.X := FObj.X;
6195 Target.Y := FObj.Y;
6196 end;
6197 end;
6199 Target.cX := Target.X + PLAYER_RECT_CX;
6200 Target.cY := Target.Y + PLAYER_RECT_CY;
6201 Target.Rect := PLAYER_RECT;
6202 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6203 Target.Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6204 (y1-4 > Target.Y+PLAYER_RECT.Y);
6205 Target.IsPlayer := True;
6206 ok := True;
6207 end
6208 else
6209 if (g_GetUIDType(Target.UID) = UID_MONSTER) and
6210 vsMonster then
6211 begin // Монстр
6212 mon := g_Monsters_ByUID(Target.UID);
6213 if mon <> nil then
6214 begin
6215 Target.X := mon.Obj.X;
6216 Target.Y := mon.Obj.Y;
6218 Target.cX := Target.X + mon.Obj.Rect.X + (mon.Obj.Rect.Width div 2);
6219 Target.cY := Target.Y + mon.Obj.Rect.Y + (mon.Obj.Rect.Height div 2);
6220 Target.Rect := mon.Obj.Rect;
6221 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6222 Target.Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6223 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6224 Target.IsPlayer := False;
6225 ok := True;
6226 end;
6227 end;
6228 end;
6230 if not ok then
6231 begin // Цели нет - обнуляем
6232 Target.X := 0;
6233 Target.Y := 0;
6234 Target.cX := 0;
6235 Target.cY := 0;
6236 Target.Visible := False;
6237 Target.Line := False;
6238 Target.IsPlayer := False;
6239 end;
6241 targets := nil;
6243 // Если цель не видима или не на линии огня, то ищем все возможные цели:
6244 if (not Target.Line) or (not Target.Visible) then
6245 begin
6246 // Игроки:
6247 if vsPlayer then
6248 for a := 0 to High(gPlayers) do
6249 if (gPlayers[a] <> nil) and (gPlayers[a].alive) and
6250 (gPlayers[a].FUID <> FUID) and
6251 (not SameTeam(FUID, gPlayers[a].FUID)) and
6252 (not gPlayers[a].NoTarget) and
6253 (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
6254 begin
6255 if not TargetOnScreen(gPlayers[a].FObj.X + PLAYER_RECT.X,
6256 gPlayers[a].FObj.Y + PLAYER_RECT.Y) then
6257 Continue;
6259 x2 := gPlayers[a].FObj.X + PLAYER_RECT_CX;
6260 y2 := gPlayers[a].FObj.Y + PLAYER_RECT_CY;
6262 // Если игрок на экране и не прикрыт стеной:
6263 if g_TraceVector(x1, y1, x2, y2) then
6264 begin
6265 // Добавляем к списку возможных целей:
6266 SetLength(targets, Length(targets)+1);
6267 with targets[High(targets)] do
6268 begin
6269 UID := gPlayers[a].FUID;
6270 X := gPlayers[a].FObj.X;
6271 Y := gPlayers[a].FObj.Y;
6272 cX := x2;
6273 cY := y2;
6274 Rect := PLAYER_RECT;
6275 Dist := g_PatchLength(x1, y1, x2, y2);
6276 Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6277 (y1-4 > Target.Y+PLAYER_RECT.Y);
6278 Visible := True;
6279 IsPlayer := True;
6280 end;
6281 end;
6282 end;
6284 // Монстры:
6285 if vsMonster then g_Mons_ForEach(monsUpdate);
6286 end;
6288 // Если есть возможные цели:
6289 // (Выбираем лучшую, меняем оружие и бежим к ней/от нее)
6290 if targets <> nil then
6291 begin
6292 // Выбираем наилучшую цель:
6293 BestTarget := targets[0];
6294 if Length(targets) > 1 then
6295 for a := 1 to High(targets) do
6296 if Compare(BestTarget, targets[a]) = 1 then
6297 BestTarget := targets[a];
6299 // Если лучшая цель "виднее" текущей, то текущая := лучшая:
6300 if ((not Target.Visible) and BestTarget.Visible and (Target.UID <> BestTarget.UID)) or
6301 ((not Target.Line) and BestTarget.Line and BestTarget.Visible) then
6302 begin
6303 Target := BestTarget;
6305 if (Healthy() = 3) or ((Healthy() = 2)) then
6306 begin // Если здоровы - догоняем
6307 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6308 SetAIFlag('GORIGHT', '1');
6309 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6310 SetAIFlag('GOLEFT', '1');
6311 end
6312 else
6313 begin // Если побиты - убегаем
6314 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6315 SetAIFlag('GORIGHT', '1');
6316 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6317 SetAIFlag('GOLEFT', '1');
6318 end;
6320 // Выбираем оружие на основе расстояния и приоритетов:
6321 SelectWeapon(Abs(x1-Target.cX));
6322 end;
6323 end;
6325 // Если есть цель:
6326 // (Догоняем/убегаем, стреляем по направлению к цели)
6327 // (Если цель далеко, то хватит следить за ней)
6328 if Target.UID <> 0 then
6329 begin
6330 if not TargetOnScreen(Target.X + Target.Rect.X,
6331 Target.Y + Target.Rect.Y) then
6332 begin // Цель сбежала с "экрана"
6333 if (Healthy() = 3) or ((Healthy() = 2)) then
6334 begin // Если здоровы - догоняем
6335 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6336 SetAIFlag('GORIGHT', '1');
6337 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6338 SetAIFlag('GOLEFT', '1');
6339 end
6340 else
6341 begin // Если побиты - забываем о цели и убегаем
6342 Target.UID := 0;
6343 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6344 SetAIFlag('GORIGHT', '1');
6345 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6346 SetAIFlag('GOLEFT', '1');
6347 end;
6348 end
6349 else
6350 begin // Цель пока на "экране"
6351 // Если цель не загорожена стеной, то отмечаем, когда ее видели:
6352 if g_TraceVector(x1, y1, Target.cX, Target.cY) then
6353 FLastVisible := gTime;
6354 // Если разница высот не велика, то догоняем:
6355 if (Abs(FObj.Y-Target.Y) <= 128) then
6356 begin
6357 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6358 SetAIFlag('GORIGHT', '1');
6359 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6360 SetAIFlag('GOLEFT', '1');
6361 end;
6362 end;
6364 // Выбираем угол вверх:
6365 if FDirection = TDirection.D_LEFT then
6366 angle := ANGLE_LEFTUP
6367 else
6368 angle := ANGLE_RIGHTUP;
6370 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6371 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6373 // Если при угле вверх можно попасть в приблизительное положение цели:
6374 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6375 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128), //96
6376 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6377 Target.Rect.Width, Target.Rect.Height) and
6378 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6379 begin // то нужно стрелять вверх
6380 SetAIFlag('NEEDFIRE', '1');
6381 SetAIFlag('NEEDSEEUP', '1');
6382 end;
6384 // Выбираем угол вниз:
6385 if FDirection = TDirection.D_LEFT then
6386 angle := ANGLE_LEFTDOWN
6387 else
6388 angle := ANGLE_RIGHTDOWN;
6390 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6391 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6393 // Если при угле вниз можно попасть в приблизительное положение цели:
6394 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6395 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6396 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6397 Target.Rect.Width, Target.Rect.Height) and
6398 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6399 begin // то нужно стрелять вниз
6400 SetAIFlag('NEEDFIRE', '1');
6401 SetAIFlag('NEEDSEEDOWN', '1');
6402 end;
6404 // Если цель видно и она на такой же высоте:
6405 if Target.Visible and
6406 (y1+4 < Target.Y+Target.Rect.Y+Target.Rect.Height) and
6407 (y1-4 > Target.Y+Target.Rect.Y) then
6408 begin
6409 // Если идем в сторону цели, то надо стрелять:
6410 if ((FDirection = TDirection.D_LEFT) and (Target.X < FObj.X)) or
6411 ((FDirection = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6412 begin // то нужно стрелять вперед
6413 SetAIFlag('NEEDFIRE', '1');
6414 SetAIFlag('NEEDSEEDOWN', '');
6415 SetAIFlag('NEEDSEEUP', '');
6416 end;
6417 // Если цель в пределах "экрана" и сложность позволяет прыжки сближения:
6418 if Abs(FObj.X-Target.X) < Trunc(gPlayerScreenSize.X*0.75) then
6419 if GetRnd(FDifficult.CloseJump) then
6420 begin // то если повезет - прыгаем (особенно, если близко)
6421 if Abs(FObj.X-Target.X) < 128 then
6422 a := 4
6423 else
6424 a := 30;
6425 if Random(a) = 0 then
6426 SetAIFlag('NEEDJUMP', '1');
6427 end;
6428 end;
6430 // Если цель все еще есть:
6431 if Target.UID <> 0 then
6432 if gTime-FLastVisible > 2000 then // Если видели давно
6433 Target.UID := 0 // то забыть цель
6434 else // Если видели недавно
6435 begin // но цель убили
6436 if Target.IsPlayer then
6437 begin // Цель - игрок
6438 pla := g_Player_Get(Target.UID);
6439 if (pla = nil) or (not pla.alive) or pla.NoTarget or
6440 (pla.FMegaRulez[MR_INVIS] >= gTime) then
6441 Target.UID := 0; // то забыть цель
6442 end
6443 else
6444 begin // Цель - монстр
6445 mon := g_Monsters_ByUID(Target.UID);
6446 if (mon = nil) or (not mon.alive) then
6447 Target.UID := 0; // то забыть цель
6448 end;
6449 end;
6450 end; // if Target.UID <> 0
6452 FTargetUID := Target.UID;
6454 // Если возможных целей нет:
6455 // (Атака чего-нибудь слева или справа)
6456 if targets = nil then
6457 if GetAIFlag('ATTACKLEFT') <> '' then
6458 begin // Если нужно атаковать налево
6459 RemoveAIFlag('ATTACKLEFT');
6461 SetAIFlag('NEEDJUMP', '1');
6463 if RunDirection() = TDirection.D_RIGHT then
6464 begin // Идем не в ту сторону
6465 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6466 begin // Если здоровы, то, возможно, стреляем бежим влево и стреляем
6467 SetAIFlag('NEEDFIRE', '1');
6468 SetAIFlag('GOLEFT', '1');
6469 end;
6470 end
6471 else
6472 begin // Идем в нужную сторону
6473 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6474 SetAIFlag('NEEDFIRE', '1');
6475 if Healthy() <= 1 then // Побиты - убегаем
6476 SetAIFlag('GORIGHT', '1');
6477 end;
6478 end
6479 else
6480 if GetAIFlag('ATTACKRIGHT') <> '' then
6481 begin // Если нужно атаковать направо
6482 RemoveAIFlag('ATTACKRIGHT');
6484 SetAIFlag('NEEDJUMP', '1');
6486 if RunDirection() = TDirection.D_LEFT then
6487 begin // Идем не в ту сторону
6488 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6489 begin // Если здоровы, то, возможно, бежим вправо и стреляем
6490 SetAIFlag('NEEDFIRE', '1');
6491 SetAIFlag('GORIGHT', '1');
6492 end;
6493 end
6494 else
6495 begin
6496 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6497 SetAIFlag('NEEDFIRE', '1');
6498 if Healthy() <= 1 then // Побиты - убегаем
6499 SetAIFlag('GOLEFT', '1');
6500 end;
6501 end;
6503 //HACK! (does it belongs there?)
6504 RealizeCurrentWeapon();
6506 // Если есть возможные цели:
6507 // (Стреляем по направлению к целям)
6508 if (targets <> nil) and (GetAIFlag('NEEDFIRE') <> '') then
6509 for a := 0 to High(targets) do
6510 begin
6511 // Если можем стрелять по диагонали:
6512 if GetRnd(FDifficult.DiagFire) then
6513 begin
6514 // Ищем цель сверху и стреляем, если есть:
6515 if FDirection = TDirection.D_LEFT then
6516 angle := ANGLE_LEFTUP
6517 else
6518 angle := ANGLE_RIGHTUP;
6520 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6521 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6523 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6524 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6525 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6526 targets[a].Rect.Width, targets[a].Rect.Height) and
6527 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6528 begin
6529 SetAIFlag('NEEDFIRE', '1');
6530 SetAIFlag('NEEDSEEUP', '1');
6531 end;
6533 // Ищем цель снизу и стреляем, если есть:
6534 if FDirection = TDirection.D_LEFT then
6535 angle := ANGLE_LEFTDOWN
6536 else
6537 angle := ANGLE_RIGHTDOWN;
6539 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6540 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6542 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6543 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6544 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6545 targets[a].Rect.Width, targets[a].Rect.Height) and
6546 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6547 begin
6548 SetAIFlag('NEEDFIRE', '1');
6549 SetAIFlag('NEEDSEEDOWN', '1');
6550 end;
6551 end;
6553 // Если цель "перед носом", то стреляем:
6554 if targets[a].Line and targets[a].Visible and
6555 (((FDirection = TDirection.D_LEFT) and (targets[a].X < FObj.X)) or
6556 ((FDirection = TDirection.D_RIGHT) and (targets[a].X > FObj.X))) then
6557 begin
6558 SetAIFlag('NEEDFIRE', '1');
6559 Break;
6560 end;
6561 end;
6563 // Если летит пуля, то, возможно, подпрыгиваем:
6564 if g_Weapon_Danger(FUID, FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y,
6565 PLAYER_RECT.Width, PLAYER_RECT.Height,
6566 40+GetInterval(FDifficult.Cover, 40)) then
6567 SetAIFlag('NEEDJUMP', '1');
6569 // Если кончились паторны, то нужно сменить оружие:
6570 ammo := GetAmmoByWeapon(FCurrWeap);
6571 if ((FCurrWeap = WEAPON_SHOTGUN2) and (ammo < 2)) or
6572 ((FCurrWeap = WEAPON_BFG) and (ammo < 40)) or
6573 (ammo = 0) then
6574 SetAIFlag('SELECTWEAPON', '1');
6576 // Если нужно сменить оружие, то выбираем нужное:
6577 if GetAIFlag('SELECTWEAPON') = '1' then
6578 begin
6579 SelectWeapon(-1);
6580 RemoveAIFlag('SELECTWEAPON');
6581 end;
6582 end;
6584 procedure TBot.Update();
6585 var
6586 EnableAI: Boolean;
6587 begin
6588 if not FAlive then
6589 begin // Respawn
6590 ReleaseKeys();
6591 PressKey(KEY_UP);
6592 end
6593 else
6594 begin
6595 EnableAI := True;
6597 // Проверяем, отключён ли AI ботов
6598 if (g_debug_BotAIOff = 1) and (Team = TEAM_RED) then
6599 EnableAI := False;
6600 if (g_debug_BotAIOff = 2) and (Team = TEAM_BLUE) then
6601 EnableAI := False;
6602 if g_debug_BotAIOff = 3 then
6603 EnableAI := False;
6605 if EnableAI then
6606 begin
6607 UpdateMove();
6608 UpdateCombat();
6609 end
6610 else
6611 begin
6612 RealizeCurrentWeapon();
6613 end;
6614 end;
6616 inherited Update();
6617 end;
6619 procedure TBot.ReleaseKey(Key: Byte);
6620 begin
6621 with FKeys[Key] do
6622 begin
6623 Pressed := False;
6624 Time := 0;
6625 end;
6626 end;
6628 function TBot.KeyPressed(Key: Word): Boolean;
6629 begin
6630 Result := FKeys[Key].Pressed;
6631 end;
6633 function TBot.GetAIFlag(aName: String20): String20;
6634 var
6635 a: Integer;
6636 begin
6637 Result := '';
6639 aName := LowerCase(aName);
6641 if FAIFlags <> nil then
6642 for a := 0 to High(FAIFlags) do
6643 if LowerCase(FAIFlags[a].Name) = aName then
6644 begin
6645 Result := FAIFlags[a].Value;
6646 Break;
6647 end;
6648 end;
6650 procedure TBot.RemoveAIFlag(aName: String20);
6651 var
6652 a, b: Integer;
6653 begin
6654 if FAIFlags = nil then Exit;
6656 aName := LowerCase(aName);
6658 for a := 0 to High(FAIFlags) do
6659 if LowerCase(FAIFlags[a].Name) = aName then
6660 begin
6661 if a <> High(FAIFlags) then
6662 for b := a to High(FAIFlags)-1 do
6663 FAIFlags[b] := FAIFlags[b+1];
6665 SetLength(FAIFlags, Length(FAIFlags)-1);
6666 Break;
6667 end;
6668 end;
6670 procedure TBot.SetAIFlag(aName, fValue: String20);
6671 var
6672 a: Integer;
6673 ok: Boolean;
6674 begin
6675 a := 0;
6676 ok := False;
6678 aName := LowerCase(aName);
6680 if FAIFlags <> nil then
6681 for a := 0 to High(FAIFlags) do
6682 if LowerCase(FAIFlags[a].Name) = aName then
6683 begin
6684 ok := True;
6685 Break;
6686 end;
6688 if ok then FAIFlags[a].Value := fValue
6689 else
6690 begin
6691 SetLength(FAIFlags, Length(FAIFlags)+1);
6692 with FAIFlags[High(FAIFlags)] do
6693 begin
6694 Name := aName;
6695 Value := fValue;
6696 end;
6697 end;
6698 end;
6700 procedure TBot.UpdateMove;
6702 procedure GoLeft(Time: Word = 1);
6703 begin
6704 ReleaseKey(KEY_LEFT);
6705 ReleaseKey(KEY_RIGHT);
6706 PressKey(KEY_LEFT, Time);
6707 SetDirection(TDirection.D_LEFT);
6708 end;
6710 procedure GoRight(Time: Word = 1);
6711 begin
6712 ReleaseKey(KEY_LEFT);
6713 ReleaseKey(KEY_RIGHT);
6714 PressKey(KEY_RIGHT, Time);
6715 SetDirection(TDirection.D_RIGHT);
6716 end;
6718 function Rnd(a: Word): Boolean;
6719 begin
6720 Result := Random(a) = 0;
6721 end;
6723 procedure Turn(Time: Word = 1200);
6724 begin
6725 if RunDirection() = TDirection.D_LEFT then GoRight(Time) else GoLeft(Time);
6726 end;
6728 procedure Stop();
6729 begin
6730 ReleaseKey(KEY_LEFT);
6731 ReleaseKey(KEY_RIGHT);
6732 end;
6734 function CanRunLeft(): Boolean;
6735 begin
6736 Result := not CollideLevel(-1, 0);
6737 end;
6739 function CanRunRight(): Boolean;
6740 begin
6741 Result := not CollideLevel(1, 0);
6742 end;
6744 function CanRun(): Boolean;
6745 begin
6746 if RunDirection() = TDirection.D_LEFT then Result := CanRunLeft() else Result := CanRunRight();
6747 end;
6749 procedure Jump(Time: Word = 30);
6750 begin
6751 PressKey(KEY_JUMP, Time);
6752 end;
6754 function NearHole(): Boolean;
6755 var
6756 x, sx: Integer;
6757 begin
6758 { TODO 5 : Лестницы }
6759 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6760 for x := 1 to PLAYER_RECT.Width do
6761 if (not StayOnStep(x*sx, 0)) and
6762 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6763 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6764 begin
6765 Result := True;
6766 Exit;
6767 end;
6769 Result := False;
6770 end;
6772 function BorderHole(): Boolean;
6773 var
6774 x, sx, xx: Integer;
6775 begin
6776 { TODO 5 : Лестницы }
6777 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6778 for x := 1 to PLAYER_RECT.Width do
6779 if (not StayOnStep(x*sx, 0)) and
6780 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6781 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6782 begin
6783 for xx := x to x+32 do
6784 if CollideLevel(xx*sx, PLAYER_RECT.Height) then
6785 begin
6786 Result := True;
6787 Exit;
6788 end;
6789 end;
6791 Result := False;
6792 end;
6794 function NearDeepHole(): Boolean;
6795 var
6796 x, sx, y: Integer;
6797 begin
6798 Result := False;
6800 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6801 y := 3;
6803 for x := 1 to PLAYER_RECT.Width do
6804 if (not StayOnStep(x*sx, 0)) and
6805 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6806 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6807 begin
6808 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6809 begin
6810 if CollideLevel(x*sx, PLAYER_RECT.Height*y) then Exit;
6811 y := y+1;
6812 end;
6814 Result := True;
6815 end else Result := False;
6816 end;
6818 function OverDeepHole(): Boolean;
6819 var
6820 y: Integer;
6821 begin
6822 Result := False;
6824 y := 1;
6825 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6826 begin
6827 if CollideLevel(0, PLAYER_RECT.Height*y) then Exit;
6828 y := y+1;
6829 end;
6831 Result := True;
6832 end;
6834 function OnGround(): Boolean;
6835 begin
6836 Result := StayOnStep(0, 0) or CollideLevel(0, 1);
6837 end;
6839 function OnLadder(): Boolean;
6840 begin
6841 Result := FullInStep(0, 0);
6842 end;
6844 function BelowLadder(): Boolean;
6845 begin
6846 Result := (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) and
6847 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6848 (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) and
6849 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6850 end;
6852 function BelowLiftUp(): Boolean;
6853 begin
6854 Result := ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) = -1) and
6855 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6856 ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) = -1) and
6857 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6858 end;
6860 function OnTopLift(): Boolean;
6861 begin
6862 Result := (FullInLift(0, 0) = -1) and (FullInLift(0, -32) = 0);
6863 end;
6865 function CanJumpOver(): Boolean;
6866 var
6867 sx, y: Integer;
6868 begin
6869 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6871 Result := False;
6873 if not CollideLevel(sx, 0) then Exit;
6875 for y := 1 to BOT_MAXJUMP do
6876 if CollideLevel(0, -y) then Exit else
6877 if not CollideLevel(sx, -y) then
6878 begin
6879 Result := True;
6880 Exit;
6881 end;
6882 end;
6884 function CanJumpUp(Dist: ShortInt): Boolean;
6885 var
6886 y, yy: Integer;
6887 c: Boolean;
6888 begin
6889 Result := False;
6891 if CollideLevel(Dist, 0) then Exit;
6893 c := False;
6894 for y := 0 to BOT_MAXJUMP do
6895 if CollideLevel(Dist, -y) then
6896 begin
6897 c := True;
6898 Break;
6899 end;
6901 if not c then Exit;
6903 c := False;
6904 for yy := y+1 to BOT_MAXJUMP do
6905 if not CollideLevel(Dist, -yy) then
6906 begin
6907 c := True;
6908 Break;
6909 end;
6911 if not c then Exit;
6913 c := False;
6914 for y := 0 to BOT_MAXJUMP do
6915 if CollideLevel(0, -y) then
6916 begin
6917 c := True;
6918 Break;
6919 end;
6921 if c then Exit;
6923 if y < yy then Exit;
6925 Result := True;
6926 end;
6928 function IsSafeTrigger(): Boolean;
6929 var
6930 a: Integer;
6931 begin
6932 Result := True;
6933 if gTriggers = nil then
6934 Exit;
6935 for a := 0 to High(gTriggers) do
6936 if Collide(gTriggers[a].X,
6937 gTriggers[a].Y,
6938 gTriggers[a].Width,
6939 gTriggers[a].Height) and
6940 (gTriggers[a].TriggerType in [TRIGGER_EXIT, TRIGGER_CLOSEDOOR,
6941 TRIGGER_CLOSETRAP, TRIGGER_TRAP,
6942 TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF,
6943 TRIGGER_ONOFF, TRIGGER_SPAWNMONSTER,
6944 TRIGGER_DAMAGE, TRIGGER_SHOT]) then
6945 Result := False;
6946 end;
6948 begin
6949 // Возможно, нажимаем кнопку:
6950 if Rnd(16) and IsSafeTrigger() then
6951 PressKey(KEY_OPEN);
6953 // Если под лифтом или ступеньками, то, возможно, прыгаем:
6954 if OnLadder() or ((BelowLadder() or BelowLiftUp()) and Rnd(8)) then
6955 begin
6956 ReleaseKey(KEY_LEFT);
6957 ReleaseKey(KEY_RIGHT);
6958 Jump();
6959 end;
6961 // Идем влево, если надо было:
6962 if GetAIFlag('GOLEFT') <> '' then
6963 begin
6964 RemoveAIFlag('GOLEFT');
6965 if CanRunLeft() then
6966 GoLeft(360);
6967 end;
6969 // Идем вправо, если надо было:
6970 if GetAIFlag('GORIGHT') <> '' then
6971 begin
6972 RemoveAIFlag('GORIGHT');
6973 if CanRunRight() then
6974 GoRight(360);
6975 end;
6977 // Если вылетели за карту, то пробуем вернуться:
6978 if FObj.X < -32 then
6979 GoRight(360)
6980 else
6981 if FObj.X+32 > gMapInfo.Width then
6982 GoLeft(360);
6984 // Прыгаем, если надо было:
6985 if GetAIFlag('NEEDJUMP') <> '' then
6986 begin
6987 Jump(0);
6988 RemoveAIFlag('NEEDJUMP');
6989 end;
6991 // Смотрим вверх, если надо было:
6992 if GetAIFlag('NEEDSEEUP') <> '' then
6993 begin
6994 ReleaseKey(KEY_UP);
6995 ReleaseKey(KEY_DOWN);
6996 PressKey(KEY_UP, 20);
6997 RemoveAIFlag('NEEDSEEUP');
6998 end;
7000 // Смотрим вниз, если надо было:
7001 if GetAIFlag('NEEDSEEDOWN') <> '' then
7002 begin
7003 ReleaseKey(KEY_UP);
7004 ReleaseKey(KEY_DOWN);
7005 PressKey(KEY_DOWN, 20);
7006 RemoveAIFlag('NEEDSEEDOWN');
7007 end;
7009 // Если нужно было в дыру и мы не на земле, то покорно летим:
7010 if GetAIFlag('GOINHOLE') <> '' then
7011 if not OnGround() then
7012 begin
7013 ReleaseKey(KEY_LEFT);
7014 ReleaseKey(KEY_RIGHT);
7015 RemoveAIFlag('GOINHOLE');
7016 SetAIFlag('FALLINHOLE', '1');
7017 end;
7019 // Если падали и достигли земли, то хватит падать:
7020 if GetAIFlag('FALLINHOLE') <> '' then
7021 if OnGround() then
7022 RemoveAIFlag('FALLINHOLE');
7024 // Если летели прямо и сейчас не на лестнице или на вершине лифта, то отходим в сторону:
7025 if not (KeyPressed(KEY_LEFT) or KeyPressed(KEY_RIGHT)) then
7026 if GetAIFlag('FALLINHOLE') = '' then
7027 if (not OnLadder()) or (FObj.Vel.Y >= 0) or (OnTopLift()) then
7028 if Rnd(2) then
7029 GoLeft(360)
7030 else
7031 GoRight(360);
7033 // Если на земле и можно подпрыгнуть, то, возможно, прыгаем:
7034 if OnGround() and
7035 CanJumpUp(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*32) and
7036 Rnd(8) then
7037 Jump();
7039 // Если на земле и возле дыры (глубина > 2 ростов игрока):
7040 if OnGround() and NearHole() then
7041 if NearDeepHole() then // Если это бездна
7042 case Random(6) of
7043 0..3: Turn(); // Бежим обратно
7044 4: Jump(); // Прыгаем
7045 5: begin // Прыгаем обратно
7046 Turn();
7047 Jump();
7048 end;
7049 end
7050 else // Это не бездна и мы еще не летим туда
7051 if GetAIFlag('GOINHOLE') = '' then
7052 case Random(6) of
7053 0: Turn(); // Не нужно туда
7054 1: Jump(); // Вдруг повезет - прыгаем
7055 else // Если яма с границей, то при случае можно туда прыгнуть
7056 if BorderHole() then
7057 SetAIFlag('GOINHOLE', '1');
7058 end;
7060 // Если на земле, но некуда идти:
7061 if (not CanRun()) and OnGround() then
7062 begin
7063 // Если мы на лестнице или можно перепрыгнуть, то прыгаем:
7064 if CanJumpOver() or OnLadder() then
7065 Jump()
7066 else // иначе попытаемся в другую сторону
7067 if Random(2) = 0 then
7068 begin
7069 if IsSafeTrigger() then
7070 PressKey(KEY_OPEN);
7071 end else
7072 Turn();
7073 end;
7075 // Осталось мало воздуха:
7076 if FAir < 36 * 2 then
7077 Jump(20);
7079 // Выбираемся из кислоты, если нет костюма, обожглись, или мало здоровья:
7080 if (FMegaRulez[MR_SUIT] < gTime) and ((FLastHit = HIT_ACID) or (Healthy() <= 1)) then
7081 if BodyInAcid(0, 0) then
7082 Jump();
7083 end;
7085 function TBot.FullInStep(XInc, YInc: Integer): Boolean;
7086 begin
7087 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
7088 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_STEP, False);
7089 end;
7091 {function TBot.NeedItem(Item: Byte): Byte;
7092 begin
7093 Result := 4;
7094 end;}
7096 procedure TBot.SelectWeapon(Dist: Integer);
7097 var
7098 a: Integer;
7100 function HaveAmmo(weapon: Byte): Boolean;
7101 begin
7102 case weapon of
7103 WEAPON_PISTOL: Result := FAmmo[A_BULLETS] >= 1;
7104 WEAPON_SHOTGUN1: Result := FAmmo[A_SHELLS] >= 1;
7105 WEAPON_SHOTGUN2: Result := FAmmo[A_SHELLS] >= 2;
7106 WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS] >= 10;
7107 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS] >= 1;
7108 WEAPON_PLASMA: Result := FAmmo[A_CELLS] >= 10;
7109 WEAPON_BFG: Result := FAmmo[A_CELLS] >= 40;
7110 WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS] >= 1;
7111 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL] >= 1;
7112 else Result := True;
7113 end;
7114 end;
7116 begin
7117 if Dist = -1 then Dist := BOT_LONGDIST;
7119 if Dist > BOT_LONGDIST then
7120 begin // Дальний бой
7121 for a := 0 to 9 do
7122 if FWeapon[FDifficult.WeaponPrior[a]] and HaveAmmo(FDifficult.WeaponPrior[a]) then
7123 begin
7124 FSelectedWeapon := FDifficult.WeaponPrior[a];
7125 Break;
7126 end;
7127 end
7128 else //if Dist > BOT_UNSAFEDIST then
7129 begin // Ближний бой
7130 for a := 0 to 9 do
7131 if FWeapon[FDifficult.CloseWeaponPrior[a]] and HaveAmmo(FDifficult.CloseWeaponPrior[a]) then
7132 begin
7133 FSelectedWeapon := FDifficult.CloseWeaponPrior[a];
7134 Break;
7135 end;
7136 end;
7137 { else
7138 begin
7139 for a := 0 to 9 do
7140 if FWeapon[FDifficult.SafeWeaponPrior[a]] and HaveAmmo(FDifficult.SafeWeaponPrior[a]) then
7141 begin
7142 FSelectedWeapon := FDifficult.SafeWeaponPrior[a];
7143 Break;
7144 end;
7145 end;}
7146 end;
7148 function TBot.PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean;
7149 begin
7150 Result := inherited PickItem(ItemType, force, remove);
7152 if Result then SetAIFlag('SELECTWEAPON', '1');
7153 end;
7155 function TBot.Heal(value: Word; Soft: Boolean): Boolean;
7156 begin
7157 Result := inherited Heal(value, Soft);
7158 end;
7160 function TBot.Healthy(): Byte;
7161 begin
7162 if FMegaRulez[MR_INVUL] >= gTime then Result := 3
7163 else if (FHealth > 80) or ((FHealth > 50) and (FArmor > 20)) then Result := 3
7164 else if (FHealth > 50) then Result := 2
7165 else if (FHealth > 20) then Result := 1
7166 else Result := 0;
7167 end;
7169 function TBot.TargetOnScreen(TX, TY: Integer): Boolean;
7170 begin
7171 Result := (Abs(FObj.X-TX) <= Trunc(gPlayerScreenSize.X*0.6)) and
7172 (Abs(FObj.Y-TY) <= Trunc(gPlayerScreenSize.Y*0.6));
7173 end;
7175 procedure TBot.OnDamage(Angle: SmallInt);
7176 var
7177 pla: TPlayer;
7178 mon: TMonster;
7179 ok: Boolean;
7180 begin
7181 inherited;
7183 if (Angle = 0) or (Angle = 180) then
7184 begin
7185 ok := False;
7186 if (g_GetUIDType(FLastSpawnerUID) = UID_PLAYER) and
7187 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER) then
7188 begin // Игрок
7189 pla := g_Player_Get(FLastSpawnerUID);
7190 ok := not TargetOnScreen(pla.FObj.X + PLAYER_RECT.X,
7191 pla.FObj.Y + PLAYER_RECT.Y);
7192 end
7193 else
7194 if (g_GetUIDType(FLastSpawnerUID) = UID_MONSTER) and
7195 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER) then
7196 begin // Монстр
7197 mon := g_Monsters_ByUID(FLastSpawnerUID);
7198 ok := not TargetOnScreen(mon.Obj.X + mon.Obj.Rect.X,
7199 mon.Obj.Y + mon.Obj.Rect.Y);
7200 end;
7202 if ok then
7203 if Angle = 0 then
7204 SetAIFlag('ATTACKLEFT', '1')
7205 else
7206 SetAIFlag('ATTACKRIGHT', '1');
7207 end;
7208 end;
7210 function TBot.RunDirection(): TDirection;
7211 begin
7212 if Abs(Vel.X) >= 1 then
7213 begin
7214 if Vel.X > 0 then Result := TDirection.D_RIGHT else Result := TDirection.D_LEFT;
7215 end else
7216 Result := FDirection;
7217 end;
7219 function TBot.GetRnd(a: Byte): Boolean;
7220 begin
7221 if a = 0 then Result := False
7222 else if a = 255 then Result := True
7223 else Result := Random(256) > 255-a;
7224 end;
7226 function TBot.GetInterval(a: Byte; radius: SmallInt): SmallInt;
7227 begin
7228 Result := Round((255-a)/255*radius*(Random(2)-1));
7229 end;
7232 procedure TDifficult.save (st: TStream);
7233 begin
7234 utils.writeInt(st, Byte(DiagFire));
7235 utils.writeInt(st, Byte(InvisFire));
7236 utils.writeInt(st, Byte(DiagPrecision));
7237 utils.writeInt(st, Byte(FlyPrecision));
7238 utils.writeInt(st, Byte(Cover));
7239 utils.writeInt(st, Byte(CloseJump));
7240 st.WriteBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7241 st.WriteBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7242 end;
7244 procedure TDifficult.load (st: TStream);
7245 begin
7246 DiagFire := utils.readByte(st);
7247 InvisFire := utils.readByte(st);
7248 DiagPrecision := utils.readByte(st);
7249 FlyPrecision := utils.readByte(st);
7250 Cover := utils.readByte(st);
7251 CloseJump := utils.readByte(st);
7252 st.ReadBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7253 st.ReadBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7254 end;
7257 procedure TBot.SaveState (st: TStream);
7258 var
7259 i: Integer;
7260 dw: Integer;
7261 begin
7262 inherited SaveState(st);
7263 utils.writeSign(st, 'BOT0');
7264 // Выбранное оружие
7265 utils.writeInt(st, Byte(FSelectedWeapon));
7266 // UID цели
7267 utils.writeInt(st, Word(FTargetUID));
7268 // Время потери цели
7269 utils.writeInt(st, LongWord(FLastVisible));
7270 // Количество флагов ИИ
7271 dw := Length(FAIFlags);
7272 utils.writeInt(st, LongInt(dw));
7273 // Флаги ИИ
7274 for i := 0 to dw-1 do
7275 begin
7276 utils.writeStr(st, FAIFlags[i].Name, 20);
7277 utils.writeStr(st, FAIFlags[i].Value, 20);
7278 end;
7279 // Настройки сложности
7280 FDifficult.save(st);
7281 end;
7284 procedure TBot.LoadState (st: TStream);
7285 var
7286 i: Integer;
7287 dw: Integer;
7288 begin
7289 inherited LoadState(st);
7290 if not utils.checkSign(st, 'BOT0') then raise XStreamError.Create('invalid bot signature');
7291 // Выбранное оружие
7292 FSelectedWeapon := utils.readByte(st);
7293 // UID цели
7294 FTargetUID := utils.readWord(st);
7295 // Время потери цели
7296 FLastVisible := utils.readLongWord(st);
7297 // Количество флагов ИИ
7298 dw := utils.readLongInt(st);
7299 if (dw < 0) or (dw > 16384) then raise XStreamError.Create('invalid number of bot AI flags');
7300 SetLength(FAIFlags, dw);
7301 // Флаги ИИ
7302 for i := 0 to dw-1 do
7303 begin
7304 FAIFlags[i].Name := utils.readStr(st, 20);
7305 FAIFlags[i].Value := utils.readStr(st, 20);
7306 end;
7307 // Настройки сложности
7308 FDifficult.load(st);
7309 end;
7312 begin
7313 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');
7314 conRegVar('player_indicator_style', @gPlayerIndicatorStyle, 'Visual appearance of indicator', 'Visual appearance of indicator');
7315 end.