DEADSOFTWARE

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