DEADSOFTWARE

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