DEADSOFTWARE

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