DEADSOFTWARE

render: player punch TAnimation -> TAnimationState
[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: TAnimationState;
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: TAnimationState 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;
2126 FPunchAnim := TAnimationState.Create(False, 1, 4);
2127 FPunchAnim.Disable;
2129 resetWeaponQueue();
2130 end;
2132 procedure TPlayer.positionChanged (); inline;
2133 begin
2134 end;
2136 procedure TPlayer.doDamage (v: Integer);
2137 begin
2138 if (v <= 0) then exit;
2139 if (v > 32767) then v := 32767;
2140 Damage(v, 0, 0, 0, mEDamageType);
2141 end;
2143 procedure TPlayer.Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte);
2144 var
2145 c: Word;
2146 begin
2147 if (not g_Game_IsClient) and (not FAlive) then
2148 Exit;
2150 FLastHit := t;
2152 // Неуязвимость не спасает от ловушек:
2153 if ((t = HIT_TRAP) or (t = HIT_SELF)) and (not FGodMode) then
2154 begin
2155 if not g_Game_IsClient then
2156 begin
2157 FArmor := 0;
2158 if t = HIT_TRAP then
2159 begin
2160 // Ловушка убивает сразу:
2161 FHealth := -100;
2162 Kill(K_EXTRAHARDKILL, SpawnerUID, t);
2163 end;
2164 if t = HIT_SELF then
2165 begin
2166 // Самоубийство:
2167 FHealth := 0;
2168 Kill(K_SIMPLEKILL, SpawnerUID, t);
2169 end;
2170 end;
2171 // Обнулить действия примочек, чтобы фон пропал
2172 FMegaRulez[MR_SUIT] := 0;
2173 FMegaRulez[MR_INVUL] := 0;
2174 FMegaRulez[MR_INVIS] := 0;
2175 FSpawnInvul := 0;
2176 FBerserk := 0;
2177 end;
2179 // Но от остального спасает:
2180 if FMegaRulez[MR_INVUL] >= gTime then
2181 Exit;
2183 // Чит-код "ГОРЕЦ":
2184 if FGodMode then
2185 Exit;
2187 // Если есть урон своим, или ранил сам себя, или тебя ранил противник:
2188 if LongBool(gGameSettings.Options and GAME_OPTION_TEAMDAMAGE) or
2189 (SpawnerUID = FUID) or
2190 (not SameTeam(FUID, SpawnerUID)) then
2191 begin
2192 FLastSpawnerUID := SpawnerUID;
2194 // Кровь (пузырьки, если в воде):
2195 if gBloodCount > 0 then
2196 begin
2197 c := Min(value, 200)*gBloodCount + Random(Min(value, 200) div 2);
2198 if value div 4 <= c then
2199 c := c - (value div 4)
2200 else
2201 c := 0;
2203 if (t = HIT_SOME) and (vx = 0) and (vy = 0) then
2204 MakeBloodSimple(c)
2205 else
2206 case t of
2207 HIT_TRAP, HIT_ACID, HIT_FLAME, HIT_SELF: MakeBloodSimple(c);
2208 HIT_BFG, HIT_ROCKET, HIT_SOME: MakeBloodVector(c, vx, vy);
2209 end;
2211 if t = HIT_WATER then
2212 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
2213 FObj.Y+PLAYER_RECT.Y-4, value div 2, 8, 4);
2214 end;
2216 // Буфер урона:
2217 if FAlive then
2218 Inc(FDamageBuffer, value);
2220 // Вспышка боли:
2221 if gFlash <> 0 then
2222 FPain := FPain + value;
2223 end;
2225 if g_Game_IsServer and g_Game_IsNet then
2226 begin
2227 MH_SEND_PlayerDamage(FUID, t, SpawnerUID, value, vx, vy);
2228 MH_SEND_PlayerStats(FUID);
2229 MH_SEND_PlayerPos(False, FUID);
2230 end;
2231 end;
2233 function TPlayer.Heal(value: Word; Soft: Boolean): Boolean;
2234 begin
2235 Result := False;
2236 if g_Game_IsClient then
2237 Exit;
2238 if not FAlive then
2239 Exit;
2241 if Soft and (FHealth < PLAYER_HP_SOFT) then
2242 begin
2243 IncMax(FHealth, value, PLAYER_HP_SOFT);
2244 Result := True;
2245 end;
2246 if (not Soft) and (FHealth < PLAYER_HP_LIMIT) then
2247 begin
2248 IncMax(FHealth, value, PLAYER_HP_LIMIT);
2249 Result := True;
2250 end;
2252 if Result and g_Game_IsServer and g_Game_IsNet then
2253 MH_SEND_PlayerStats(FUID);
2254 end;
2256 destructor TPlayer.Destroy();
2257 begin
2258 if (gPlayer1 <> nil) and (gPlayer1.FUID = FUID) then
2259 gPlayer1 := nil;
2260 if (gPlayer2 <> nil) and (gPlayer2.FUID = FUID) then
2261 gPlayer2 := nil;
2263 FSawSound.Free();
2264 FSawSoundIdle.Free();
2265 FSawSoundHit.Free();
2266 FSawSoundSelect.Free();
2267 FFlameSoundOn.Free();
2268 FFlameSoundOff.Free();
2269 FFlameSoundWork.Free();
2270 FJetSoundFly.Free();
2271 FJetSoundOn.Free();
2272 FJetSoundOff.Free();
2273 FModel.Free();
2274 FPunchAnim.Free();
2276 inherited;
2277 end;
2279 procedure TPlayer.DoPunch();
2280 begin
2281 FPunchAnim.Reset;
2282 FPunchAnim.Enable;
2283 end;
2285 procedure TPlayer.Fire();
2286 var
2287 f, DidFire: Boolean;
2288 wx, wy, xd, yd: Integer;
2289 locobj: TObj;
2290 begin
2291 if g_Game_IsClient then Exit;
2292 // FBFGFireCounter - время перед выстрелом (для BFG)
2293 // FReloading - время после выстрела (для всего)
2295 if FSpectator then
2296 begin
2297 Respawn(False);
2298 Exit;
2299 end;
2301 if FReloading[FCurrWeap] <> 0 then Exit;
2303 DidFire := False;
2305 f := False;
2306 wx := FObj.X+WEAPONPOINT[FDirection].X;
2307 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
2308 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
2309 yd := wy+firediry();
2311 case FCurrWeap of
2312 WEAPON_KASTET:
2313 begin
2314 DoPunch();
2315 if R_BERSERK in FRulez then
2316 begin
2317 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
2318 locobj.X := FObj.X+FObj.Rect.X;
2319 locobj.Y := FObj.Y+FObj.Rect.Y;
2320 locobj.rect.X := 0;
2321 locobj.rect.Y := 0;
2322 locobj.rect.Width := 39;
2323 locobj.rect.Height := 52;
2324 locobj.Vel.X := (xd-wx) div 2;
2325 locobj.Vel.Y := (yd-wy) div 2;
2326 locobj.Accel.X := xd-wx;
2327 locobj.Accel.y := yd-wy;
2329 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
2330 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
2331 else
2332 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
2334 if (gFlash = 1) and (FPain < 50) then FPain := min(FPain + 25, 50);
2335 end
2336 else
2337 begin
2338 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
2339 end;
2341 DidFire := True;
2342 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2343 end;
2345 WEAPON_SAW:
2346 begin
2347 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
2348 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
2349 begin
2350 FSawSoundSelect.Stop();
2351 FSawSound.Stop();
2352 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
2353 end
2354 else if not FSawSoundHit.IsPlaying() then
2355 begin
2356 FSawSoundSelect.Stop();
2357 FSawSound.PlayAt(FObj.X, FObj.Y);
2358 end;
2360 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2361 DidFire := True;
2362 f := True;
2363 end;
2365 WEAPON_PISTOL:
2366 if FAmmo[A_BULLETS] > 0 then
2367 begin
2368 g_Weapon_pistol(wx, wy, xd, yd, FUID);
2369 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2370 Dec(FAmmo[A_BULLETS]);
2371 FFireAngle := FAngle;
2372 f := True;
2373 DidFire := True;
2374 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2375 GameVelX, GameVelY-2, SHELL_BULLET);
2376 end;
2378 WEAPON_SHOTGUN1:
2379 if FAmmo[A_SHELLS] > 0 then
2380 begin
2381 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2382 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', wx, wy);
2383 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2384 Dec(FAmmo[A_SHELLS]);
2385 FFireAngle := FAngle;
2386 f := True;
2387 DidFire := True;
2388 FShellTimer := 10;
2389 FShellType := SHELL_SHELL;
2390 end;
2392 WEAPON_SHOTGUN2:
2393 if FAmmo[A_SHELLS] >= 2 then
2394 begin
2395 g_Weapon_dshotgun(wx, wy, xd, yd, FUID);
2396 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2397 Dec(FAmmo[A_SHELLS], 2);
2398 FFireAngle := FAngle;
2399 f := True;
2400 DidFire := True;
2401 FShellTimer := 13;
2402 FShellType := SHELL_DBLSHELL;
2403 end;
2405 WEAPON_CHAINGUN:
2406 if FAmmo[A_BULLETS] > 0 then
2407 begin
2408 g_Weapon_mgun(wx, wy, xd, yd, FUID);
2409 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', wx, wy);
2410 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2411 Dec(FAmmo[A_BULLETS]);
2412 FFireAngle := FAngle;
2413 f := True;
2414 DidFire := True;
2415 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2416 GameVelX, GameVelY-2, SHELL_BULLET);
2417 end;
2419 WEAPON_ROCKETLAUNCHER:
2420 if FAmmo[A_ROCKETS] > 0 then
2421 begin
2422 g_Weapon_rocket(wx, wy, xd, yd, FUID);
2423 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2424 Dec(FAmmo[A_ROCKETS]);
2425 FFireAngle := FAngle;
2426 f := True;
2427 DidFire := True;
2428 end;
2430 WEAPON_PLASMA:
2431 if FAmmo[A_CELLS] > 0 then
2432 begin
2433 g_Weapon_plasma(wx, wy, xd, yd, FUID);
2434 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2435 Dec(FAmmo[A_CELLS]);
2436 FFireAngle := FAngle;
2437 f := True;
2438 DidFire := True;
2439 end;
2441 WEAPON_BFG:
2442 if (FAmmo[A_CELLS] >= 40) and (FBFGFireCounter = -1) then
2443 begin
2444 FBFGFireCounter := 17;
2445 if not FNoReload then
2446 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', FObj.X, FObj.Y);
2447 Dec(FAmmo[A_CELLS], 40);
2448 DidFire := True;
2449 end;
2451 WEAPON_SUPERPULEMET:
2452 if FAmmo[A_SHELLS] > 0 then
2453 begin
2454 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2455 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', wx, wy);
2456 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2457 Dec(FAmmo[A_SHELLS]);
2458 FFireAngle := FAngle;
2459 f := True;
2460 DidFire := True;
2461 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2462 GameVelX, GameVelY-2, SHELL_SHELL);
2463 end;
2465 WEAPON_FLAMETHROWER:
2466 if FAmmo[A_FUEL] > 0 then
2467 begin
2468 g_Weapon_flame(wx, wy, xd, yd, FUID);
2469 FlamerOn;
2470 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2471 Dec(FAmmo[A_FUEL]);
2472 FFireAngle := FAngle;
2473 f := True;
2474 DidFire := True;
2475 end
2476 else
2477 begin
2478 FlamerOff;
2479 if g_Game_IsNet and g_Game_IsServer then MH_SEND_PlayerStats(FUID);
2480 end;
2481 end;
2483 if g_Game_IsNet then
2484 begin
2485 if DidFire then
2486 begin
2487 if FCurrWeap <> WEAPON_BFG then
2488 MH_SEND_PlayerFire(FUID, FCurrWeap, wx, wy, xd, yd, LastShotID)
2489 else
2490 if not FNoReload then
2491 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_WEAPON_STARTFIREBFG');
2492 end;
2494 MH_SEND_PlayerStats(FUID);
2495 end;
2497 if not f then Exit;
2499 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
2500 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
2501 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
2502 end;
2504 function TPlayer.GetAmmoByWeapon(Weapon: Byte): Word;
2505 begin
2506 case Weapon of
2507 WEAPON_PISTOL, WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS];
2508 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS];
2509 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS];
2510 WEAPON_PLASMA, WEAPON_BFG: Result := FAmmo[A_CELLS];
2511 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL];
2512 else Result := 0;
2513 end;
2514 end;
2516 function TPlayer.HeadInLiquid(XInc, YInc: Integer): Boolean;
2517 begin
2518 Result := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X+XInc, FObj.Y+PLAYER_HEADRECT.Y+YInc,
2519 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
2520 PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, True);
2521 end;
2523 procedure TPlayer.FlamerOn;
2524 begin
2525 FFlameSoundOff.Stop();
2526 FFlameSoundOff.SetPosition(0);
2527 if FFlaming then
2528 begin
2529 if (not FFlameSoundOn.IsPlaying()) and (not FFlameSoundWork.IsPlaying()) then
2530 FFlameSoundWork.PlayAt(FObj.X, FObj.Y);
2531 end
2532 else
2533 begin
2534 FFlameSoundOn.PlayAt(FObj.X, FObj.Y);
2535 FFlaming := True;
2536 end;
2537 end;
2539 procedure TPlayer.FlamerOff;
2540 begin
2541 if FFlaming then
2542 begin
2543 FFlameSoundOn.Stop();
2544 FFlameSoundOn.SetPosition(0);
2545 FFlameSoundWork.Stop();
2546 FFlameSoundWork.SetPosition(0);
2547 FFlameSoundOff.PlayAt(FObj.X, FObj.Y);
2548 FFlaming := False;
2549 end;
2550 end;
2552 procedure TPlayer.JetpackOn;
2553 begin
2554 FJetSoundFly.Stop;
2555 FJetSoundOff.Stop;
2556 FJetSoundOn.SetPosition(0);
2557 FJetSoundOn.PlayAt(FObj.X, FObj.Y);
2558 FlySmoke(8);
2559 end;
2561 procedure TPlayer.JetpackOff;
2562 begin
2563 FJetSoundFly.Stop;
2564 FJetSoundOn.Stop;
2565 FJetSoundOff.SetPosition(0);
2566 FJetSoundOff.PlayAt(FObj.X, FObj.Y);
2567 end;
2569 procedure TPlayer.CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
2570 begin
2571 if Timeout <= 0 then
2572 exit;
2573 if (FMegaRulez[MR_SUIT] > gTime) or (FMegaRulez[MR_INVUL] > gTime) then
2574 exit; // Не загораемся когда есть защита
2575 if g_Obj_CollidePanel(@FObj, 0, 0, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2) then
2576 exit; // Не подгораем в воде на всякий случай
2577 if FFireTime <= 0 then
2578 g_Sound_PlayExAt('SOUND_IGNITE', FObj.X, FObj.Y);
2579 FFireTime := Timeout;
2580 FFireAttacker := Attacker;
2581 if g_Game_IsNet and g_Game_IsServer then
2582 MH_SEND_PlayerStats(FUID);
2583 end;
2585 procedure TPlayer.Jump();
2586 begin
2587 if gFly or FJetpack then
2588 begin
2589 // Полет (чит-код или джетпак):
2590 if FObj.Vel.Y > -VEL_FLY then
2591 FObj.Vel.Y := FObj.Vel.Y - 3;
2592 if FJetpack then
2593 begin
2594 if FJetFuel > 0 then
2595 Dec(FJetFuel);
2596 if (FJetFuel < 1) and g_Game_IsServer then
2597 begin
2598 FJetpack := False;
2599 JetpackOff;
2600 if g_Game_IsNet then
2601 MH_SEND_PlayerStats(FUID);
2602 end;
2603 end;
2604 Exit;
2605 end;
2607 // Не включать джетпак в режиме прохождения сквозь стены
2608 if FGhost then
2609 FCanJetpack := False;
2611 // Прыгаем или всплываем:
2612 if (CollideLevel(0, 1) or
2613 g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y+36, PLAYER_RECT.Width,
2614 PLAYER_RECT.Height-33, PANEL_STEP, False)
2615 ) and (FObj.Accel.Y = 0) then // Не прыгать, если есть вертикальное ускорение
2616 begin
2617 FObj.Vel.Y := -VEL_JUMP;
2618 FCanJetpack := False;
2619 end
2620 else
2621 begin
2622 if BodyInLiquid(0, 0) then
2623 FObj.Vel.Y := -VEL_SW
2624 else if (FJetFuel > 0) and FCanJetpack and
2625 g_Game_IsServer and (not g_Obj_CollideLiquid(@FObj, 0, 0)) then
2626 begin
2627 FJetpack := True;
2628 JetpackOn;
2629 if g_Game_IsNet then
2630 MH_SEND_PlayerStats(FUID);
2631 end;
2632 end;
2633 end;
2635 procedure TPlayer.Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
2636 var
2637 a, i, k, ab, ar: Byte;
2638 s: String;
2639 mon: TMonster;
2640 plr: TPlayer;
2641 srv, netsrv: Boolean;
2642 DoFrags: Boolean;
2643 OldLR: Byte;
2644 KP: TPlayer;
2645 it: PItem;
2647 procedure PushItem(t: Byte);
2648 var
2649 id: DWORD;
2650 begin
2651 id := g_Items_Create(FObj.X, FObj.Y, t, True, False);
2652 it := g_Items_ByIdx(id);
2653 if KillType = K_EXTRAHARDKILL then // -7..+7; -8..0
2654 begin
2655 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-7+Random(15),
2656 (FObj.Vel.Y div 2)-Random(9));
2657 it.positionChanged(); // this updates spatial accelerators
2658 end
2659 else
2660 begin
2661 if KillType = K_HARDKILL then // -5..+5; -5..0
2662 begin
2663 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-5+Random(11),
2664 (FObj.Vel.Y div 2)-Random(6));
2665 end
2666 else // -3..+3; -3..0
2667 begin
2668 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-3+Random(7),
2669 (FObj.Vel.Y div 2)-Random(4));
2670 end;
2671 it.positionChanged(); // this updates spatial accelerators
2672 end;
2674 if g_Game_IsNet and g_Game_IsServer then
2675 MH_SEND_ItemSpawn(True, id);
2676 end;
2678 begin
2679 DoFrags := (gGameSettings.MaxLives = 0) or (gGameSettings.GameMode = GM_COOP);
2680 Srv := g_Game_IsServer;
2681 Netsrv := g_Game_IsServer and g_Game_IsNet;
2682 if Srv then FDeath := FDeath + 1;
2683 if FAlive then
2684 begin
2685 if FGhost then
2686 FGhost := False;
2687 if not FPhysics then
2688 FPhysics := True;
2689 FAlive := False;
2690 end;
2691 FShellTimer := -1;
2693 if (gGameSettings.MaxLives > 0) and Srv and (gLMSRespawn = LMS_RESPAWN_NONE) then
2694 begin
2695 if FLives > 0 then FLives := FLives - 1;
2696 if FLives = 0 then FNoRespawn := True;
2697 end;
2699 // Номер типа смерти:
2700 a := 1;
2701 case KillType of
2702 K_SIMPLEKILL: a := 1;
2703 K_HARDKILL: a := 2;
2704 K_EXTRAHARDKILL: a := 3;
2705 K_FALLKILL: a := 4;
2706 end;
2708 // Звук смерти:
2709 if not FModel.PlaySound(MODELSOUND_DIE, a, FObj.X, FObj.Y) then
2710 for i := 1 to 3 do
2711 if FModel.PlaySound(MODELSOUND_DIE, i, FObj.X, FObj.Y) then
2712 Break;
2714 // Время респауна:
2715 if Srv then
2716 case KillType of
2717 K_SIMPLEKILL:
2718 FTime[T_RESPAWN] := gTime + TIME_RESPAWN1;
2719 K_HARDKILL:
2720 FTime[T_RESPAWN] := gTime + TIME_RESPAWN2;
2721 K_EXTRAHARDKILL, K_FALLKILL:
2722 FTime[T_RESPAWN] := gTime + TIME_RESPAWN3;
2723 end;
2725 // Переключаем состояние:
2726 case KillType of
2727 K_SIMPLEKILL:
2728 SetAction(A_DIE1);
2729 K_HARDKILL, K_EXTRAHARDKILL:
2730 SetAction(A_DIE2);
2731 end;
2733 // Реакция монстров на смерть игрока:
2734 if (KillType <> K_FALLKILL) and (Srv) then
2735 g_Monsters_killedp();
2737 if SpawnerUID = FUID then
2738 begin // Самоубился
2739 if Srv and (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2740 begin
2741 Dec(FFrags);
2742 FLastFrag := 0;
2743 end;
2744 g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2745 end
2746 else
2747 if g_GetUIDType(SpawnerUID) = UID_PLAYER then
2748 begin // Убит другим игроком
2749 KP := g_Player_Get(SpawnerUID);
2750 if (KP <> nil) and Srv then
2751 begin
2752 if (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2753 if SameTeam(FUID, SpawnerUID) then
2754 begin
2755 Dec(KP.FFrags);
2756 KP.FLastFrag := 0;
2757 end else
2758 begin
2759 Inc(KP.FFrags);
2760 KP.FragCombo();
2761 end;
2763 if (gGameSettings.GameMode = GM_TDM) and DoFrags then
2764 Inc(gTeamStat[KP.Team].Goals,
2765 IfThen(SameTeam(FUID, SpawnerUID), -1, 1));
2767 if netsrv then MH_SEND_PlayerStats(SpawnerUID);
2768 end;
2770 plr := g_Player_Get(SpawnerUID);
2771 if plr = nil then
2772 s := '?'
2773 else
2774 s := plr.FName;
2776 case KillType of
2777 K_HARDKILL:
2778 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2779 [FName, s]),
2780 gShowKillMsg);
2781 K_EXTRAHARDKILL:
2782 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2783 [FName, s]),
2784 gShowKillMsg);
2785 else
2786 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2787 [FName, s]),
2788 gShowKillMsg);
2789 end;
2790 end
2791 else if g_GetUIDType(SpawnerUID) = UID_MONSTER then
2792 begin // Убит монстром
2793 mon := g_Monsters_ByUID(SpawnerUID);
2794 if mon = nil then
2795 s := '?'
2796 else
2797 s := g_Mons_GetKilledByTypeId(mon.MonsterType);
2799 case KillType of
2800 K_HARDKILL:
2801 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2802 [FName, s]),
2803 gShowKillMsg);
2804 K_EXTRAHARDKILL:
2805 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2806 [FName, s]),
2807 gShowKillMsg);
2808 else
2809 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2810 [FName, s]),
2811 gShowKillMsg);
2812 end;
2813 end
2814 else // Особые типы смерти
2815 case t of
2816 HIT_DISCON: ;
2817 HIT_SELF: g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2818 HIT_FALL: g_Console_Add(Format(_lc[I_PLAYER_KILL_FALL], [FName]), True);
2819 HIT_WATER: g_Console_Add(Format(_lc[I_PLAYER_KILL_WATER], [FName]), True);
2820 HIT_ACID: g_Console_Add(Format(_lc[I_PLAYER_KILL_ACID], [FName]), True);
2821 HIT_TRAP: g_Console_Add(Format(_lc[I_PLAYER_KILL_TRAP], [FName]), True);
2822 else g_Console_Add(Format(_lc[I_PLAYER_DIED], [FName]), True);
2823 end;
2825 if Srv then
2826 begin
2827 // Выброс оружия:
2828 for a := WP_FIRST to WP_LAST do
2829 if FWeapon[a] then
2830 begin
2831 case a of
2832 WEAPON_SAW: i := ITEM_WEAPON_SAW;
2833 WEAPON_SHOTGUN1: i := ITEM_WEAPON_SHOTGUN1;
2834 WEAPON_SHOTGUN2: i := ITEM_WEAPON_SHOTGUN2;
2835 WEAPON_CHAINGUN: i := ITEM_WEAPON_CHAINGUN;
2836 WEAPON_ROCKETLAUNCHER: i := ITEM_WEAPON_ROCKETLAUNCHER;
2837 WEAPON_PLASMA: i := ITEM_WEAPON_PLASMA;
2838 WEAPON_BFG: i := ITEM_WEAPON_BFG;
2839 WEAPON_SUPERPULEMET: i := ITEM_WEAPON_SUPERPULEMET;
2840 WEAPON_FLAMETHROWER: i := ITEM_WEAPON_FLAMETHROWER;
2841 else i := 0;
2842 end;
2844 if i <> 0 then
2845 PushItem(i);
2846 end;
2848 // Выброс рюкзака:
2849 if R_ITEM_BACKPACK in FRulez then
2850 PushItem(ITEM_AMMO_BACKPACK);
2852 // Выброс ракетного ранца:
2853 if FJetFuel > 0 then
2854 PushItem(ITEM_JETPACK);
2856 // Выброс ключей:
2857 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) or
2858 (not LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS)) then
2859 begin
2860 if R_KEY_RED in FRulez then
2861 PushItem(ITEM_KEY_RED);
2863 if R_KEY_GREEN in FRulez then
2864 PushItem(ITEM_KEY_GREEN);
2866 if R_KEY_BLUE in FRulez then
2867 PushItem(ITEM_KEY_BLUE);
2868 end;
2870 // Выброс флага:
2871 DropFlag(KillType = K_FALLKILL);
2872 end;
2874 FCorpse := g_Player_CreateCorpse(Self);
2876 if Srv and (gGameSettings.MaxLives > 0) and FNoRespawn and
2877 (gLMSRespawn = LMS_RESPAWN_NONE) then
2878 begin
2879 a := 0;
2880 k := 0;
2881 ar := 0;
2882 ab := 0;
2883 for i := Low(gPlayers) to High(gPlayers) do
2884 begin
2885 if gPlayers[i] = nil then continue;
2886 if (not gPlayers[i].FNoRespawn) and (not gPlayers[i].FSpectator) then
2887 begin
2888 Inc(a);
2889 if gPlayers[i].FTeam = TEAM_RED then Inc(ar)
2890 else if gPlayers[i].FTeam = TEAM_BLUE then Inc(ab);
2891 k := i;
2892 end;
2893 end;
2895 OldLR := gLMSRespawn;
2896 if (gGameSettings.GameMode = GM_COOP) then
2897 begin
2898 if (a = 0) then
2899 begin
2900 // everyone is dead, restart the map
2901 g_Game_Message(_lc[I_MESSAGE_LMS_LOSE], 144);
2902 if Netsrv then
2903 MH_SEND_GameEvent(NET_EV_LMS_LOSE);
2904 gLMSRespawn := LMS_RESPAWN_FINAL;
2905 gLMSRespawnTime := gTime + 5000;
2906 end
2907 else if (a = 1) then
2908 begin
2909 if (gPlayers[k] <> nil) and not (gPlayers[k] is TBot) then
2910 if (gPlayers[k] = gPlayer1) or
2911 (gPlayers[k] = gPlayer2) then
2912 g_Console_Add('*** ' + _lc[I_MESSAGE_LMS_SURVIVOR] + ' ***', True)
2913 else if Netsrv and (gPlayers[k].FClientID >= 0) then
2914 MH_SEND_GameEvent(NET_EV_LMS_SURVIVOR, 0, 'N', gPlayers[k].FClientID);
2915 end;
2916 end
2917 else if (gGameSettings.GameMode = GM_TDM) then
2918 begin
2919 if (ab = 0) and (ar <> 0) then
2920 begin
2921 // blu team ded
2922 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 144);
2923 if Netsrv then
2924 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_RED);
2925 Inc(gTeamStat[TEAM_RED].Goals);
2926 gLMSRespawn := LMS_RESPAWN_FINAL;
2927 gLMSRespawnTime := gTime + 5000;
2928 end
2929 else if (ar = 0) and (ab <> 0) then
2930 begin
2931 // red team ded
2932 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 144);
2933 if Netsrv then
2934 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_BLUE);
2935 Inc(gTeamStat[TEAM_BLUE].Goals);
2936 gLMSRespawn := LMS_RESPAWN_FINAL;
2937 gLMSRespawnTime := gTime + 5000;
2938 end
2939 else if (ar = 0) and (ab = 0) then
2940 begin
2941 // everyone ded
2942 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2943 if Netsrv then
2944 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2945 gLMSRespawn := LMS_RESPAWN_FINAL;
2946 gLMSRespawnTime := gTime + 5000;
2947 end;
2948 end
2949 else if (gGameSettings.GameMode = GM_DM) then
2950 begin
2951 if (a = 1) then
2952 begin
2953 if gPlayers[k] <> nil then
2954 with gPlayers[k] do
2955 begin
2956 // survivor is the winner
2957 g_Game_Message(Format(_lc[I_MESSAGE_LMS_WIN], [AnsiUpperCase(FName)]), 144);
2958 if Netsrv then
2959 MH_SEND_GameEvent(NET_EV_LMS_WIN, 0, FName);
2960 Inc(FFrags);
2961 end;
2962 gLMSRespawn := LMS_RESPAWN_FINAL;
2963 gLMSRespawnTime := gTime + 5000;
2964 end
2965 else if (a = 0) then
2966 begin
2967 // everyone is dead, restart the map
2968 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2969 if Netsrv then
2970 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2971 gLMSRespawn := LMS_RESPAWN_FINAL;
2972 gLMSRespawnTime := gTime + 5000;
2973 end;
2974 end;
2975 if srv and (OldLR = LMS_RESPAWN_NONE) and (gLMSRespawn > LMS_RESPAWN_NONE) then
2976 begin
2977 if NetMode = NET_SERVER then
2978 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime)
2979 else
2980 g_Console_Add(Format(_lc[I_MSG_WARMUP_START], [(gLMSRespawnTime - gTime) div 1000]), True);
2981 end;
2982 end;
2984 if Netsrv then
2985 begin
2986 MH_SEND_PlayerStats(FUID);
2987 MH_SEND_PlayerDeath(FUID, KillType, t, SpawnerUID);
2988 if gGameSettings.GameMode = GM_TDM then MH_SEND_GameStats;
2989 end;
2991 if srv and FNoRespawn then Spectate(True);
2992 FWantsInGame := True;
2993 end;
2995 function TPlayer.BodyInLiquid(XInc, YInc: Integer): Boolean;
2996 begin
2997 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
2998 PLAYER_RECT.Height-20, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, False);
2999 end;
3001 function TPlayer.BodyInAcid(XInc, YInc: Integer): Boolean;
3002 begin
3003 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3004 PLAYER_RECT.Height-20, PANEL_ACID1 or PANEL_ACID2, False);
3005 end;
3007 procedure TPlayer.MakeBloodSimple(Count: Word);
3008 var Blood: TModelBlood;
3009 begin
3010 Blood := SELF.FModel.GetBlood();
3011 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)+8,
3012 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3013 Count div 2, 3, -1, 16, (PLAYER_RECT.Height*2 div 3),
3014 Blood.R, Blood.G, Blood.B, Blood.Kind);
3015 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-8,
3016 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3017 Count div 2, -3, -1, 16, (PLAYER_RECT.Height*2) div 3,
3018 Blood.R, Blood.G, Blood.B, Blood.Kind);
3019 end;
3021 procedure TPlayer.MakeBloodVector(Count: Word; VelX, VelY: Integer);
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),
3026 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3027 Count, VelX, VelY, 16, (PLAYER_RECT.Height*2) div 3,
3028 Blood.R, Blood.G, Blood.B, Blood.Kind);
3029 end;
3031 procedure TPlayer.QueueWeaponSwitch(Weapon: Byte);
3032 begin
3033 if g_Game_IsClient then Exit;
3034 if Weapon > High(FWeapon) then Exit;
3035 FNextWeap := FNextWeap or (1 shl Weapon);
3036 end;
3038 procedure TPlayer.resetWeaponQueue ();
3039 begin
3040 FNextWeap := 0;
3041 FNextWeapDelay := 0;
3042 end;
3044 function TPlayer.hasAmmoForWeapon (weapon: Byte): Boolean;
3045 begin
3046 result := false;
3047 case weapon of
3048 WEAPON_KASTET, WEAPON_SAW: result := true;
3049 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3050 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3051 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3052 WEAPON_PLASMA, WEAPON_BFG: result := (FAmmo[A_CELLS] > 0);
3053 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3054 else result := (weapon < length(FWeapon));
3055 end;
3056 end;
3058 // return 255 for "no switch"
3059 function TPlayer.getNextWeaponIndex (): Byte;
3060 var
3061 i: Word;
3062 wantThisWeapon: array[0..64] of Boolean;
3063 wwc: Integer = 0; //HACK!
3064 dir, cwi: Integer;
3065 begin
3066 result := 255; // default result: "no switch"
3067 // had weapon cycling on previous frame? remove that flag
3068 if (FNextWeap and $2000) <> 0 then
3069 begin
3070 FNextWeap := FNextWeap and $1FFF;
3071 FNextWeapDelay := 0;
3072 end;
3073 // cycling has priority
3074 if (FNextWeap and $C000) <> 0 then
3075 begin
3076 if (FNextWeap and $8000) <> 0 then
3077 dir := 1
3078 else
3079 dir := -1;
3080 FNextWeap := FNextWeap or $2000; // we need this
3081 if FNextWeapDelay > 0 then
3082 exit; // cooldown time
3083 cwi := FCurrWeap;
3084 for i := 0 to High(FWeapon) do
3085 begin
3086 cwi := (cwi+length(FWeapon)+dir) mod length(FWeapon);
3087 if FWeapon[cwi] then
3088 begin
3089 //e_WriteLog(Format(' SWITCH: cur=%d; new=%d', [FCurrWeap, cwi]), MSG_WARNING);
3090 result := Byte(cwi);
3091 FNextWeapDelay := WEAPON_DELAY;
3092 exit;
3093 end;
3094 end;
3095 resetWeaponQueue();
3096 exit;
3097 end;
3098 // no cycling
3099 for i := 0 to High(wantThisWeapon) do
3100 wantThisWeapon[i] := false;
3101 for i := 0 to High(FWeapon) do
3102 if (FNextWeap and (1 shl i)) <> 0 then
3103 begin
3104 wantThisWeapon[i] := true;
3105 Inc(wwc);
3106 end;
3107 // exclude currently selected weapon from the set
3108 wantThisWeapon[FCurrWeap] := false;
3109 // slow down alterations a little
3110 if wwc > 1 then
3111 begin
3112 //e_WriteLog(Format(' FNextWeap=%x; delay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3113 // more than one weapon requested, assume "alteration" and check alteration delay
3114 if FNextWeapDelay > 0 then
3115 begin
3116 FNextWeap := 0;
3117 exit;
3118 end; // yeah
3119 end;
3120 // do not reset weapon queue, it will be done in `RealizeCurrentWeapon()`
3121 // but clear all counters if no weapon should be switched
3122 if wwc < 1 then
3123 begin
3124 resetWeaponQueue();
3125 exit;
3126 end;
3127 //e_WriteLog(Format('wwc=%d', [wwc]), MSG_WARNING);
3128 // try weapons in descending order
3129 for i := High(FWeapon) downto 0 do
3130 begin
3131 if wantThisWeapon[i] and FWeapon[i] and ((wwc = 1) or hasAmmoForWeapon(i)) then
3132 begin
3133 // i found her!
3134 result := Byte(i);
3135 resetWeaponQueue();
3136 FNextWeapDelay := WEAPON_DELAY * 2; // anyway, 'cause why not
3137 exit;
3138 end;
3139 end;
3140 // no suitable weapon found, so reset the queue, to avoid accidental "queuing" of weapon w/o ammo
3141 resetWeaponQueue();
3142 end;
3144 procedure TPlayer.RealizeCurrentWeapon();
3145 function switchAllowed (): Boolean;
3146 var
3147 i: Byte;
3148 begin
3149 result := false;
3150 if FBFGFireCounter <> -1 then
3151 exit;
3152 if FTime[T_SWITCH] > gTime then
3153 exit;
3154 for i := WP_FIRST to WP_LAST do
3155 if FReloading[i] > 0 then
3156 exit;
3157 result := true;
3158 end;
3160 var
3161 nw: Byte;
3162 begin
3163 //e_WriteLog(Format('***RealizeCurrentWeapon: FNextWeap=%x; FNextWeapDelay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3164 //FNextWeap := FNextWeap and $1FFF;
3165 if FNextWeapDelay > 0 then Dec(FNextWeapDelay); // "alteration delay"
3167 if not switchAllowed then
3168 begin
3169 //HACK for weapon cycling
3170 if (FNextWeap and $E000) <> 0 then FNextWeap := 0;
3171 exit;
3172 end;
3174 nw := getNextWeaponIndex();
3175 if nw = 255 then exit; // don't reset anything here
3176 if nw > High(FWeapon) then
3177 begin
3178 // don't forget to reset queue here!
3179 //e_WriteLog(' RealizeCurrentWeapon: WUTAFUUUU', MSG_WARNING);
3180 resetWeaponQueue();
3181 exit;
3182 end;
3184 if FWeapon[nw] then
3185 begin
3186 FCurrWeap := nw;
3187 FTime[T_SWITCH] := gTime+156;
3188 if FCurrWeap = WEAPON_SAW then FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3189 FModel.SetWeapon(FCurrWeap);
3190 if g_Game_IsNet then MH_SEND_PlayerStats(FUID);
3191 end;
3192 end;
3194 procedure TPlayer.NextWeapon();
3195 begin
3196 if g_Game_IsClient then Exit;
3197 FNextWeap := $8000;
3198 end;
3200 procedure TPlayer.PrevWeapon();
3201 begin
3202 if g_Game_IsClient then Exit;
3203 FNextWeap := $4000;
3204 end;
3206 procedure TPlayer.SetWeapon(W: Byte);
3207 begin
3208 if FCurrWeap <> W then
3209 if W = WEAPON_SAW then
3210 FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3212 FCurrWeap := W;
3213 FModel.SetWeapon(CurrWeap);
3214 resetWeaponQueue();
3215 end;
3217 function TPlayer.PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean;
3219 function allowBerserkSwitching (): Boolean;
3220 begin
3221 if (FBFGFireCounter <> -1) then begin result := false; exit; end;
3222 result := true;
3223 if gBerserkAutoswitch then exit;
3224 if not conIsCheatsEnabled then exit;
3225 result := false;
3226 end;
3228 var
3229 a: Boolean;
3230 begin
3231 Result := False;
3232 if g_Game_IsClient then Exit;
3234 // a = true - место спавна предмета:
3235 a := LongBool(gGameSettings.Options and GAME_OPTION_WEAPONSTAY) and arespawn;
3236 remove := not a;
3238 case ItemType of
3239 ITEM_MEDKIT_SMALL:
3240 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3241 begin
3242 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
3243 Result := True;
3244 remove := True;
3245 FFireTime := 0;
3246 if gFlash = 2 then Inc(FPickup, 5);
3247 end;
3249 ITEM_MEDKIT_LARGE:
3250 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3251 begin
3252 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
3253 Result := True;
3254 remove := True;
3255 FFireTime := 0;
3256 if gFlash = 2 then Inc(FPickup, 5);
3257 end;
3259 ITEM_ARMOR_GREEN:
3260 if FArmor < PLAYER_AP_SOFT then
3261 begin
3262 FArmor := PLAYER_AP_SOFT;
3263 Result := True;
3264 remove := True;
3265 if gFlash = 2 then Inc(FPickup, 5);
3266 end;
3268 ITEM_ARMOR_BLUE:
3269 if FArmor < PLAYER_AP_LIMIT then
3270 begin
3271 FArmor := PLAYER_AP_LIMIT;
3272 Result := True;
3273 remove := True;
3274 if gFlash = 2 then Inc(FPickup, 5);
3275 end;
3277 ITEM_SPHERE_BLUE:
3278 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3279 begin
3280 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
3281 Result := True;
3282 remove := True;
3283 FFireTime := 0;
3284 if gFlash = 2 then Inc(FPickup, 5);
3285 end;
3287 ITEM_SPHERE_WHITE:
3288 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) or (FFireTime > 0) then
3289 begin
3290 if FHealth < PLAYER_HP_LIMIT then
3291 FHealth := PLAYER_HP_LIMIT;
3292 if FArmor < PLAYER_AP_LIMIT then
3293 FArmor := PLAYER_AP_LIMIT;
3294 Result := True;
3295 remove := True;
3296 FFireTime := 0;
3297 if gFlash = 2 then Inc(FPickup, 5);
3298 end;
3300 ITEM_WEAPON_SAW:
3301 if (not FWeapon[WEAPON_SAW]) or ((not arespawn) and (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) then
3302 begin
3303 FWeapon[WEAPON_SAW] := True;
3304 Result := True;
3305 if gFlash = 2 then Inc(FPickup, 5);
3306 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3307 end;
3309 ITEM_WEAPON_SHOTGUN1:
3310 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN1] then
3311 begin
3312 // Нужно, чтобы не взять все пули сразу:
3313 if a and FWeapon[WEAPON_SHOTGUN1] then Exit;
3315 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3316 FWeapon[WEAPON_SHOTGUN1] := True;
3317 Result := True;
3318 if gFlash = 2 then Inc(FPickup, 5);
3319 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3320 end;
3322 ITEM_WEAPON_SHOTGUN2:
3323 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN2] then
3324 begin
3325 if a and FWeapon[WEAPON_SHOTGUN2] then Exit;
3327 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3328 FWeapon[WEAPON_SHOTGUN2] := True;
3329 Result := True;
3330 if gFlash = 2 then Inc(FPickup, 5);
3331 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3332 end;
3334 ITEM_WEAPON_CHAINGUN:
3335 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or not FWeapon[WEAPON_CHAINGUN] then
3336 begin
3337 if a and FWeapon[WEAPON_CHAINGUN] then Exit;
3339 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3340 FWeapon[WEAPON_CHAINGUN] := True;
3341 Result := True;
3342 if gFlash = 2 then Inc(FPickup, 5);
3343 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3344 end;
3346 ITEM_WEAPON_ROCKETLAUNCHER:
3347 if (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or not FWeapon[WEAPON_ROCKETLAUNCHER] then
3348 begin
3349 if a and FWeapon[WEAPON_ROCKETLAUNCHER] then Exit;
3351 IncMax(FAmmo[A_ROCKETS], 2, FMaxAmmo[A_ROCKETS]);
3352 FWeapon[WEAPON_ROCKETLAUNCHER] := True;
3353 Result := True;
3354 if gFlash = 2 then Inc(FPickup, 5);
3355 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3356 end;
3358 ITEM_WEAPON_PLASMA:
3359 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_PLASMA] then
3360 begin
3361 if a and FWeapon[WEAPON_PLASMA] then Exit;
3363 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3364 FWeapon[WEAPON_PLASMA] := True;
3365 Result := True;
3366 if gFlash = 2 then Inc(FPickup, 5);
3367 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3368 end;
3370 ITEM_WEAPON_BFG:
3371 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_BFG] then
3372 begin
3373 if a and FWeapon[WEAPON_BFG] then Exit;
3375 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3376 FWeapon[WEAPON_BFG] := True;
3377 Result := True;
3378 if gFlash = 2 then Inc(FPickup, 5);
3379 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3380 end;
3382 ITEM_WEAPON_SUPERPULEMET:
3383 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SUPERPULEMET] then
3384 begin
3385 if a and FWeapon[WEAPON_SUPERPULEMET] then Exit;
3387 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3388 FWeapon[WEAPON_SUPERPULEMET] := True;
3389 Result := True;
3390 if gFlash = 2 then Inc(FPickup, 5);
3391 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3392 end;
3394 ITEM_WEAPON_FLAMETHROWER:
3395 if (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) or not FWeapon[WEAPON_FLAMETHROWER] then
3396 begin
3397 if a and FWeapon[WEAPON_FLAMETHROWER] then Exit;
3399 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3400 FWeapon[WEAPON_FLAMETHROWER] := True;
3401 Result := True;
3402 if gFlash = 2 then Inc(FPickup, 5);
3403 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3404 end;
3406 ITEM_AMMO_BULLETS:
3407 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3408 begin
3409 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3410 Result := True;
3411 remove := True;
3412 if gFlash = 2 then Inc(FPickup, 5);
3413 end;
3415 ITEM_AMMO_BULLETS_BOX:
3416 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3417 begin
3418 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3419 Result := True;
3420 remove := True;
3421 if gFlash = 2 then Inc(FPickup, 5);
3422 end;
3424 ITEM_AMMO_SHELLS:
3425 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3426 begin
3427 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3428 Result := True;
3429 remove := True;
3430 if gFlash = 2 then Inc(FPickup, 5);
3431 end;
3433 ITEM_AMMO_SHELLS_BOX:
3434 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3435 begin
3436 IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
3437 Result := True;
3438 remove := True;
3439 if gFlash = 2 then Inc(FPickup, 5);
3440 end;
3442 ITEM_AMMO_ROCKET:
3443 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3444 begin
3445 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3446 Result := True;
3447 remove := True;
3448 if gFlash = 2 then Inc(FPickup, 5);
3449 end;
3451 ITEM_AMMO_ROCKET_BOX:
3452 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3453 begin
3454 IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
3455 Result := True;
3456 remove := True;
3457 if gFlash = 2 then Inc(FPickup, 5);
3458 end;
3460 ITEM_AMMO_CELL:
3461 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3462 begin
3463 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3464 Result := True;
3465 remove := True;
3466 if gFlash = 2 then Inc(FPickup, 5);
3467 end;
3469 ITEM_AMMO_CELL_BIG:
3470 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3471 begin
3472 IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
3473 Result := True;
3474 remove := True;
3475 if gFlash = 2 then Inc(FPickup, 5);
3476 end;
3478 ITEM_AMMO_FUELCAN:
3479 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3480 begin
3481 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3482 Result := True;
3483 remove := True;
3484 if gFlash = 2 then Inc(FPickup, 5);
3485 end;
3487 ITEM_AMMO_BACKPACK:
3488 if not(R_ITEM_BACKPACK in FRulez) or
3489 (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
3490 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
3491 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
3492 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
3493 (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) then
3494 begin
3495 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
3496 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
3497 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
3498 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
3499 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
3501 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3502 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3503 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3504 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3505 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3506 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3507 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3508 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3509 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3510 IncMax(FAmmo[A_FUEL], 50, FMaxAmmo[A_FUEL]);
3512 FRulez := FRulez + [R_ITEM_BACKPACK];
3513 Result := True;
3514 remove := True;
3515 if gFlash = 2 then Inc(FPickup, 5);
3516 end;
3518 ITEM_KEY_RED:
3519 if not(R_KEY_RED in FRulez) then
3520 begin
3521 Include(FRulez, R_KEY_RED);
3522 Result := True;
3523 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3524 if gFlash = 2 then Inc(FPickup, 5);
3525 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3526 end;
3528 ITEM_KEY_GREEN:
3529 if not(R_KEY_GREEN in FRulez) then
3530 begin
3531 Include(FRulez, R_KEY_GREEN);
3532 Result := True;
3533 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3534 if gFlash = 2 then Inc(FPickup, 5);
3535 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3536 end;
3538 ITEM_KEY_BLUE:
3539 if not(R_KEY_BLUE in FRulez) then
3540 begin
3541 Include(FRulez, R_KEY_BLUE);
3542 Result := True;
3543 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3544 if gFlash = 2 then Inc(FPickup, 5);
3545 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3546 end;
3548 ITEM_SUIT:
3549 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
3550 begin
3551 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
3552 Result := True;
3553 remove := True;
3554 FFireTime := 0;
3555 if gFlash = 2 then Inc(FPickup, 5);
3556 end;
3558 ITEM_OXYGEN:
3559 if FAir < AIR_MAX then
3560 begin
3561 FAir := AIR_MAX;
3562 Result := True;
3563 remove := True;
3564 if gFlash = 2 then Inc(FPickup, 5);
3565 end;
3567 ITEM_MEDKIT_BLACK:
3568 begin
3569 if not (R_BERSERK in FRulez) then
3570 begin
3571 Include(FRulez, R_BERSERK);
3572 if allowBerserkSwitching then
3573 begin
3574 FCurrWeap := WEAPON_KASTET;
3575 resetWeaponQueue();
3576 FModel.SetWeapon(WEAPON_KASTET);
3577 end;
3578 if gFlash <> 0 then
3579 begin
3580 Inc(FPain, 100);
3581 if gFlash = 2 then Inc(FPickup, 5);
3582 end;
3583 FBerserk := gTime+30000;
3584 Result := True;
3585 remove := True;
3586 FFireTime := 0;
3587 end;
3588 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3589 begin
3590 if FHealth < PLAYER_HP_SOFT then FHealth := PLAYER_HP_SOFT;
3591 FBerserk := gTime+30000;
3592 Result := True;
3593 remove := True;
3594 FFireTime := 0;
3595 end;
3596 end;
3598 ITEM_INVUL:
3599 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
3600 begin
3601 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
3602 FSpawnInvul := 0;
3603 Result := True;
3604 remove := True;
3605 if gFlash = 2 then Inc(FPickup, 5);
3606 end;
3608 ITEM_BOTTLE:
3609 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3610 begin
3611 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
3612 Result := True;
3613 remove := True;
3614 FFireTime := 0;
3615 if gFlash = 2 then Inc(FPickup, 5);
3616 end;
3618 ITEM_HELMET:
3619 if FArmor < PLAYER_AP_LIMIT then
3620 begin
3621 IncMax(FArmor, 5, PLAYER_AP_LIMIT);
3622 Result := True;
3623 remove := True;
3624 if gFlash = 2 then Inc(FPickup, 5);
3625 end;
3627 ITEM_JETPACK:
3628 if FJetFuel < JET_MAX then
3629 begin
3630 FJetFuel := JET_MAX;
3631 Result := True;
3632 remove := True;
3633 if gFlash = 2 then Inc(FPickup, 5);
3634 end;
3636 ITEM_INVIS:
3637 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
3638 begin
3639 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
3640 Result := True;
3641 remove := True;
3642 if gFlash = 2 then Inc(FPickup, 5);
3643 end;
3644 end;
3645 end;
3647 procedure TPlayer.Touch();
3648 begin
3649 if not FAlive then
3650 Exit;
3651 //FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
3652 if FIamBot then
3653 begin
3654 // Бросить флаг товарищу:
3655 if gGameSettings.GameMode = GM_CTF then
3656 DropFlag();
3657 end;
3658 end;
3660 procedure TPlayer.Push(vx, vy: Integer);
3661 begin
3662 if (not FPhysics) and FGhost then
3663 Exit;
3664 FObj.Accel.X := FObj.Accel.X + vx;
3665 FObj.Accel.Y := FObj.Accel.Y + vy;
3666 if g_Game_IsNet and g_Game_IsServer then
3667 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3668 end;
3670 procedure TPlayer.Reset(Force: Boolean);
3671 begin
3672 if Force then
3673 FAlive := False;
3675 FSpawned := False;
3676 FTime[T_RESPAWN] := 0;
3677 FTime[T_FLAGCAP] := 0;
3678 FGodMode := False;
3679 FNoTarget := False;
3680 FNoReload := False;
3681 FFrags := 0;
3682 FLastFrag := 0;
3683 FComboEvnt := -1;
3684 FKills := 0;
3685 FMonsterKills := 0;
3686 FDeath := 0;
3687 FSecrets := 0;
3688 FSpawnInvul := 0;
3689 FCorpse := -1;
3690 FReady := False;
3691 if FNoRespawn then
3692 begin
3693 FSpectator := False;
3694 FGhost := False;
3695 FPhysics := True;
3696 FSpectatePlayer := -1;
3697 FNoRespawn := False;
3698 end;
3699 FLives := gGameSettings.MaxLives;
3701 SetFlag(FLAG_NONE);
3702 end;
3704 procedure TPlayer.SoftReset();
3705 begin
3706 ReleaseKeys();
3708 FDamageBuffer := 0;
3709 FSlopeOld := 0;
3710 FIncCamOld := 0;
3711 FIncCam := 0;
3712 FBFGFireCounter := -1;
3713 FShellTimer := -1;
3714 FPain := 0;
3715 FLastHit := 0;
3716 FLastFrag := 0;
3717 FComboEvnt := -1;
3719 SetFlag(FLAG_NONE);
3720 SetAction(A_STAND, True);
3721 end;
3723 function TPlayer.GetRespawnPoint(): Byte;
3724 var
3725 c: Byte;
3726 begin
3727 Result := 255;
3728 // На будущее: FSpawn - игрок уже играл и перерождается
3730 // Одиночная игра/кооператив
3731 if gGameSettings.GameMode in [GM_COOP, GM_SINGLE] then
3732 begin
3733 if Self = gPlayer1 then
3734 begin
3735 // player 1 should try to spawn on the player 1 point
3736 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3737 Exit(RESPAWNPOINT_PLAYER1)
3738 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3739 Exit(RESPAWNPOINT_PLAYER2);
3740 end
3741 else if Self = gPlayer2 then
3742 begin
3743 // player 2 should try to spawn on the player 2 point
3744 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3745 Exit(RESPAWNPOINT_PLAYER2)
3746 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3747 Exit(RESPAWNPOINT_PLAYER1);
3748 end
3749 else
3750 begin
3751 // other players randomly pick either the first or the second point
3752 c := IfThen((Random(2) = 0), RESPAWNPOINT_PLAYER1, RESPAWNPOINT_PLAYER2);
3753 if g_Map_GetPointCount(c) > 0 then
3754 Exit(c);
3755 // try the other one
3756 c := IfThen((c = RESPAWNPOINT_PLAYER1), RESPAWNPOINT_PLAYER2, RESPAWNPOINT_PLAYER1);
3757 if g_Map_GetPointCount(c) > 0 then
3758 Exit(c);
3759 end;
3760 end;
3762 // Мясоповал
3763 if gGameSettings.GameMode = GM_DM then
3764 begin
3765 // try DM points first
3766 if g_Map_GetPointCount(RESPAWNPOINT_DM) > 0 then
3767 Exit(RESPAWNPOINT_DM);
3768 end;
3770 // Командные
3771 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3772 begin
3773 // try team points first
3774 c := RESPAWNPOINT_DM;
3775 if FTeam = TEAM_RED then
3776 c := RESPAWNPOINT_RED
3777 else if FTeam = TEAM_BLUE then
3778 c := RESPAWNPOINT_BLUE;
3779 if g_Map_GetPointCount(c) > 0 then
3780 Exit(c);
3781 end;
3783 // still haven't found a spawnpoint, try random shit
3784 Result := g_Map_GetRandomPointType();
3785 end;
3787 procedure TPlayer.Respawn(Silent: Boolean; Force: Boolean = False);
3788 var
3789 RespawnPoint: TRespawnPoint;
3790 a, b, c: Byte;
3791 begin
3792 FSlopeOld := 0;
3793 FIncCamOld := 0;
3794 FIncCam := 0;
3795 FBFGFireCounter := -1;
3796 FShellTimer := -1;
3797 FPain := 0;
3798 FLastHit := 0;
3799 FSpawnInvul := 0;
3800 FCorpse := -1;
3802 if not g_Game_IsServer then
3803 Exit;
3804 if FDummy then
3805 Exit;
3806 FWantsInGame := True;
3807 FJustTeleported := True;
3808 if Force then
3809 begin
3810 FTime[T_RESPAWN] := 0;
3811 FAlive := False;
3812 end;
3813 FNetTime := 0;
3814 // if server changes MaxLives we gotta be ready
3815 if gGameSettings.MaxLives = 0 then FNoRespawn := False;
3817 // Еще нельзя возродиться:
3818 if FTime[T_RESPAWN] > gTime then
3819 Exit;
3821 // Просрал все жизни:
3822 if FNoRespawn then
3823 begin
3824 if not FSpectator then Spectate(True);
3825 FWantsInGame := True;
3826 Exit;
3827 end;
3829 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.GameMode <> GM_COOP) then
3830 begin // "Своя игра"
3831 // Берсерк не сохраняется между уровнями:
3832 FRulez := FRulez-[R_BERSERK];
3833 end
3834 else // "Одиночная игра"/"Кооп"
3835 begin
3836 // Берсерк и ключи не сохраняются между уровнями:
3837 FRulez := FRulez-[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE, R_BERSERK];
3838 end;
3840 // Получаем точку спауна игрока:
3841 c := GetRespawnPoint();
3843 ReleaseKeys();
3844 SetFlag(FLAG_NONE);
3846 // Воскрешение без оружия:
3847 if not FAlive then
3848 begin
3849 FHealth := Round(PLAYER_HP_SOFT * (FHandicap / 100));
3850 FArmor := 0;
3851 FAlive := True;
3852 FAir := AIR_DEF;
3853 FJetFuel := 0;
3855 for a := WP_FIRST to WP_LAST do
3856 begin
3857 FWeapon[a] := False;
3858 FReloading[a] := 0;
3859 end;
3861 FWeapon[WEAPON_PISTOL] := True;
3862 FWeapon[WEAPON_KASTET] := True;
3863 FCurrWeap := WEAPON_PISTOL;
3864 resetWeaponQueue();
3866 FModel.SetWeapon(FCurrWeap);
3868 for b := A_BULLETS to A_HIGH do
3869 FAmmo[b] := 0;
3871 FAmmo[A_BULLETS] := 50;
3873 FMaxAmmo[A_BULLETS] := AmmoLimits[0, A_BULLETS];
3874 FMaxAmmo[A_SHELLS] := AmmoLimits[0, A_SHELLS];
3875 FMaxAmmo[A_ROCKETS] := AmmoLimits[0, A_SHELLS];
3876 FMaxAmmo[A_CELLS] := AmmoLimits[0, A_CELLS];
3877 FMaxAmmo[A_FUEL] := AmmoLimits[0, A_FUEL];
3879 if (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) and
3880 LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS) then
3881 FRulez := [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE]
3882 else
3883 FRulez := [];
3884 end;
3886 // Получаем координаты точки возрождения:
3887 if not g_Map_GetPoint(c, RespawnPoint) then
3888 begin
3889 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3890 Exit;
3891 end;
3893 // Установка координат и сброс всех параметров:
3894 FObj.X := RespawnPoint.X-PLAYER_RECT.X;
3895 FObj.Y := RespawnPoint.Y-PLAYER_RECT.Y;
3896 FObj.oldX := FObj.X; // don't interpolate after respawn
3897 FObj.oldY := FObj.Y;
3898 FObj.Vel.X := 0;
3899 FObj.Vel.Y := 0;
3900 FObj.Accel.X := 0;
3901 FObj.Accel.Y := 0;
3903 FDirection := RespawnPoint.Direction;
3904 if FDirection = TDirection.D_LEFT then
3905 FAngle := 180
3906 else
3907 FAngle := 0;
3909 SetAction(A_STAND, True);
3910 FModel.Direction := FDirection;
3912 for a := Low(FTime) to High(FTime) do
3913 FTime[a] := 0;
3915 for a := Low(FMegaRulez) to High(FMegaRulez) do
3916 FMegaRulez[a] := 0;
3918 // Respawn invulnerability
3919 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.SpawnInvul > 0) then
3920 begin
3921 FMegaRulez[MR_INVUL] := gTime + gGameSettings.SpawnInvul * 1000;
3922 FSpawnInvul := FMegaRulez[MR_INVUL];
3923 end;
3925 FDamageBuffer := 0;
3926 FJetpack := False;
3927 FCanJetpack := False;
3928 FFlaming := False;
3929 FFireTime := 0;
3930 FFirePainTime := 0;
3931 FFireAttacker := 0;
3933 // Анимация возрождения:
3934 if (not gLoadGameMode) and (not Silent) then
3935 r_GFX_OnceAnim(
3936 R_GFX_TELEPORT_FAST,
3937 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
3938 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
3939 );
3941 FSpectator := False;
3942 FGhost := False;
3943 FPhysics := True;
3944 FSpectatePlayer := -1;
3945 FSpawned := True;
3947 if (gPlayer1 = nil) and (gSpectLatchPID1 = FUID) then
3948 gPlayer1 := self;
3949 if (gPlayer2 = nil) and (gSpectLatchPID2 = FUID) then
3950 gPlayer2 := self;
3952 if g_Game_IsNet then
3953 begin
3954 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3955 MH_SEND_PlayerStats(FUID, NET_EVERYONE);
3956 if not Silent then
3957 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
3958 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32,
3959 0, NET_GFX_TELE);
3960 end;
3961 end;
3963 procedure TPlayer.Spectate(NoMove: Boolean = False);
3964 begin
3965 if FAlive then
3966 Kill(K_EXTRAHARDKILL, FUID, HIT_SOME)
3967 else if (not NoMove) then
3968 begin
3969 GameX := gMapInfo.Width div 2;
3970 GameY := gMapInfo.Height div 2;
3971 end;
3972 FXTo := GameX;
3973 FYTo := GameY;
3975 FAlive := False;
3976 FSpectator := True;
3977 FGhost := True;
3978 FPhysics := False;
3979 FWantsInGame := False;
3980 FSpawned := False;
3981 FCorpse := -1;
3983 if FNoRespawn then
3984 begin
3985 if Self = gPlayer1 then
3986 begin
3987 gSpectLatchPID1 := FUID;
3988 gPlayer1 := nil;
3989 end
3990 else if Self = gPlayer2 then
3991 begin
3992 gSpectLatchPID2 := FUID;
3993 gPlayer2 := nil;
3994 end;
3995 end;
3997 if g_Game_IsNet then
3998 MH_SEND_PlayerStats(FUID);
3999 end;
4001 procedure TPlayer.SwitchNoClip;
4002 begin
4003 if not FAlive then
4004 Exit;
4005 FGhost := not FGhost;
4006 FPhysics := not FGhost;
4007 if FGhost then
4008 begin
4009 FXTo := FObj.X;
4010 FYTo := FObj.Y;
4011 end else
4012 begin
4013 FObj.Accel.X := 0;
4014 FObj.Accel.Y := 0;
4015 end;
4016 end;
4018 procedure TPlayer.Run(Direction: TDirection);
4019 var
4020 a, b: Integer;
4021 begin
4022 if MAX_RUNVEL > 8 then
4023 FlySmoke();
4025 // Бежим:
4026 if Direction = TDirection.D_LEFT then
4027 begin
4028 if FObj.Vel.X > -MAX_RUNVEL then
4029 FObj.Vel.X := FObj.Vel.X - (MAX_RUNVEL shr 3);
4030 end
4031 else
4032 if FObj.Vel.X < MAX_RUNVEL then
4033 FObj.Vel.X := FObj.Vel.X + (MAX_RUNVEL shr 3);
4035 // Возможно, пинаем куски:
4036 if (FObj.Vel.X <> 0) and (gGibs <> nil) then
4037 begin
4038 b := Abs(FObj.Vel.X);
4039 if b > 1 then b := b * (Random(8 div b) + 1);
4040 for a := 0 to High(gGibs) do
4041 begin
4042 if gGibs[a].alive and
4043 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
4044 FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
4045 begin
4046 // Пинаем куски
4047 if FObj.Vel.X < 0 then
4048 begin
4049 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)+120) // налево
4050 end
4051 else
4052 begin
4053 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)); // направо
4054 end;
4055 gGibs[a].positionChanged(); // this updates spatial accelerators
4056 end;
4057 end;
4058 end;
4060 SetAction(A_WALK);
4061 end;
4063 procedure TPlayer.SeeDown();
4064 begin
4065 SetAction(A_SEEDOWN);
4067 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTDOWN else FAngle := ANGLE_RIGHTDOWN;
4069 if FIncCam > -120 then DecMin(FIncCam, 5, -120);
4070 end;
4072 procedure TPlayer.SeeUp();
4073 begin
4074 SetAction(A_SEEUP);
4076 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTUP else FAngle := ANGLE_RIGHTUP;
4078 if FIncCam < 120 then IncMax(FIncCam, 5, 120);
4079 end;
4081 procedure TPlayer.SetAction(Action: Byte; Force: Boolean = False);
4082 var
4083 Prior: Byte;
4084 begin
4085 case Action of
4086 A_WALK: Prior := 3;
4087 A_DIE1: Prior := 5;
4088 A_DIE2: Prior := 5;
4089 A_ATTACK: Prior := 2;
4090 A_SEEUP: Prior := 1;
4091 A_SEEDOWN: Prior := 1;
4092 A_ATTACKUP: Prior := 2;
4093 A_ATTACKDOWN: Prior := 2;
4094 A_PAIN: Prior := 4;
4095 else Prior := 0;
4096 end;
4098 if (Prior > FActionPrior) or Force then
4099 if not ((Prior = 2) and (FCurrWeap = WEAPON_SAW)) then
4100 begin
4101 FActionPrior := Prior;
4102 FActionAnim := Action;
4103 FActionForce := Force;
4104 FActionChanged := True;
4105 end;
4107 if Action in [A_ATTACK, A_ATTACKUP, A_ATTACKDOWN] then FModel.SetFire(True);
4108 end;
4110 function TPlayer.StayOnStep(XInc, YInc: Integer): Boolean;
4111 begin
4112 Result := not g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height-1,
4113 PLAYER_RECT.Width, 1, PANEL_STEP, False)
4114 and g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height,
4115 PLAYER_RECT.Width, 1, PANEL_STEP, False);
4116 end;
4118 function TPlayer.TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
4119 begin
4120 Result := False;
4122 if g_CollideLevel(X, Y, PLAYER_RECT.Width, PLAYER_RECT.Height) then
4123 begin
4124 g_Sound_PlayExAt('SOUND_GAME_NOTELEPORT', FObj.X, FObj.Y);
4125 if g_Game_IsServer and g_Game_IsNet then
4126 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_GAME_NOTELEPORT');
4127 Exit;
4128 end;
4130 FJustTeleported := True;
4132 if not silent then
4133 begin
4134 g_Sound_PlayExAt('SOUND_GAME_TELEPORT', FObj.X, FObj.Y);
4135 r_GFX_OnceAnim(
4136 R_GFX_TELEPORT_FAST,
4137 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4138 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4139 );
4140 if g_Game_IsServer and g_Game_IsNet then
4141 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4142 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 1,
4143 NET_GFX_TELE);
4144 end;
4146 FObj.X := X-PLAYER_RECT.X;
4147 FObj.Y := Y-PLAYER_RECT.Y;
4148 FObj.oldX := FObj.X; // don't interpolate after respawn
4149 FObj.oldY := FObj.Y;
4150 if FAlive and FGhost then
4151 begin
4152 FXTo := FObj.X;
4153 FYTo := FObj.Y;
4154 end;
4156 if not g_Game_IsNet then
4157 begin
4158 if dir = 1 then
4159 begin
4160 SetDirection(TDirection.D_LEFT);
4161 FAngle := 180;
4162 end
4163 else
4164 if dir = 2 then
4165 begin
4166 SetDirection(TDirection.D_RIGHT);
4167 FAngle := 0;
4168 end
4169 else
4170 if dir = 3 then
4171 begin // обратное
4172 if FDirection = TDirection.D_RIGHT then
4173 begin
4174 SetDirection(TDirection.D_LEFT);
4175 FAngle := 180;
4176 end
4177 else
4178 begin
4179 SetDirection(TDirection.D_RIGHT);
4180 FAngle := 0;
4181 end;
4182 end;
4183 end;
4185 if not silent then
4186 begin
4187 r_GFX_OnceAnim(
4188 R_GFX_TELEPORT_FAST,
4189 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4190 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4191 );
4192 if g_Game_IsServer and g_Game_IsNet then
4193 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4194 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 0,
4195 NET_GFX_TELE);
4196 end;
4198 Result := True;
4199 end;
4201 function nonz(a: Single): Single;
4202 begin
4203 if a <> 0 then
4204 Result := a
4205 else
4206 Result := 1;
4207 end;
4209 function TPlayer.refreshCorpse(): Boolean;
4210 var
4211 i: Integer;
4212 begin
4213 Result := False;
4214 FCorpse := -1;
4215 if FAlive or FSpectator then
4216 Exit;
4217 if (gCorpses = nil) or (Length(gCorpses) = 0) then
4218 Exit;
4219 for i := 0 to High(gCorpses) do
4220 if gCorpses[i] <> nil then
4221 if gCorpses[i].FPlayerUID = FUID then
4222 begin
4223 Result := True;
4224 FCorpse := i;
4225 break;
4226 end;
4227 end;
4229 function TPlayer.getCameraObj(): TObj;
4230 begin
4231 if (not FAlive) and (not FSpectator) and
4232 (FCorpse >= 0) and (FCorpse < Length(gCorpses)) and
4233 (gCorpses[FCorpse] <> nil) and (gCorpses[FCorpse].FPlayerUID = FUID) then
4234 begin
4235 gCorpses[FCorpse].FObj.slopeUpLeft := FObj.slopeUpLeft;
4236 Result := gCorpses[FCorpse].FObj;
4237 end
4238 else
4239 begin
4240 Result := FObj;
4241 end;
4242 end;
4244 procedure TPlayer.PreUpdate();
4245 begin
4246 FSlopeOld := FObj.slopeUpLeft;
4247 FIncCamOld := FIncCam;
4248 FObj.oldX := FObj.X;
4249 FObj.oldY := FObj.Y;
4250 end;
4252 procedure TPlayer.Update();
4253 var
4254 b: Byte;
4255 i, ii, wx, wy, xd, yd, k: Integer;
4256 blockmon, headwater, dospawn: Boolean;
4257 NetServer: Boolean;
4258 AnyServer: Boolean;
4259 SetSpect: Boolean;
4260 begin
4261 NetServer := g_Game_IsNet and g_Game_IsServer;
4262 AnyServer := g_Game_IsServer;
4264 if g_Game_IsClient and (NetInterpLevel > 0) then
4265 DoLerp(NetInterpLevel + 1)
4266 else
4267 if FGhost then
4268 DoLerp(4);
4270 if NetServer then
4271 if FClientID >= 0 then
4272 begin
4273 FPing := NetClients[FClientID].Peer^.lastRoundTripTime;
4274 if NetClients[FClientID].Peer^.packetsSent > 0 then
4275 FLoss := Round(100*NetClients[FClientID].Peer^.packetsLost/NetClients[FClientID].Peer^.packetsSent)
4276 else
4277 FLoss := 0;
4278 end else
4279 begin
4280 FPing := 0;
4281 FLoss := 0;
4282 end;
4284 if FAlive then
4285 FPunchAnim.Update;
4286 if FPunchAnim.played then
4287 FPunchAnim.Disable;
4289 if FAlive and (gFly or FJetpack) then
4290 FlySmoke();
4292 if FDirection = TDirection.D_LEFT then
4293 FAngle := 180
4294 else
4295 FAngle := 0;
4297 if FAlive and (not FGhost) then
4298 begin
4299 if FKeys[KEY_UP].Pressed then
4300 SeeUp();
4301 if FKeys[KEY_DOWN].Pressed then
4302 SeeDown();
4303 end;
4305 if (not (FKeys[KEY_UP].Pressed or FKeys[KEY_DOWN].Pressed)) and
4306 (FIncCam <> 0) then
4307 begin
4308 i := g_basic.Sign(FIncCam);
4309 FIncCam := Abs(FIncCam);
4310 DecMin(FIncCam, 5, 0);
4311 FIncCam := FIncCam*i;
4312 end;
4314 // no need to do that each second frame, weapon queue will take care of it
4315 if FAlive and FKeys[KEY_NEXTWEAPON].Pressed and AnyServer then NextWeapon();
4316 if FAlive and FKeys[KEY_PREVWEAPON].Pressed and AnyServer then PrevWeapon();
4318 if gTime mod (GAME_TICK*2) <> 0 then
4319 begin
4320 if (FObj.Vel.X = 0) and FAlive then
4321 begin
4322 if FKeys[KEY_LEFT].Pressed then
4323 Run(TDirection.D_LEFT);
4324 if FKeys[KEY_RIGHT].Pressed then
4325 Run(TDirection.D_RIGHT);
4326 end;
4328 if FPhysics then
4329 begin
4330 g_Obj_Move(@FObj, True, True, True);
4331 positionChanged(); // this updates spatial accelerators
4332 end;
4334 Exit;
4335 end;
4337 FActionChanged := False;
4339 if FAlive then
4340 begin
4341 // Let alive player do some actions
4342 if FKeys[KEY_LEFT].Pressed then Run(TDirection.D_LEFT);
4343 if FKeys[KEY_RIGHT].Pressed then Run(TDirection.D_RIGHT);
4344 //if FKeys[KEY_NEXTWEAPON].Pressed and AnyServer then NextWeapon();
4345 //if FKeys[KEY_PREVWEAPON].Pressed and AnyServer then PrevWeapon();
4346 if FKeys[KEY_FIRE].Pressed and AnyServer then Fire()
4347 else
4348 begin
4349 if AnyServer then
4350 begin
4351 FlamerOff;
4352 if NetServer then MH_SEND_PlayerStats(FUID);
4353 end;
4354 end;
4355 if FKeys[KEY_OPEN].Pressed and AnyServer then Use();
4356 if FKeys[KEY_JUMP].Pressed then Jump()
4357 else
4358 begin
4359 if AnyServer and FJetpack then
4360 begin
4361 FJetpack := False;
4362 JetpackOff;
4363 if NetServer then MH_SEND_PlayerStats(FUID);
4364 end;
4365 FCanJetpack := True;
4366 end;
4367 end
4368 else // Dead
4369 begin
4370 dospawn := False;
4371 if not FGhost then
4372 for k := Low(FKeys) to KEY_CHAT-1 do
4373 begin
4374 if FKeys[k].Pressed then
4375 begin
4376 dospawn := True;
4377 break;
4378 end;
4379 end;
4380 if dospawn then
4381 begin
4382 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
4383 Respawn(False)
4384 else // Single
4385 if (FTime[T_RESPAWN] <= gTime) and
4386 gGameOn and (not FAlive) then
4387 begin
4388 if (g_Player_GetCount() > 1) then
4389 Respawn(False)
4390 else
4391 begin
4392 gExit := EXIT_RESTART;
4393 Exit;
4394 end;
4395 end;
4396 end;
4397 // Dead spectator actions
4398 if FGhost then
4399 begin
4400 if FKeys[KEY_OPEN].Pressed and AnyServer then Fire();
4401 if FKeys[KEY_FIRE].Pressed and AnyServer then
4402 begin
4403 if FSpectator then
4404 begin
4405 if (FSpectatePlayer >= High(gPlayers)) then
4406 FSpectatePlayer := -1
4407 else
4408 begin
4409 SetSpect := False;
4410 for I := FSpectatePlayer + 1 to High(gPlayers) do
4411 if gPlayers[I] <> nil then
4412 if gPlayers[I].alive then
4413 if gPlayers[I].UID <> FUID then
4414 begin
4415 FSpectatePlayer := I;
4416 SetSpect := True;
4417 break;
4418 end;
4420 if not SetSpect then FSpectatePlayer := -1;
4421 end;
4423 ReleaseKeys;
4424 end;
4425 end;
4426 end;
4427 end;
4428 // No clipping
4429 if FGhost then
4430 begin
4431 if FKeys[KEY_UP].Pressed or FKeys[KEY_JUMP].Pressed then
4432 begin
4433 FYTo := FObj.Y - 32;
4434 FSpectatePlayer := -1;
4435 end;
4436 if FKeys[KEY_DOWN].Pressed then
4437 begin
4438 FYTo := FObj.Y + 32;
4439 FSpectatePlayer := -1;
4440 end;
4441 if FKeys[KEY_LEFT].Pressed then
4442 begin
4443 FXTo := FObj.X - 32;
4444 FSpectatePlayer := -1;
4445 end;
4446 if FKeys[KEY_RIGHT].Pressed then
4447 begin
4448 FXTo := FObj.X + 32;
4449 FSpectatePlayer := -1;
4450 end;
4452 if (FXTo < -64) then
4453 FXTo := -64
4454 else if (FXTo > gMapInfo.Width + 32) then
4455 FXTo := gMapInfo.Width + 32;
4456 if (FYTo < -72) then
4457 FYTo := -72
4458 else if (FYTo > gMapInfo.Height + 32) then
4459 FYTo := gMapInfo.Height + 32;
4460 end;
4462 if FPhysics then
4463 begin
4464 g_Obj_Move(@FObj, True, True, True);
4465 positionChanged(); // this updates spatial accelerators
4466 end
4467 else
4468 begin
4469 FObj.Vel.X := 0;
4470 FObj.Vel.Y := 0;
4471 if FSpectator then
4472 if (FSpectatePlayer <= High(gPlayers)) and (FSpectatePlayer >= 0) then
4473 if gPlayers[FSpectatePlayer] <> nil then
4474 if gPlayers[FSpectatePlayer].alive then
4475 begin
4476 FXTo := gPlayers[FSpectatePlayer].GameX;
4477 FYTo := gPlayers[FSpectatePlayer].GameY;
4478 end;
4479 end;
4481 blockmon := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X, FObj.Y+PLAYER_HEADRECT.Y,
4482 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
4483 PANEL_BLOCKMON, True);
4484 headwater := HeadInLiquid(0, 0);
4486 // Сопротивление воздуха:
4487 if (not FAlive) or not (FKeys[KEY_LEFT].Pressed or FKeys[KEY_RIGHT].Pressed) then
4488 if FObj.Vel.X <> 0 then
4489 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
4491 if (FLastHit = HIT_TRAP) and (FPain > 90) then FPain := 90;
4492 DecMin(FPain, 5, 0);
4493 DecMin(FPickup, 1, 0);
4495 if FAlive and (FObj.Y > Integer(gMapInfo.Height)+128) and AnyServer then
4496 begin
4497 // Обнулить действия примочек, чтобы фон пропал
4498 FMegaRulez[MR_SUIT] := 0;
4499 FMegaRulez[MR_INVUL] := 0;
4500 FMegaRulez[MR_INVIS] := 0;
4501 Kill(K_FALLKILL, 0, HIT_FALL);
4502 end;
4504 i := 9;
4506 if FAlive then
4507 begin
4508 if FCurrWeap = WEAPON_SAW then
4509 if not (FSawSound.IsPlaying() or FSawSoundHit.IsPlaying() or
4510 FSawSoundSelect.IsPlaying()) then
4511 FSawSoundIdle.PlayAt(FObj.X, FObj.Y);
4513 if FJetpack then
4514 if (not FJetSoundFly.IsPlaying()) and (not FJetSoundOn.IsPlaying()) and
4515 (not FJetSoundOff.IsPlaying()) then
4516 begin
4517 FJetSoundFly.SetPosition(0);
4518 FJetSoundFly.PlayAt(FObj.X, FObj.Y);
4519 end;
4521 for b := WP_FIRST to WP_LAST do
4522 if FReloading[b] > 0 then
4523 if FNoReload then
4524 FReloading[b] := 0
4525 else
4526 Dec(FReloading[b]);
4528 if FShellTimer > -1 then
4529 if FShellTimer = 0 then
4530 begin
4531 if FShellType = SHELL_SHELL then
4532 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4533 GameVelX, GameVelY-2, SHELL_SHELL)
4534 else if FShellType = SHELL_DBLSHELL then
4535 begin
4536 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4537 GameVelX+1, GameVelY-2, SHELL_SHELL);
4538 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4539 GameVelX-1, GameVelY-2, SHELL_SHELL);
4540 end;
4541 FShellTimer := -1;
4542 end else Dec(FShellTimer);
4544 if (FBFGFireCounter > -1) then
4545 if FBFGFireCounter = 0 then
4546 begin
4547 if AnyServer then
4548 begin
4549 wx := FObj.X+WEAPONPOINT[FDirection].X;
4550 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
4551 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
4552 yd := wy+firediry();
4553 g_Weapon_bfgshot(wx, wy, xd, yd, FUID);
4554 if NetServer then MH_SEND_PlayerFire(FUID, WEAPON_BFG, wx, wy, xd, yd);
4555 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4556 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4557 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4558 end;
4560 FReloading[WEAPON_BFG] := WEAPON_RELOAD[WEAPON_BFG];
4561 FBFGFireCounter := -1;
4562 end else
4563 if FNoReload then
4564 FBFGFireCounter := 0
4565 else
4566 Dec(FBFGFireCounter);
4568 if (FMegaRulez[MR_SUIT] < gTime) and AnyServer then
4569 begin
4570 b := g_GetAcidHit(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width, PLAYER_RECT.Height);
4572 if (b > 0) and (gTime mod (15*GAME_TICK) = 0) then Damage(b, 0, 0, 0, HIT_ACID);
4573 end;
4575 if (headwater or blockmon) then
4576 begin
4577 Dec(FAir);
4579 if FAir < -9 then
4580 begin
4581 if AnyServer then Damage(10, 0, 0, 0, HIT_WATER);
4582 FAir := 0;
4583 end
4584 else if (FAir mod 31 = 0) and not blockmon then
4585 begin
4586 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2), FObj.Y+PLAYER_RECT.Y-4, 5+Random(6), 8, 4);
4587 if Random(2) = 0 then
4588 g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
4589 else
4590 g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
4591 end;
4592 end else if FAir < AIR_DEF then
4593 FAir := AIR_DEF;
4595 if FFireTime > 0 then
4596 begin
4597 if BodyInLiquid(0, 0) then
4598 begin
4599 FFireTime := 0;
4600 FFirePainTime := 0;
4601 end
4602 else if FMegaRulez[MR_SUIT] >= gTime then
4603 begin
4604 if FMegaRulez[MR_SUIT] = gTime then
4605 FFireTime := 1;
4606 FFirePainTime := 0;
4607 end
4608 else
4609 begin
4610 OnFireFlame(1);
4611 if FFirePainTime <= 0 then
4612 begin
4613 if g_Game_IsServer then
4614 Damage(2, FFireAttacker, 0, 0, HIT_FLAME);
4615 FFirePainTime := 12 - FFireTime div 12;
4616 end;
4617 FFirePainTime := FFirePainTime - 1;
4618 FFireTime := FFireTime - 1;
4619 if ((FFireTime mod 33) = 0) and (FMegaRulez[MR_INVUL] < gTime) then
4620 FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
4621 if (FFireTime = 0) and g_Game_IsNet and g_Game_IsServer then
4622 MH_SEND_PlayerStats(FUID);
4623 end;
4624 end;
4626 if FDamageBuffer > 0 then
4627 begin
4628 if FDamageBuffer >= 9 then
4629 begin
4630 SetAction(A_PAIN);
4632 if FDamageBuffer < 30 then i := 9
4633 else if FDamageBuffer < 100 then i := 18
4634 else i := 27;
4635 end;
4637 ii := Round(FDamageBuffer*FHealth / nonz(FArmor*(3/4)+FHealth));
4638 FArmor := FArmor-(FDamageBuffer-ii);
4639 FHealth := FHealth-ii;
4640 if FArmor < 0 then
4641 begin
4642 FHealth := FHealth+FArmor;
4643 FArmor := 0;
4644 end;
4646 if AnyServer then
4647 if FHealth <= 0 then
4648 if FHealth > -30 then Kill(K_SIMPLEKILL, FLastSpawnerUID, FLastHit)
4649 else if FHealth > -50 then Kill(K_HARDKILL, FLastSpawnerUID, FLastHit)
4650 else Kill(K_EXTRAHARDKILL, FLastSpawnerUID, FLastHit);
4652 if FAlive and ((FLastHit <> HIT_FLAME) or (FFireTime <= 0)) then
4653 begin
4654 if FDamageBuffer <= 20 then FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y)
4655 else if FDamageBuffer <= 55 then FModel.PlaySound(MODELSOUND_PAIN, 2, FObj.X, FObj.Y)
4656 else if FDamageBuffer <= 120 then FModel.PlaySound(MODELSOUND_PAIN, 3, FObj.X, FObj.Y)
4657 else FModel.PlaySound(MODELSOUND_PAIN, 4, FObj.X, FObj.Y);
4658 end;
4660 FDamageBuffer := 0;
4661 end;
4663 {CollideItem();}
4664 end; // if FAlive then ...
4666 if (FActionAnim = A_PAIN) and (FModel.Animation <> A_PAIN) then
4667 begin
4668 FModel.ChangeAnimation(FActionAnim, FActionForce);
4669 FModel.AnimState.MinLength := i;
4670 end else FModel.ChangeAnimation(FActionAnim, FActionForce and (FModel.Animation <> A_STAND));
4672 if (FModel.AnimState.Played or ((not FActionChanged) and (FModel.Animation = A_WALK)))
4673 then SetAction(A_STAND, True);
4675 if not ((FModel.Animation = A_WALK) and (Abs(FObj.Vel.X) < 4) and not FModel.GetFire()) then FModel.Update;
4677 for b := Low(FKeys) to High(FKeys) do
4678 if FKeys[b].Time = 0 then FKeys[b].Pressed := False else Dec(FKeys[b].Time);
4679 end;
4682 procedure TPlayer.getMapBox (out x, y, w, h: Integer); inline;
4683 begin
4684 x := FObj.X+PLAYER_RECT.X;
4685 y := FObj.Y+PLAYER_RECT.Y;
4686 w := PLAYER_RECT.Width;
4687 h := PLAYER_RECT.Height;
4688 end;
4691 procedure TPlayer.moveBy (dx, dy: Integer); inline;
4692 begin
4693 if (dx <> 0) or (dy <> 0) then
4694 begin
4695 FObj.X += dx;
4696 FObj.Y += dy;
4697 positionChanged();
4698 end;
4699 end;
4702 function TPlayer.Collide(X, Y: Integer; Width, Height: Word): Boolean;
4703 begin
4704 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4705 FObj.Y+PLAYER_RECT.Y,
4706 PLAYER_RECT.Width,
4707 PLAYER_RECT.Height,
4708 X, Y,
4709 Width, Height);
4710 end;
4712 function TPlayer.Collide(Panel: TPanel): Boolean;
4713 begin
4714 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4715 FObj.Y+PLAYER_RECT.Y,
4716 PLAYER_RECT.Width,
4717 PLAYER_RECT.Height,
4718 Panel.X, Panel.Y,
4719 Panel.Width, Panel.Height);
4720 end;
4722 function TPlayer.Collide(X, Y: Integer): Boolean;
4723 begin
4724 X := X-FObj.X-PLAYER_RECT.X;
4725 Y := Y-FObj.Y-PLAYER_RECT.Y;
4726 Result := (x >= 0) and (x <= PLAYER_RECT.Width) and
4727 (y >= 0) and (y <= PLAYER_RECT.Height);
4728 end;
4730 function g_Player_ValidName(Name: string): Boolean;
4731 var
4732 a: Integer;
4733 begin
4734 Result := True;
4736 if gPlayers = nil then Exit;
4738 for a := 0 to High(gPlayers) do
4739 if gPlayers[a] <> nil then
4740 if LowerCase(Name) = LowerCase(gPlayers[a].FName) then
4741 begin
4742 Result := False;
4743 Exit;
4744 end;
4745 end;
4747 procedure TPlayer.SetDirection(Direction: TDirection);
4748 var
4749 d: TDirection;
4750 begin
4751 d := FModel.Direction;
4753 FModel.Direction := Direction;
4754 if d <> Direction then FModel.ChangeAnimation(FModel.Animation, True);
4756 FDirection := Direction;
4757 end;
4759 function TPlayer.GetKeys(): Byte;
4760 begin
4761 Result := 0;
4763 if R_KEY_RED in FRulez then Result := KEY_RED;
4764 if R_KEY_GREEN in FRulez then Result := Result or KEY_GREEN;
4765 if R_KEY_BLUE in FRulez then Result := Result or KEY_BLUE;
4767 if FTeam = TEAM_RED then Result := Result or KEY_REDTEAM;
4768 if FTeam = TEAM_BLUE then Result := Result or KEY_BLUETEAM;
4769 end;
4771 procedure TPlayer.Use();
4772 var
4773 a: Integer;
4774 begin
4775 if FTime[T_USE] > gTime then Exit;
4777 g_Triggers_PressR(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
4778 PLAYER_RECT.Height, FUID, ACTIVATE_PLAYERPRESS);
4780 for a := 0 to High(gPlayers) do
4781 if (gPlayers[a] <> nil) and (gPlayers[a] <> Self) and
4782 gPlayers[a].alive and SameTeam(FUID, gPlayers[a].FUID) and
4783 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4784 FObj.Rect.Width, FObj.Rect.Height, @gPlayers[a].FObj) then
4785 begin
4786 gPlayers[a].Touch();
4787 if g_Game_IsNet and g_Game_IsServer then
4788 MH_SEND_GameEvent(NET_EV_PLAYER_TOUCH, gPlayers[a].FUID);
4789 end;
4791 FTime[T_USE] := gTime+120;
4792 end;
4794 procedure TPlayer.NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
4795 var
4796 locObj: TObj;
4797 F: Boolean;
4798 WX, WY, XD, YD: Integer;
4799 begin
4800 F := False;
4801 WX := X;
4802 WY := Y;
4803 XD := AX;
4804 YD := AY;
4806 case FCurrWeap of
4807 WEAPON_KASTET:
4808 begin
4809 DoPunch();
4810 if R_BERSERK in FRulez then
4811 begin
4812 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
4813 locobj.X := FObj.X+FObj.Rect.X;
4814 locobj.Y := FObj.Y+FObj.Rect.Y;
4815 locobj.rect.X := 0;
4816 locobj.rect.Y := 0;
4817 locobj.rect.Width := 39;
4818 locobj.rect.Height := 52;
4819 locobj.Vel.X := (xd-wx) div 2;
4820 locobj.Vel.Y := (yd-wy) div 2;
4821 locobj.Accel.X := xd-wx;
4822 locobj.Accel.y := yd-wy;
4824 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
4825 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
4826 else
4827 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
4829 if gFlash = 1 then
4830 if FPain < 50 then
4831 FPain := min(FPain + 25, 50);
4832 end else
4833 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
4834 end;
4836 WEAPON_SAW:
4837 begin
4838 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4839 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
4840 begin
4841 FSawSoundSelect.Stop();
4842 FSawSound.Stop();
4843 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
4844 end
4845 else if not FSawSoundHit.IsPlaying() then
4846 begin
4847 FSawSoundSelect.Stop();
4848 FSawSound.PlayAt(FObj.X, FObj.Y);
4849 end;
4850 f := True;
4851 end;
4853 WEAPON_PISTOL:
4854 begin
4855 g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', GameX, Gamey);
4856 FFireAngle := FAngle;
4857 f := True;
4858 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4859 GameVelX, GameVelY-2, SHELL_BULLET);
4860 end;
4862 WEAPON_SHOTGUN1:
4863 begin
4864 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4865 FFireAngle := FAngle;
4866 f := True;
4867 FShellTimer := 10;
4868 FShellType := SHELL_SHELL;
4869 end;
4871 WEAPON_SHOTGUN2:
4872 begin
4873 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN2', Gamex, Gamey);
4874 FFireAngle := FAngle;
4875 f := True;
4876 FShellTimer := 13;
4877 FShellType := SHELL_DBLSHELL;
4878 end;
4880 WEAPON_CHAINGUN:
4881 begin
4882 g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', Gamex, Gamey);
4883 FFireAngle := FAngle;
4884 f := True;
4885 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4886 GameVelX, GameVelY-2, SHELL_BULLET);
4887 end;
4889 WEAPON_ROCKETLAUNCHER:
4890 begin
4891 g_Weapon_Rocket(wx, wy, xd, yd, FUID, WID);
4892 FFireAngle := FAngle;
4893 f := True;
4894 end;
4896 WEAPON_PLASMA:
4897 begin
4898 g_Weapon_Plasma(wx, wy, xd, yd, FUID, WID);
4899 FFireAngle := FAngle;
4900 f := True;
4901 end;
4903 WEAPON_BFG:
4904 begin
4905 g_Weapon_BFGShot(wx, wy, xd, yd, FUID, WID);
4906 FFireAngle := FAngle;
4907 f := True;
4908 end;
4910 WEAPON_SUPERPULEMET:
4911 begin
4912 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4913 FFireAngle := FAngle;
4914 f := True;
4915 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4916 GameVelX, GameVelY-2, SHELL_SHELL);
4917 end;
4919 WEAPON_FLAMETHROWER:
4920 begin
4921 g_Weapon_flame(wx, wy, xd, yd, FUID, WID);
4922 FlamerOn;
4923 FFireAngle := FAngle;
4924 f := True;
4925 end;
4926 end;
4928 if not f then Exit;
4930 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4931 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4932 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4933 end;
4935 procedure TPlayer.DoLerp(Level: Integer = 2);
4936 begin
4937 if FObj.X <> FXTo then FObj.X := Lerp(FObj.X, FXTo, Level);
4938 if FObj.Y <> FYTo then FObj.Y := Lerp(FObj.Y, FYTo, Level);
4939 end;
4941 procedure TPlayer.SetLerp(XTo, YTo: Integer);
4942 var
4943 AX, AY: Integer;
4944 begin
4945 FXTo := XTo;
4946 FYTo := YTo;
4947 if FJustTeleported or (NetInterpLevel < 1) then
4948 begin
4949 FObj.X := XTo;
4950 FObj.Y := YTo;
4951 if FJustTeleported then
4952 begin
4953 FObj.oldX := FObj.X;
4954 FObj.oldY := FObj.Y;
4955 end;
4956 end
4957 else
4958 begin
4959 AX := Abs(FXTo - FObj.X);
4960 AY := Abs(FYTo - FObj.Y);
4961 if (AX > 32) or (AX <= NetInterpLevel) then
4962 FObj.X := FXTo;
4963 if (AY > 32) or (AY <= NetInterpLevel) then
4964 FObj.Y := FYTo;
4965 end;
4966 end;
4968 function TPlayer.FullInLift(XInc, YInc: Integer): Integer;
4969 begin
4970 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
4971 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
4972 PANEL_LIFTUP, False) then Result := -1
4973 else
4974 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
4975 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
4976 PANEL_LIFTDOWN, False) then Result := 1
4977 else Result := 0;
4978 end;
4980 function TPlayer.GetFlag(Flag: Byte): Boolean;
4981 var
4982 s, ts: String;
4983 evtype, a: Byte;
4984 begin
4985 Result := False;
4987 if Flag = FLAG_NONE then
4988 Exit;
4990 if not g_Game_IsServer then Exit;
4992 // Принес чужой флаг на свою базу:
4993 if (Flag = FTeam) and
4994 (gFlags[Flag].State = FLAG_STATE_NORMAL) and
4995 (FFlag <> FLAG_NONE) then
4996 begin
4997 if FFlag = FLAG_RED then
4998 s := _lc[I_PLAYER_FLAG_RED]
4999 else
5000 s := _lc[I_PLAYER_FLAG_BLUE];
5002 evtype := FLAG_STATE_SCORED;
5004 ts := Format('%.4d', [gFlags[FFlag].CaptureTime]);
5005 Insert('.', ts, Length(ts) + 1 - 3);
5006 g_Console_Add(Format(_lc[I_PLAYER_FLAG_CAPTURE], [FName, s, ts]), True);
5008 g_Map_ResetFlag(FFlag);
5009 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_CAPTURE], [AnsiUpperCase(s)]), 144);
5011 if ((Self = gPlayer1) or (Self = gPlayer2)
5012 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5013 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5014 a := 0
5015 else
5016 a := 1;
5018 if not sound_cap_flag[a].IsPlaying() then
5019 sound_cap_flag[a].Play();
5021 gTeamStat[FTeam].Goals := gTeamStat[FTeam].Goals + 1;
5023 Result := True;
5024 if g_Game_IsNet then
5025 begin
5026 MH_SEND_FlagEvent(evtype, FFlag, FUID, False);
5027 MH_SEND_GameStats;
5028 end;
5030 gFlags[FFlag].CaptureTime := 0;
5031 SetFlag(FLAG_NONE);
5032 Exit;
5033 end;
5035 // Подобрал свой флаг - вернул его на базу:
5036 if (Flag = FTeam) and
5037 (gFlags[Flag].State = FLAG_STATE_DROPPED) then
5038 begin
5039 if Flag = FLAG_RED then
5040 s := _lc[I_PLAYER_FLAG_RED]
5041 else
5042 s := _lc[I_PLAYER_FLAG_BLUE];
5044 evtype := FLAG_STATE_RETURNED;
5045 gFlags[Flag].CaptureTime := 0;
5047 g_Console_Add(Format(_lc[I_PLAYER_FLAG_RETURN], [FName, s]), True);
5049 g_Map_ResetFlag(Flag);
5050 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
5052 if ((Self = gPlayer1) or (Self = gPlayer2)
5053 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5054 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5055 a := 0
5056 else
5057 a := 1;
5059 if not sound_ret_flag[a].IsPlaying() then
5060 sound_ret_flag[a].Play();
5062 Result := True;
5063 if g_Game_IsNet then
5064 begin
5065 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5066 MH_SEND_GameStats;
5067 end;
5068 Exit;
5069 end;
5071 // Подобрал чужой флаг:
5072 if (Flag <> FTeam) and (FTime[T_FLAGCAP] <= gTime) then
5073 begin
5074 SetFlag(Flag);
5076 if Flag = FLAG_RED then
5077 s := _lc[I_PLAYER_FLAG_RED]
5078 else
5079 s := _lc[I_PLAYER_FLAG_BLUE];
5081 evtype := FLAG_STATE_CAPTURED;
5083 g_Console_Add(Format(_lc[I_PLAYER_FLAG_GET], [FName, s]), True);
5085 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_GET], [AnsiUpperCase(s)]), 144);
5087 gFlags[Flag].State := FLAG_STATE_CAPTURED;
5089 if ((Self = gPlayer1) or (Self = gPlayer2)
5090 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5091 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5092 a := 0
5093 else
5094 a := 1;
5096 if not sound_get_flag[a].IsPlaying() then
5097 sound_get_flag[a].Play();
5099 Result := True;
5100 if g_Game_IsNet then
5101 begin
5102 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5103 MH_SEND_GameStats;
5104 end;
5105 end;
5106 end;
5108 procedure TPlayer.SetFlag(Flag: Byte);
5109 begin
5110 FFlag := Flag;
5111 if FModel <> nil then
5112 FModel.SetFlag(FFlag);
5113 end;
5115 function TPlayer.DropFlag(Silent: Boolean = True): Boolean;
5116 var
5117 s: String;
5118 a: Byte;
5119 begin
5120 Result := False;
5121 if (not g_Game_IsServer) or (FFlag = FLAG_NONE) then
5122 Exit;
5123 FTime[T_FLAGCAP] := gTime + 2000;
5124 with gFlags[FFlag] do
5125 begin
5126 Obj.X := FObj.X;
5127 Obj.Y := FObj.Y;
5128 Direction := FDirection;
5129 State := FLAG_STATE_DROPPED;
5130 Count := FLAG_TIME;
5131 g_Obj_Push(@Obj, (FObj.Vel.X div 2)-2+Random(5),
5132 (FObj.Vel.Y div 2)-2+Random(5));
5133 positionChanged(); // this updates spatial accelerators
5135 if FFlag = FLAG_RED then
5136 s := _lc[I_PLAYER_FLAG_RED]
5137 else
5138 s := _lc[I_PLAYER_FLAG_BLUE];
5140 g_Console_Add(Format(_lc[I_PLAYER_FLAG_DROP], [FName, s]), True);
5141 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_DROP], [AnsiUpperCase(s)]), 144);
5143 if ((Self = gPlayer1) or (Self = gPlayer2)
5144 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5145 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5146 a := 0
5147 else
5148 a := 1;
5150 if (not Silent) and (not sound_lost_flag[a].IsPlaying()) then
5151 sound_lost_flag[a].Play();
5153 if g_Game_IsNet then
5154 MH_SEND_FlagEvent(FLAG_STATE_DROPPED, Flag, FUID, False);
5155 end;
5156 SetFlag(FLAG_NONE);
5157 Result := True;
5158 end;
5160 procedure TPlayer.GetSecret();
5161 begin
5162 if (self = gPlayer1) or (self = gPlayer2) then
5163 begin
5164 g_Console_Add(Format(_lc[I_PLAYER_SECRET], [FName]), True);
5165 g_Sound_PlayEx('SOUND_GAME_SECRET');
5166 end;
5167 Inc(FSecrets);
5168 end;
5170 procedure TPlayer.PressKey(Key: Byte; Time: Word = 1);
5171 begin
5172 Assert(Key <= High(FKeys));
5174 FKeys[Key].Pressed := True;
5175 FKeys[Key].Time := Time;
5176 end;
5178 function TPlayer.IsKeyPressed(K: Byte): Boolean;
5179 begin
5180 Result := FKeys[K].Pressed;
5181 end;
5183 procedure TPlayer.ReleaseKeys();
5184 var
5185 a: Integer;
5186 begin
5187 for a := Low(FKeys) to High(FKeys) do
5188 begin
5189 FKeys[a].Pressed := False;
5190 FKeys[a].Time := 0;
5191 end;
5192 end;
5194 procedure TPlayer.OnDamage(Angle: SmallInt);
5195 begin
5196 end;
5198 function TPlayer.firediry(): Integer;
5199 begin
5200 if FKeys[KEY_UP].Pressed then Result := -42
5201 else if FKeys[KEY_DOWN].Pressed then Result := 19
5202 else Result := 0;
5203 end;
5205 procedure TPlayer.RememberState();
5206 var
5207 i: Integer;
5208 SavedState: TPlayerSavedState;
5209 begin
5210 SavedState.Health := FHealth;
5211 SavedState.Armor := FArmor;
5212 SavedState.Air := FAir;
5213 SavedState.JetFuel := FJetFuel;
5214 SavedState.CurrWeap := FCurrWeap;
5215 SavedState.NextWeap := FNextWeap;
5216 SavedState.NextWeapDelay := FNextWeapDelay;
5217 for i := Low(FWeapon) to High(FWeapon) do
5218 SavedState.Weapon[i] := FWeapon[i];
5219 for i := Low(FAmmo) to High(FAmmo) do
5220 SavedState.Ammo[i] := FAmmo[i];
5221 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5222 SavedState.MaxAmmo[i] := FMaxAmmo[i];
5223 SavedState.Rulez := FRulez - [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5225 FSavedStateNum := -1;
5226 for i := Low(SavedStates) to High(SavedStates) do
5227 if not SavedStates[i].Used then
5228 begin
5229 FSavedStateNum := i;
5230 break;
5231 end;
5232 if FSavedStateNum < 0 then
5233 begin
5234 SetLength(SavedStates, Length(SavedStates) + 1);
5235 FSavedStateNum := High(SavedStates);
5236 end;
5238 SavedState.Used := True;
5239 SavedStates[FSavedStateNum] := SavedState;
5240 end;
5242 procedure TPlayer.RecallState();
5243 var
5244 i: Integer;
5245 SavedState: TPlayerSavedState;
5246 begin
5247 if(FSavedStateNum < 0) or (FSavedStateNum > High(SavedStates)) then
5248 Exit;
5250 SavedState := SavedStates[FSavedStateNum];
5251 SavedStates[FSavedStateNum].Used := False;
5252 FSavedStateNum := -1;
5254 FHealth := SavedState.Health;
5255 FArmor := SavedState.Armor;
5256 FAir := SavedState.Air;
5257 FJetFuel := SavedState.JetFuel;
5258 FCurrWeap := SavedState.CurrWeap;
5259 FNextWeap := SavedState.NextWeap;
5260 FNextWeapDelay := SavedState.NextWeapDelay;
5261 for i := Low(FWeapon) to High(FWeapon) do
5262 FWeapon[i] := SavedState.Weapon[i];
5263 for i := Low(FAmmo) to High(FAmmo) do
5264 FAmmo[i] := SavedState.Ammo[i];
5265 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5266 FMaxAmmo[i] := SavedState.MaxAmmo[i];
5267 FRulez := SavedState.Rulez;
5269 if gGameSettings.GameType = GT_SERVER then
5270 MH_SEND_PlayerStats(FUID);
5271 end;
5273 procedure TPlayer.SaveState (st: TStream);
5274 var
5275 i: Integer;
5276 b: Byte;
5277 begin
5278 // Сигнатура игрока
5279 utils.writeSign(st, 'PLYR');
5280 utils.writeInt(st, Byte(PLR_SAVE_VERSION)); // version
5281 // Бот или человек
5282 utils.writeBool(st, FIamBot);
5283 // UID игрока
5284 utils.writeInt(st, Word(FUID));
5285 // Имя игрока
5286 utils.writeStr(st, FName);
5287 // Команда
5288 utils.writeInt(st, Byte(FTeam));
5289 // Жив ли
5290 utils.writeBool(st, FAlive);
5291 // Израсходовал ли все жизни
5292 utils.writeBool(st, FNoRespawn);
5293 // Направление
5294 if FDirection = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
5295 utils.writeInt(st, Byte(b));
5296 // Здоровье
5297 utils.writeInt(st, LongInt(FHealth));
5298 // Коэффициент инвалидности
5299 utils.writeInt(st, LongInt(FHandicap));
5300 // Жизни
5301 utils.writeInt(st, Byte(FLives));
5302 // Броня
5303 utils.writeInt(st, LongInt(FArmor));
5304 // Запас воздуха
5305 utils.writeInt(st, LongInt(FAir));
5306 // Запас горючего
5307 utils.writeInt(st, LongInt(FJetFuel));
5308 // Боль
5309 utils.writeInt(st, LongInt(FPain));
5310 // Убил
5311 utils.writeInt(st, LongInt(FKills));
5312 // Убил монстров
5313 utils.writeInt(st, LongInt(FMonsterKills));
5314 // Фрагов
5315 utils.writeInt(st, LongInt(FFrags));
5316 // Фрагов подряд
5317 utils.writeInt(st, Byte(FFragCombo));
5318 // Время последнего фрага
5319 utils.writeInt(st, LongWord(FLastFrag));
5320 // Смертей
5321 utils.writeInt(st, LongInt(FDeath));
5322 // Какой флаг несет
5323 utils.writeInt(st, Byte(FFlag));
5324 // Нашел секретов
5325 utils.writeInt(st, LongInt(FSecrets));
5326 // Текущее оружие
5327 utils.writeInt(st, Byte(FCurrWeap));
5328 // Желаемое оружие
5329 utils.writeInt(st, Word(FNextWeap));
5330 // ...и пауза
5331 utils.writeInt(st, Byte(FNextWeapDelay));
5332 // Время зарядки BFG
5333 utils.writeInt(st, SmallInt(FBFGFireCounter));
5334 // Буфер урона
5335 utils.writeInt(st, LongInt(FDamageBuffer));
5336 // Последний ударивший
5337 utils.writeInt(st, Word(FLastSpawnerUID));
5338 // Тип последнего полученного урона
5339 utils.writeInt(st, Byte(FLastHit));
5340 // Объект игрока
5341 Obj_SaveState(st, @FObj);
5342 // Текущее количество патронов
5343 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FAmmo[i]));
5344 // Максимальное количество патронов
5345 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FMaxAmmo[i]));
5346 // Наличие оружия
5347 for i := WP_FIRST to WP_LAST do utils.writeBool(st, FWeapon[i]);
5348 // Время перезарядки оружия
5349 for i := WP_FIRST to WP_LAST do utils.writeInt(st, Word(FReloading[i]));
5350 // Наличие рюкзака
5351 utils.writeBool(st, (R_ITEM_BACKPACK in FRulez));
5352 // Наличие красного ключа
5353 utils.writeBool(st, (R_KEY_RED in FRulez));
5354 // Наличие зеленого ключа
5355 utils.writeBool(st, (R_KEY_GREEN in FRulez));
5356 // Наличие синего ключа
5357 utils.writeBool(st, (R_KEY_BLUE in FRulez));
5358 // Наличие берсерка
5359 utils.writeBool(st, (R_BERSERK in FRulez));
5360 // Время действия специальных предметов
5361 for i := MR_SUIT to MR_MAX do utils.writeInt(st, LongWord(FMegaRulez[i]));
5362 // Время до повторного респауна, смены оружия, исользования, захвата флага
5363 for i := T_RESPAWN to T_FLAGCAP do utils.writeInt(st, LongWord(FTime[i]));
5364 // Название модели
5365 utils.writeStr(st, FModel.GetName());
5366 // Цвет модели
5367 utils.writeInt(st, Byte(FColor.R));
5368 utils.writeInt(st, Byte(FColor.G));
5369 utils.writeInt(st, Byte(FColor.B));
5370 end;
5373 procedure TPlayer.LoadState (st: TStream);
5374 var
5375 i: Integer;
5376 str: String;
5377 b: Byte;
5378 begin
5379 assert(st <> nil);
5381 // Сигнатура игрока
5382 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
5383 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
5384 // Бот или человек:
5385 FIamBot := utils.readBool(st);
5386 // UID игрока
5387 FUID := utils.readWord(st);
5388 // Имя игрока
5389 str := utils.readStr(st);
5390 if (self <> gPlayer1) and (self <> gPlayer2) then FName := str;
5391 // Команда
5392 FTeam := utils.readByte(st);
5393 // Жив ли
5394 FAlive := utils.readBool(st);
5395 // Израсходовал ли все жизни
5396 FNoRespawn := utils.readBool(st);
5397 // Направление
5398 b := utils.readByte(st);
5399 if b = 1 then FDirection := TDirection.D_LEFT else FDirection := TDirection.D_RIGHT; // b = 2
5400 // Здоровье
5401 FHealth := utils.readLongInt(st);
5402 // Коэффициент инвалидности
5403 FHandicap := utils.readLongInt(st);
5404 // Жизни
5405 FLives := utils.readByte(st);
5406 // Броня
5407 FArmor := utils.readLongInt(st);
5408 // Запас воздуха
5409 FAir := utils.readLongInt(st);
5410 // Запас горючего
5411 FJetFuel := utils.readLongInt(st);
5412 // Боль
5413 FPain := utils.readLongInt(st);
5414 // Убил
5415 FKills := utils.readLongInt(st);
5416 // Убил монстров
5417 FMonsterKills := utils.readLongInt(st);
5418 // Фрагов
5419 FFrags := utils.readLongInt(st);
5420 // Фрагов подряд
5421 FFragCombo := utils.readByte(st);
5422 // Время последнего фрага
5423 FLastFrag := utils.readLongWord(st);
5424 // Смертей
5425 FDeath := utils.readLongInt(st);
5426 // Какой флаг несет
5427 FFlag := utils.readByte(st);
5428 // Нашел секретов
5429 FSecrets := utils.readLongInt(st);
5430 // Текущее оружие
5431 FCurrWeap := utils.readByte(st);
5432 // Желаемое оружие
5433 FNextWeap := utils.readWord(st);
5434 // ...и пауза
5435 FNextWeapDelay := utils.readByte(st);
5436 // Время зарядки BFG
5437 FBFGFireCounter := utils.readSmallInt(st);
5438 // Буфер урона
5439 FDamageBuffer := utils.readLongInt(st);
5440 // Последний ударивший
5441 FLastSpawnerUID := utils.readWord(st);
5442 // Тип последнего полученного урона
5443 FLastHit := utils.readByte(st);
5444 // Объект игрока
5445 Obj_LoadState(@FObj, st);
5446 // Текущее количество патронов
5447 for i := A_BULLETS to A_HIGH do FAmmo[i] := utils.readWord(st);
5448 // Максимальное количество патронов
5449 for i := A_BULLETS to A_HIGH do FMaxAmmo[i] := utils.readWord(st);
5450 // Наличие оружия
5451 for i := WP_FIRST to WP_LAST do FWeapon[i] := utils.readBool(st);
5452 // Время перезарядки оружия
5453 for i := WP_FIRST to WP_LAST do FReloading[i] := utils.readWord(st);
5454 // Наличие рюкзака
5455 if utils.readBool(st) then Include(FRulez, R_ITEM_BACKPACK);
5456 // Наличие красного ключа
5457 if utils.readBool(st) then Include(FRulez, R_KEY_RED);
5458 // Наличие зеленого ключа
5459 if utils.readBool(st) then Include(FRulez, R_KEY_GREEN);
5460 // Наличие синего ключа
5461 if utils.readBool(st) then Include(FRulez, R_KEY_BLUE);
5462 // Наличие берсерка
5463 if utils.readBool(st) then Include(FRulez, R_BERSERK);
5464 // Время действия специальных предметов
5465 for i := MR_SUIT to MR_MAX do FMegaRulez[i] := utils.readLongWord(st);
5466 // Время до повторного респауна, смены оружия, исользования, захвата флага
5467 for i := T_RESPAWN to T_FLAGCAP do FTime[i] := utils.readLongWord(st);
5468 // Название модели
5469 str := utils.readStr(st);
5470 // Цвет модели
5471 FColor.R := utils.readByte(st);
5472 FColor.G := utils.readByte(st);
5473 FColor.B := utils.readByte(st);
5474 if (self = gPlayer1) then
5475 begin
5476 str := gPlayer1Settings.Model;
5477 FColor := gPlayer1Settings.Color;
5478 end
5479 else if (self = gPlayer2) then
5480 begin
5481 str := gPlayer2Settings.Model;
5482 FColor := gPlayer2Settings.Color;
5483 end;
5484 // Обновляем модель игрока
5485 SetModel(str);
5486 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
5487 FModel.Color := TEAMCOLOR[FTeam]
5488 else
5489 FModel.Color := FColor;
5490 end;
5493 procedure TPlayer.AllRulez(Health: Boolean);
5494 var
5495 a: Integer;
5496 begin
5497 if Health then
5498 begin
5499 FHealth := PLAYER_HP_LIMIT;
5500 FArmor := PLAYER_AP_LIMIT;
5501 Exit;
5502 end;
5504 for a := WP_FIRST to WP_LAST do FWeapon[a] := True;
5505 for a := A_BULLETS to A_HIGH do FAmmo[a] := 30000;
5506 FRulez := FRulez+[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5507 end;
5509 procedure TPlayer.RestoreHealthArmor();
5510 begin
5511 FHealth := PLAYER_HP_LIMIT;
5512 FArmor := PLAYER_AP_LIMIT;
5513 end;
5515 procedure TPlayer.FragCombo();
5516 var
5517 Param: Integer;
5518 begin
5519 if (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) or g_Game_IsClient then
5520 Exit;
5521 if gTime - FLastFrag < FRAG_COMBO_TIME then
5522 begin
5523 if FFragCombo < 5 then
5524 Inc(FFragCombo);
5525 Param := FUID or (FFragCombo shl 16);
5526 if (FComboEvnt >= Low(gDelayedEvents)) and
5527 (FComboEvnt <= High(gDelayedEvents)) and
5528 gDelayedEvents[FComboEvnt].Pending and
5529 (gDelayedEvents[FComboEvnt].DEType = DE_KILLCOMBO) and
5530 (gDelayedEvents[FComboEvnt].DENum and $FFFF = FUID) then
5531 begin
5532 gDelayedEvents[FComboEvnt].Time := gTime + 500;
5533 gDelayedEvents[FComboEvnt].DENum := Param;
5534 end
5535 else
5536 FComboEvnt := g_Game_DelayEvent(DE_KILLCOMBO, 500, Param);
5537 end
5538 else
5539 FFragCombo := 1;
5541 FLastFrag := gTime;
5542 end;
5544 procedure TPlayer.GiveItem(ItemType: Byte);
5545 begin
5546 case ItemType of
5547 ITEM_SUIT:
5548 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
5549 begin
5550 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
5551 end;
5553 ITEM_OXYGEN:
5554 if FAir < AIR_MAX then
5555 begin
5556 FAir := AIR_MAX;
5557 end;
5559 ITEM_MEDKIT_BLACK:
5560 begin
5561 if not (R_BERSERK in FRulez) then
5562 begin
5563 Include(FRulez, R_BERSERK);
5564 if FBFGFireCounter < 1 then
5565 begin
5566 FCurrWeap := WEAPON_KASTET;
5567 resetWeaponQueue();
5568 FModel.SetWeapon(WEAPON_KASTET);
5569 end;
5570 if gFlash <> 0 then
5571 Inc(FPain, 100);
5572 FBerserk := gTime+30000;
5573 end;
5574 if FHealth < PLAYER_HP_SOFT then
5575 begin
5576 FHealth := PLAYER_HP_SOFT;
5577 FBerserk := gTime+30000;
5578 end;
5579 end;
5581 ITEM_INVUL:
5582 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
5583 begin
5584 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
5585 FSpawnInvul := 0;
5586 end;
5588 ITEM_INVIS:
5589 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
5590 begin
5591 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
5592 end;
5594 ITEM_JETPACK:
5595 if FJetFuel < JET_MAX then
5596 begin
5597 FJetFuel := JET_MAX;
5598 end;
5600 ITEM_MEDKIT_SMALL: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
5601 ITEM_MEDKIT_LARGE: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
5603 ITEM_ARMOR_GREEN: if FArmor < PLAYER_AP_SOFT then FArmor := PLAYER_AP_SOFT;
5604 ITEM_ARMOR_BLUE: if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5606 ITEM_SPHERE_BLUE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
5607 ITEM_SPHERE_WHITE:
5608 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) then
5609 begin
5610 if FHealth < PLAYER_HP_LIMIT then FHealth := PLAYER_HP_LIMIT;
5611 if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5612 end;
5614 ITEM_WEAPON_SAW: FWeapon[WEAPON_SAW] := True;
5615 ITEM_WEAPON_SHOTGUN1: FWeapon[WEAPON_SHOTGUN1] := True;
5616 ITEM_WEAPON_SHOTGUN2: FWeapon[WEAPON_SHOTGUN2] := True;
5617 ITEM_WEAPON_CHAINGUN: FWeapon[WEAPON_CHAINGUN] := True;
5618 ITEM_WEAPON_ROCKETLAUNCHER: FWeapon[WEAPON_ROCKETLAUNCHER] := True;
5619 ITEM_WEAPON_PLASMA: FWeapon[WEAPON_PLASMA] := True;
5620 ITEM_WEAPON_BFG: FWeapon[WEAPON_BFG] := True;
5621 ITEM_WEAPON_SUPERPULEMET: FWeapon[WEAPON_SUPERPULEMET] := True;
5622 ITEM_WEAPON_FLAMETHROWER: FWeapon[WEAPON_FLAMETHROWER] := True;
5624 ITEM_AMMO_BULLETS: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5625 ITEM_AMMO_BULLETS_BOX: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
5626 ITEM_AMMO_SHELLS: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5627 ITEM_AMMO_SHELLS_BOX: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
5628 ITEM_AMMO_ROCKET: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5629 ITEM_AMMO_ROCKET_BOX: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
5630 ITEM_AMMO_CELL: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5631 ITEM_AMMO_CELL_BIG: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
5632 ITEM_AMMO_FUELCAN: if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
5634 ITEM_AMMO_BACKPACK:
5635 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
5636 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
5637 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
5638 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
5639 (FMaxAmmo[A_FUEL] < AmmoLimits[1, A_FUEL]) then
5640 begin
5641 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
5642 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
5643 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
5644 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
5645 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
5647 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5648 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5649 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5650 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5652 FRulez := FRulez + [R_ITEM_BACKPACK];
5653 end;
5655 ITEM_KEY_RED: if not (R_KEY_RED in FRulez) then Include(FRulez, R_KEY_RED);
5656 ITEM_KEY_GREEN: if not (R_KEY_GREEN in FRulez) then Include(FRulez, R_KEY_GREEN);
5657 ITEM_KEY_BLUE: if not (R_KEY_BLUE in FRulez) then Include(FRulez, R_KEY_BLUE);
5659 ITEM_BOTTLE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
5660 ITEM_HELMET: if FArmor < PLAYER_AP_LIMIT then IncMax(FArmor, 5, PLAYER_AP_LIMIT);
5662 else
5663 Exit;
5664 end;
5665 if g_Game_IsNet and g_Game_IsServer then
5666 MH_SEND_PlayerStats(FUID);
5667 end;
5669 procedure TPlayer.FlySmoke(Times: DWORD = 1);
5670 var i: DWORD;
5671 begin
5672 if (Random(5) = 1) and (Times = 1) then
5673 Exit;
5675 if BodyInLiquid(0, 0) then
5676 begin
5677 g_GFX_Bubbles(Obj.X+Obj.Rect.X+(Obj.Rect.Width div 2)+Random(3)-1,
5678 Obj.Y+Obj.Rect.Height+8, 1, 8, 4);
5679 if Random(2) = 0 then
5680 g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
5681 else
5682 g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
5683 Exit;
5684 end;
5686 for i := 1 to Times do
5687 begin
5688 r_GFX_OnceAnim(
5689 R_GFX_SMOKE_TRANS,
5690 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_SMOKE_WIDTH div 2),
5691 Obj.Y+Obj.Rect.Height-4+Random(8+Times*2)
5692 );
5693 end;
5694 end;
5696 procedure TPlayer.OnFireFlame(Times: DWORD = 1);
5697 var i: DWORD;
5698 begin
5699 if (Random(10) = 1) and (Times = 1) then
5700 Exit;
5702 for i := 1 to Times do
5703 begin
5704 r_GFX_OnceAnim(
5705 R_GFX_FLAME,
5706 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_FLAME_WIDTH div 2),
5707 Obj.Y+8+Random(8+Times*2)
5708 );
5709 end;
5710 end;
5712 procedure TPlayer.PauseSounds(Enable: Boolean);
5713 begin
5714 FSawSound.Pause(Enable);
5715 FSawSoundIdle.Pause(Enable);
5716 FSawSoundHit.Pause(Enable);
5717 FSawSoundSelect.Pause(Enable);
5718 FFlameSoundOn.Pause(Enable);
5719 FFlameSoundOff.Pause(Enable);
5720 FFlameSoundWork.Pause(Enable);
5721 FJetSoundFly.Pause(Enable);
5722 FJetSoundOn.Pause(Enable);
5723 FJetSoundOff.Pause(Enable);
5724 end;
5726 { T C o r p s e : }
5728 constructor TCorpse.Create(X, Y: Integer; ModelName: String; aMess: Boolean);
5729 begin
5730 g_Obj_Init(@FObj);
5731 FObj.X := X;
5732 FObj.Y := Y;
5733 FObj.Rect := PLAYER_CORPSERECT;
5734 FModelName := ModelName;
5735 FMess := aMess;
5737 if FMess then
5738 begin
5739 FState := CORPSE_STATE_MESS;
5740 g_PlayerModel_GetAnim(ModelName, A_DIE2, FAnimation, FAnimationMask);
5741 end
5742 else
5743 begin
5744 FState := CORPSE_STATE_NORMAL;
5745 g_PlayerModel_GetAnim(ModelName, A_DIE1, FAnimation, FAnimationMask);
5746 end;
5747 end;
5749 destructor TCorpse.Destroy();
5750 begin
5751 FAnimation.Free();
5753 inherited;
5754 end;
5756 function TCorpse.ObjPtr (): PObj; inline; begin result := @FObj; end;
5758 procedure TCorpse.positionChanged (); inline; begin end;
5760 procedure TCorpse.moveBy (dx, dy: Integer); inline;
5761 begin
5762 if (dx <> 0) or (dy <> 0) then
5763 begin
5764 FObj.X += dx;
5765 FObj.Y += dy;
5766 positionChanged();
5767 end;
5768 end;
5771 procedure TCorpse.getMapBox (out x, y, w, h: Integer); inline;
5772 begin
5773 x := FObj.X+PLAYER_CORPSERECT.X;
5774 y := FObj.Y+PLAYER_CORPSERECT.Y;
5775 w := PLAYER_CORPSERECT.Width;
5776 h := PLAYER_CORPSERECT.Height;
5777 end;
5780 procedure TCorpse.Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
5781 var
5782 pm: TPlayerModel;
5783 Blood: TModelBlood;
5784 begin
5785 if FState = CORPSE_STATE_REMOVEME then
5786 Exit;
5788 FDamage := FDamage + Value;
5790 if FDamage > 150 then
5791 begin
5792 if FAnimation <> nil then
5793 begin
5794 FAnimation.Free();
5795 FAnimation := nil;
5797 FState := CORPSE_STATE_REMOVEME;
5799 g_Player_CreateGibs(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
5800 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
5801 FModelName, FColor);
5802 // Звук мяса от трупа:
5803 pm := g_PlayerModel_Get(FModelName);
5804 pm.PlaySound(MODELSOUND_DIE, 5, FObj.X, FObj.Y);
5805 pm.Free;
5807 // Зловещий смех:
5808 if (gBodyKillEvent <> -1)
5809 and gDelayedEvents[gBodyKillEvent].Pending then
5810 gDelayedEvents[gBodyKillEvent].Pending := False;
5811 gBodyKillEvent := g_Game_DelayEvent(DE_BODYKILL, 1050, SpawnerUID);
5812 end;
5813 end
5814 else
5815 begin
5816 Blood := g_PlayerModel_GetBlood(FModelName);
5817 FObj.Vel.X := FObj.Vel.X + vx;
5818 FObj.Vel.Y := FObj.Vel.Y + vy;
5819 g_GFX_Blood(FObj.X+PLAYER_CORPSERECT.X+(PLAYER_CORPSERECT.Width div 2),
5820 FObj.Y+PLAYER_CORPSERECT.Y+(PLAYER_CORPSERECT.Height div 2),
5821 Value, vx, vy, 16, (PLAYER_CORPSERECT.Height*2) div 3,
5822 Blood.R, Blood.G, Blood.B, Blood.Kind);
5823 end;
5824 end;
5826 procedure TCorpse.Update();
5827 var
5828 st: Word;
5829 begin
5830 if FState = CORPSE_STATE_REMOVEME then
5831 Exit;
5833 FObj.oldX := FObj.X;
5834 FObj.oldY := FObj.Y;
5836 if gTime mod (GAME_TICK*2) <> 0 then
5837 begin
5838 g_Obj_Move(@FObj, True, True, True);
5839 positionChanged(); // this updates spatial accelerators
5840 Exit;
5841 end;
5843 // Сопротивление воздуха для трупа:
5844 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
5846 st := g_Obj_Move(@FObj, True, True, True);
5847 positionChanged(); // this updates spatial accelerators
5849 if WordBool(st and MOVE_FALLOUT) then
5850 begin
5851 FState := CORPSE_STATE_REMOVEME;
5852 Exit;
5853 end;
5855 if FAnimation <> nil then
5856 FAnimation.Update();
5857 if FAnimationMask <> nil then
5858 FAnimationMask.Update();
5859 end;
5862 procedure TCorpse.SaveState (st: TStream);
5863 var
5864 anim: Boolean;
5865 begin
5866 assert(st <> nil);
5868 // Сигнатура трупа
5869 utils.writeSign(st, 'CORP');
5870 utils.writeInt(st, Byte(0));
5871 // Состояние
5872 utils.writeInt(st, Byte(FState));
5873 // Накопленный урон
5874 utils.writeInt(st, Byte(FDamage));
5875 // Цвет
5876 utils.writeInt(st, Byte(FColor.R));
5877 utils.writeInt(st, Byte(FColor.G));
5878 utils.writeInt(st, Byte(FColor.B));
5879 // Объект трупа
5880 Obj_SaveState(st, @FObj);
5881 utils.writeInt(st, Word(FPlayerUID));
5882 // Есть ли анимация
5883 anim := (FAnimation <> nil);
5884 utils.writeBool(st, anim);
5885 // Если есть - сохраняем
5886 if anim then FAnimation.SaveState(st);
5887 // Есть ли маска анимации
5888 anim := (FAnimationMask <> nil);
5889 utils.writeBool(st, anim);
5890 // Если есть - сохраняем
5891 if anim then FAnimationMask.SaveState(st);
5892 end;
5895 procedure TCorpse.LoadState (st: TStream);
5896 var
5897 anim: Boolean;
5898 begin
5899 assert(st <> nil);
5901 // Сигнатура трупа
5902 if not utils.checkSign(st, 'CORP') then raise XStreamError.Create('invalid corpse signature');
5903 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid corpse version');
5904 // Состояние
5905 FState := utils.readByte(st);
5906 // Накопленный урон
5907 FDamage := utils.readByte(st);
5908 // Цвет
5909 FColor.R := utils.readByte(st);
5910 FColor.G := utils.readByte(st);
5911 FColor.B := utils.readByte(st);
5912 // Объект трупа
5913 Obj_LoadState(@FObj, st);
5914 FPlayerUID := utils.readWord(st);
5915 // Есть ли анимация
5916 anim := utils.readBool(st);
5917 // Если есть - загружаем
5918 if anim then
5919 begin
5920 Assert(FAnimation <> nil, 'TCorpse.LoadState: no FAnimation');
5921 FAnimation.LoadState(st);
5922 end;
5923 // Есть ли маска анимации
5924 anim := utils.readBool(st);
5925 // Если есть - загружаем
5926 if anim then
5927 begin
5928 Assert(FAnimationMask <> nil, 'TCorpse.LoadState: no FAnimationMask');
5929 FAnimationMask.LoadState(st);
5930 end;
5931 end;
5933 { T B o t : }
5935 constructor TBot.Create();
5936 var
5937 a: Integer;
5938 begin
5939 inherited Create();
5941 FPhysics := True;
5942 FSpectator := False;
5943 FGhost := False;
5945 FIamBot := True;
5947 Inc(gNumBots);
5949 for a := WP_FIRST to WP_LAST do
5950 begin
5951 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
5952 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
5953 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
5954 end;
5955 end;
5957 destructor TBot.Destroy();
5958 begin
5959 Dec(gNumBots);
5960 inherited Destroy();
5961 end;
5963 procedure TBot.Respawn(Silent: Boolean; Force: Boolean = False);
5964 begin
5965 inherited Respawn(Silent, Force);
5967 FAIFlags := nil;
5968 FSelectedWeapon := FCurrWeap;
5969 resetWeaponQueue();
5970 FTargetUID := 0;
5971 end;
5973 procedure TBot.UpdateCombat();
5974 type
5975 TTarget = record
5976 UID: Word;
5977 X, Y: Integer;
5978 Rect: TRectWH;
5979 cX, cY: Integer;
5980 Dist: Word;
5981 Line: Boolean;
5982 Visible: Boolean;
5983 IsPlayer: Boolean;
5984 end;
5986 TTargetRecord = array of TTarget;
5988 function Compare(a, b: TTarget): Integer;
5989 begin
5990 if a.Line and not b.Line then // A на линии огня
5991 Result := -1
5992 else
5993 if not a.Line and b.Line then // B на линии огня
5994 Result := 1
5995 else // И A, и B на линии или не на линии огня
5996 if (a.Line and b.Line) or ((not a.Line) and (not b.Line)) then
5997 begin
5998 if a.Dist > b.Dist then // B ближе
5999 Result := 1
6000 else // A ближе или равноудаленно с B
6001 Result := -1;
6002 end
6003 else // Странно -> A
6004 Result := -1;
6005 end;
6007 var
6008 a, x1, y1, x2, y2: Integer;
6009 targets: TTargetRecord;
6010 ammo: Word;
6011 Target, BestTarget: TTarget;
6012 firew, fireh: Integer;
6013 angle: SmallInt;
6014 mon: TMonster;
6015 pla, tpla: TPlayer;
6016 vsPlayer, vsMonster, ok: Boolean;
6019 function monsUpdate (mon: TMonster): Boolean;
6020 begin
6021 result := false; // don't stop
6022 if mon.alive and (mon.MonsterType <> MONSTER_BARREL) then
6023 begin
6024 if not TargetOnScreen(mon.Obj.X+mon.Obj.Rect.X, mon.Obj.Y+mon.Obj.Rect.Y) then exit;
6026 x2 := mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2);
6027 y2 := mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2);
6029 // Если монстр на экране и не прикрыт стеной
6030 if g_TraceVector(x1, y1, x2, y2) then
6031 begin
6032 // Добавляем к списку возможных целей
6033 SetLength(targets, Length(targets)+1);
6034 with targets[High(targets)] do
6035 begin
6036 UID := mon.UID;
6037 X := mon.Obj.X;
6038 Y := mon.Obj.Y;
6039 cX := x2;
6040 cY := y2;
6041 Rect := mon.Obj.Rect;
6042 Dist := g_PatchLength(x1, y1, x2, y2);
6043 Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6044 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6045 Visible := True;
6046 IsPlayer := False;
6047 end;
6048 end;
6049 end;
6050 end;
6052 begin
6053 vsPlayer := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER);
6054 vsMonster := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER);
6056 // Если текущее оружие не то, что нужно, то меняем:
6057 if FCurrWeap <> FSelectedWeapon then
6058 NextWeapon();
6060 // Если нужно стрелять и нужное оружие, то нажать "Стрелять":
6061 if (GetAIFlag('NEEDFIRE') <> '') and (FCurrWeap = FSelectedWeapon) then
6062 begin
6063 RemoveAIFlag('NEEDFIRE');
6065 case FCurrWeap of
6066 WEAPON_PLASMA, WEAPON_SUPERPULEMET, WEAPON_CHAINGUN: PressKey(KEY_FIRE, 20);
6067 WEAPON_SAW, WEAPON_KASTET, WEAPON_FLAMETHROWER: PressKey(KEY_FIRE, 40);
6068 else PressKey(KEY_FIRE);
6069 end;
6070 end;
6072 // Координаты ствола:
6073 x1 := FObj.X + WEAPONPOINT[FDirection].X;
6074 y1 := FObj.Y + WEAPONPOINT[FDirection].Y;
6076 Target.UID := FTargetUID;
6078 ok := False;
6079 if Target.UID <> 0 then
6080 begin // Цель есть - настраиваем
6081 if (g_GetUIDType(Target.UID) = UID_PLAYER) and
6082 vsPlayer then
6083 begin // Игрок
6084 tpla := g_Player_Get(Target.UID);
6085 if tpla <> nil then
6086 with tpla do
6087 begin
6088 if (@FObj) <> nil then
6089 begin
6090 Target.X := FObj.X;
6091 Target.Y := FObj.Y;
6092 end;
6093 end;
6095 Target.cX := Target.X + PLAYER_RECT_CX;
6096 Target.cY := Target.Y + PLAYER_RECT_CY;
6097 Target.Rect := PLAYER_RECT;
6098 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6099 Target.Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6100 (y1-4 > Target.Y+PLAYER_RECT.Y);
6101 Target.IsPlayer := True;
6102 ok := True;
6103 end
6104 else
6105 if (g_GetUIDType(Target.UID) = UID_MONSTER) and
6106 vsMonster then
6107 begin // Монстр
6108 mon := g_Monsters_ByUID(Target.UID);
6109 if mon <> nil then
6110 begin
6111 Target.X := mon.Obj.X;
6112 Target.Y := mon.Obj.Y;
6114 Target.cX := Target.X + mon.Obj.Rect.X + (mon.Obj.Rect.Width div 2);
6115 Target.cY := Target.Y + mon.Obj.Rect.Y + (mon.Obj.Rect.Height div 2);
6116 Target.Rect := mon.Obj.Rect;
6117 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6118 Target.Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6119 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6120 Target.IsPlayer := False;
6121 ok := True;
6122 end;
6123 end;
6124 end;
6126 if not ok then
6127 begin // Цели нет - обнуляем
6128 Target.X := 0;
6129 Target.Y := 0;
6130 Target.cX := 0;
6131 Target.cY := 0;
6132 Target.Visible := False;
6133 Target.Line := False;
6134 Target.IsPlayer := False;
6135 end;
6137 targets := nil;
6139 // Если цель не видима или не на линии огня, то ищем все возможные цели:
6140 if (not Target.Line) or (not Target.Visible) then
6141 begin
6142 // Игроки:
6143 if vsPlayer then
6144 for a := 0 to High(gPlayers) do
6145 if (gPlayers[a] <> nil) and (gPlayers[a].alive) and
6146 (gPlayers[a].FUID <> FUID) and
6147 (not SameTeam(FUID, gPlayers[a].FUID)) and
6148 (not gPlayers[a].NoTarget) and
6149 (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
6150 begin
6151 if not TargetOnScreen(gPlayers[a].FObj.X + PLAYER_RECT.X,
6152 gPlayers[a].FObj.Y + PLAYER_RECT.Y) then
6153 Continue;
6155 x2 := gPlayers[a].FObj.X + PLAYER_RECT_CX;
6156 y2 := gPlayers[a].FObj.Y + PLAYER_RECT_CY;
6158 // Если игрок на экране и не прикрыт стеной:
6159 if g_TraceVector(x1, y1, x2, y2) then
6160 begin
6161 // Добавляем к списку возможных целей:
6162 SetLength(targets, Length(targets)+1);
6163 with targets[High(targets)] do
6164 begin
6165 UID := gPlayers[a].FUID;
6166 X := gPlayers[a].FObj.X;
6167 Y := gPlayers[a].FObj.Y;
6168 cX := x2;
6169 cY := y2;
6170 Rect := PLAYER_RECT;
6171 Dist := g_PatchLength(x1, y1, x2, y2);
6172 Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6173 (y1-4 > Target.Y+PLAYER_RECT.Y);
6174 Visible := True;
6175 IsPlayer := True;
6176 end;
6177 end;
6178 end;
6180 // Монстры:
6181 if vsMonster then g_Mons_ForEach(monsUpdate);
6182 end;
6184 // Если есть возможные цели:
6185 // (Выбираем лучшую, меняем оружие и бежим к ней/от нее)
6186 if targets <> nil then
6187 begin
6188 // Выбираем наилучшую цель:
6189 BestTarget := targets[0];
6190 if Length(targets) > 1 then
6191 for a := 1 to High(targets) do
6192 if Compare(BestTarget, targets[a]) = 1 then
6193 BestTarget := targets[a];
6195 // Если лучшая цель "виднее" текущей, то текущая := лучшая:
6196 if ((not Target.Visible) and BestTarget.Visible and (Target.UID <> BestTarget.UID)) or
6197 ((not Target.Line) and BestTarget.Line and BestTarget.Visible) then
6198 begin
6199 Target := BestTarget;
6201 if (Healthy() = 3) or ((Healthy() = 2)) then
6202 begin // Если здоровы - догоняем
6203 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6204 SetAIFlag('GORIGHT', '1');
6205 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6206 SetAIFlag('GOLEFT', '1');
6207 end
6208 else
6209 begin // Если побиты - убегаем
6210 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6211 SetAIFlag('GORIGHT', '1');
6212 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6213 SetAIFlag('GOLEFT', '1');
6214 end;
6216 // Выбираем оружие на основе расстояния и приоритетов:
6217 SelectWeapon(Abs(x1-Target.cX));
6218 end;
6219 end;
6221 // Если есть цель:
6222 // (Догоняем/убегаем, стреляем по направлению к цели)
6223 // (Если цель далеко, то хватит следить за ней)
6224 if Target.UID <> 0 then
6225 begin
6226 if not TargetOnScreen(Target.X + Target.Rect.X,
6227 Target.Y + Target.Rect.Y) then
6228 begin // Цель сбежала с "экрана"
6229 if (Healthy() = 3) or ((Healthy() = 2)) then
6230 begin // Если здоровы - догоняем
6231 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6232 SetAIFlag('GORIGHT', '1');
6233 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6234 SetAIFlag('GOLEFT', '1');
6235 end
6236 else
6237 begin // Если побиты - забываем о цели и убегаем
6238 Target.UID := 0;
6239 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6240 SetAIFlag('GORIGHT', '1');
6241 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6242 SetAIFlag('GOLEFT', '1');
6243 end;
6244 end
6245 else
6246 begin // Цель пока на "экране"
6247 // Если цель не загорожена стеной, то отмечаем, когда ее видели:
6248 if g_TraceVector(x1, y1, Target.cX, Target.cY) then
6249 FLastVisible := gTime;
6250 // Если разница высот не велика, то догоняем:
6251 if (Abs(FObj.Y-Target.Y) <= 128) then
6252 begin
6253 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6254 SetAIFlag('GORIGHT', '1');
6255 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6256 SetAIFlag('GOLEFT', '1');
6257 end;
6258 end;
6260 // Выбираем угол вверх:
6261 if FDirection = TDirection.D_LEFT then
6262 angle := ANGLE_LEFTUP
6263 else
6264 angle := ANGLE_RIGHTUP;
6266 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6267 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6269 // Если при угле вверх можно попасть в приблизительное положение цели:
6270 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6271 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128), //96
6272 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6273 Target.Rect.Width, Target.Rect.Height) and
6274 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6275 begin // то нужно стрелять вверх
6276 SetAIFlag('NEEDFIRE', '1');
6277 SetAIFlag('NEEDSEEUP', '1');
6278 end;
6280 // Выбираем угол вниз:
6281 if FDirection = TDirection.D_LEFT then
6282 angle := ANGLE_LEFTDOWN
6283 else
6284 angle := ANGLE_RIGHTDOWN;
6286 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6287 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6289 // Если при угле вниз можно попасть в приблизительное положение цели:
6290 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6291 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6292 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6293 Target.Rect.Width, Target.Rect.Height) and
6294 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6295 begin // то нужно стрелять вниз
6296 SetAIFlag('NEEDFIRE', '1');
6297 SetAIFlag('NEEDSEEDOWN', '1');
6298 end;
6300 // Если цель видно и она на такой же высоте:
6301 if Target.Visible and
6302 (y1+4 < Target.Y+Target.Rect.Y+Target.Rect.Height) and
6303 (y1-4 > Target.Y+Target.Rect.Y) then
6304 begin
6305 // Если идем в сторону цели, то надо стрелять:
6306 if ((FDirection = TDirection.D_LEFT) and (Target.X < FObj.X)) or
6307 ((FDirection = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6308 begin // то нужно стрелять вперед
6309 SetAIFlag('NEEDFIRE', '1');
6310 SetAIFlag('NEEDSEEDOWN', '');
6311 SetAIFlag('NEEDSEEUP', '');
6312 end;
6313 // Если цель в пределах "экрана" и сложность позволяет прыжки сближения:
6314 if Abs(FObj.X-Target.X) < Trunc(gPlayerScreenSize.X*0.75) then
6315 if GetRnd(FDifficult.CloseJump) then
6316 begin // то если повезет - прыгаем (особенно, если близко)
6317 if Abs(FObj.X-Target.X) < 128 then
6318 a := 4
6319 else
6320 a := 30;
6321 if Random(a) = 0 then
6322 SetAIFlag('NEEDJUMP', '1');
6323 end;
6324 end;
6326 // Если цель все еще есть:
6327 if Target.UID <> 0 then
6328 if gTime-FLastVisible > 2000 then // Если видели давно
6329 Target.UID := 0 // то забыть цель
6330 else // Если видели недавно
6331 begin // но цель убили
6332 if Target.IsPlayer then
6333 begin // Цель - игрок
6334 pla := g_Player_Get(Target.UID);
6335 if (pla = nil) or (not pla.alive) or pla.NoTarget or
6336 (pla.FMegaRulez[MR_INVIS] >= gTime) then
6337 Target.UID := 0; // то забыть цель
6338 end
6339 else
6340 begin // Цель - монстр
6341 mon := g_Monsters_ByUID(Target.UID);
6342 if (mon = nil) or (not mon.alive) then
6343 Target.UID := 0; // то забыть цель
6344 end;
6345 end;
6346 end; // if Target.UID <> 0
6348 FTargetUID := Target.UID;
6350 // Если возможных целей нет:
6351 // (Атака чего-нибудь слева или справа)
6352 if targets = nil then
6353 if GetAIFlag('ATTACKLEFT') <> '' then
6354 begin // Если нужно атаковать налево
6355 RemoveAIFlag('ATTACKLEFT');
6357 SetAIFlag('NEEDJUMP', '1');
6359 if RunDirection() = TDirection.D_RIGHT then
6360 begin // Идем не в ту сторону
6361 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6362 begin // Если здоровы, то, возможно, стреляем бежим влево и стреляем
6363 SetAIFlag('NEEDFIRE', '1');
6364 SetAIFlag('GOLEFT', '1');
6365 end;
6366 end
6367 else
6368 begin // Идем в нужную сторону
6369 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6370 SetAIFlag('NEEDFIRE', '1');
6371 if Healthy() <= 1 then // Побиты - убегаем
6372 SetAIFlag('GORIGHT', '1');
6373 end;
6374 end
6375 else
6376 if GetAIFlag('ATTACKRIGHT') <> '' then
6377 begin // Если нужно атаковать направо
6378 RemoveAIFlag('ATTACKRIGHT');
6380 SetAIFlag('NEEDJUMP', '1');
6382 if RunDirection() = TDirection.D_LEFT then
6383 begin // Идем не в ту сторону
6384 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6385 begin // Если здоровы, то, возможно, бежим вправо и стреляем
6386 SetAIFlag('NEEDFIRE', '1');
6387 SetAIFlag('GORIGHT', '1');
6388 end;
6389 end
6390 else
6391 begin
6392 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6393 SetAIFlag('NEEDFIRE', '1');
6394 if Healthy() <= 1 then // Побиты - убегаем
6395 SetAIFlag('GOLEFT', '1');
6396 end;
6397 end;
6399 //HACK! (does it belongs there?)
6400 RealizeCurrentWeapon();
6402 // Если есть возможные цели:
6403 // (Стреляем по направлению к целям)
6404 if (targets <> nil) and (GetAIFlag('NEEDFIRE') <> '') then
6405 for a := 0 to High(targets) do
6406 begin
6407 // Если можем стрелять по диагонали:
6408 if GetRnd(FDifficult.DiagFire) then
6409 begin
6410 // Ищем цель сверху и стреляем, если есть:
6411 if FDirection = TDirection.D_LEFT then
6412 angle := ANGLE_LEFTUP
6413 else
6414 angle := ANGLE_RIGHTUP;
6416 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6417 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6419 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6420 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6421 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6422 targets[a].Rect.Width, targets[a].Rect.Height) and
6423 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6424 begin
6425 SetAIFlag('NEEDFIRE', '1');
6426 SetAIFlag('NEEDSEEUP', '1');
6427 end;
6429 // Ищем цель снизу и стреляем, если есть:
6430 if FDirection = TDirection.D_LEFT then
6431 angle := ANGLE_LEFTDOWN
6432 else
6433 angle := ANGLE_RIGHTDOWN;
6435 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6436 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6438 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6439 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6440 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6441 targets[a].Rect.Width, targets[a].Rect.Height) and
6442 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6443 begin
6444 SetAIFlag('NEEDFIRE', '1');
6445 SetAIFlag('NEEDSEEDOWN', '1');
6446 end;
6447 end;
6449 // Если цель "перед носом", то стреляем:
6450 if targets[a].Line and targets[a].Visible and
6451 (((FDirection = TDirection.D_LEFT) and (targets[a].X < FObj.X)) or
6452 ((FDirection = TDirection.D_RIGHT) and (targets[a].X > FObj.X))) then
6453 begin
6454 SetAIFlag('NEEDFIRE', '1');
6455 Break;
6456 end;
6457 end;
6459 // Если летит пуля, то, возможно, подпрыгиваем:
6460 if g_Weapon_Danger(FUID, FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y,
6461 PLAYER_RECT.Width, PLAYER_RECT.Height,
6462 40+GetInterval(FDifficult.Cover, 40)) then
6463 SetAIFlag('NEEDJUMP', '1');
6465 // Если кончились паторны, то нужно сменить оружие:
6466 ammo := GetAmmoByWeapon(FCurrWeap);
6467 if ((FCurrWeap = WEAPON_SHOTGUN2) and (ammo < 2)) or
6468 ((FCurrWeap = WEAPON_BFG) and (ammo < 40)) or
6469 (ammo = 0) then
6470 SetAIFlag('SELECTWEAPON', '1');
6472 // Если нужно сменить оружие, то выбираем нужное:
6473 if GetAIFlag('SELECTWEAPON') = '1' then
6474 begin
6475 SelectWeapon(-1);
6476 RemoveAIFlag('SELECTWEAPON');
6477 end;
6478 end;
6480 procedure TBot.Update();
6481 var
6482 EnableAI: Boolean;
6483 begin
6484 if not FAlive then
6485 begin // Respawn
6486 ReleaseKeys();
6487 PressKey(KEY_UP);
6488 end
6489 else
6490 begin
6491 EnableAI := True;
6493 // Проверяем, отключён ли AI ботов
6494 if (g_debug_BotAIOff = 1) and (Team = TEAM_RED) then
6495 EnableAI := False;
6496 if (g_debug_BotAIOff = 2) and (Team = TEAM_BLUE) then
6497 EnableAI := False;
6498 if g_debug_BotAIOff = 3 then
6499 EnableAI := False;
6501 if EnableAI then
6502 begin
6503 UpdateMove();
6504 UpdateCombat();
6505 end
6506 else
6507 begin
6508 RealizeCurrentWeapon();
6509 end;
6510 end;
6512 inherited Update();
6513 end;
6515 procedure TBot.ReleaseKey(Key: Byte);
6516 begin
6517 with FKeys[Key] do
6518 begin
6519 Pressed := False;
6520 Time := 0;
6521 end;
6522 end;
6524 function TBot.KeyPressed(Key: Word): Boolean;
6525 begin
6526 Result := FKeys[Key].Pressed;
6527 end;
6529 function TBot.GetAIFlag(aName: String20): String20;
6530 var
6531 a: Integer;
6532 begin
6533 Result := '';
6535 aName := LowerCase(aName);
6537 if FAIFlags <> nil then
6538 for a := 0 to High(FAIFlags) do
6539 if LowerCase(FAIFlags[a].Name) = aName then
6540 begin
6541 Result := FAIFlags[a].Value;
6542 Break;
6543 end;
6544 end;
6546 procedure TBot.RemoveAIFlag(aName: String20);
6547 var
6548 a, b: Integer;
6549 begin
6550 if FAIFlags = nil then Exit;
6552 aName := LowerCase(aName);
6554 for a := 0 to High(FAIFlags) do
6555 if LowerCase(FAIFlags[a].Name) = aName then
6556 begin
6557 if a <> High(FAIFlags) then
6558 for b := a to High(FAIFlags)-1 do
6559 FAIFlags[b] := FAIFlags[b+1];
6561 SetLength(FAIFlags, Length(FAIFlags)-1);
6562 Break;
6563 end;
6564 end;
6566 procedure TBot.SetAIFlag(aName, fValue: String20);
6567 var
6568 a: Integer;
6569 ok: Boolean;
6570 begin
6571 a := 0;
6572 ok := False;
6574 aName := LowerCase(aName);
6576 if FAIFlags <> nil then
6577 for a := 0 to High(FAIFlags) do
6578 if LowerCase(FAIFlags[a].Name) = aName then
6579 begin
6580 ok := True;
6581 Break;
6582 end;
6584 if ok then FAIFlags[a].Value := fValue
6585 else
6586 begin
6587 SetLength(FAIFlags, Length(FAIFlags)+1);
6588 with FAIFlags[High(FAIFlags)] do
6589 begin
6590 Name := aName;
6591 Value := fValue;
6592 end;
6593 end;
6594 end;
6596 procedure TBot.UpdateMove;
6598 procedure GoLeft(Time: Word = 1);
6599 begin
6600 ReleaseKey(KEY_LEFT);
6601 ReleaseKey(KEY_RIGHT);
6602 PressKey(KEY_LEFT, Time);
6603 SetDirection(TDirection.D_LEFT);
6604 end;
6606 procedure GoRight(Time: Word = 1);
6607 begin
6608 ReleaseKey(KEY_LEFT);
6609 ReleaseKey(KEY_RIGHT);
6610 PressKey(KEY_RIGHT, Time);
6611 SetDirection(TDirection.D_RIGHT);
6612 end;
6614 function Rnd(a: Word): Boolean;
6615 begin
6616 Result := Random(a) = 0;
6617 end;
6619 procedure Turn(Time: Word = 1200);
6620 begin
6621 if RunDirection() = TDirection.D_LEFT then GoRight(Time) else GoLeft(Time);
6622 end;
6624 procedure Stop();
6625 begin
6626 ReleaseKey(KEY_LEFT);
6627 ReleaseKey(KEY_RIGHT);
6628 end;
6630 function CanRunLeft(): Boolean;
6631 begin
6632 Result := not CollideLevel(-1, 0);
6633 end;
6635 function CanRunRight(): Boolean;
6636 begin
6637 Result := not CollideLevel(1, 0);
6638 end;
6640 function CanRun(): Boolean;
6641 begin
6642 if RunDirection() = TDirection.D_LEFT then Result := CanRunLeft() else Result := CanRunRight();
6643 end;
6645 procedure Jump(Time: Word = 30);
6646 begin
6647 PressKey(KEY_JUMP, Time);
6648 end;
6650 function NearHole(): Boolean;
6651 var
6652 x, sx: Integer;
6653 begin
6654 { TODO 5 : Лестницы }
6655 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6656 for x := 1 to PLAYER_RECT.Width do
6657 if (not StayOnStep(x*sx, 0)) and
6658 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6659 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6660 begin
6661 Result := True;
6662 Exit;
6663 end;
6665 Result := False;
6666 end;
6668 function BorderHole(): Boolean;
6669 var
6670 x, sx, xx: Integer;
6671 begin
6672 { TODO 5 : Лестницы }
6673 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6674 for x := 1 to PLAYER_RECT.Width do
6675 if (not StayOnStep(x*sx, 0)) and
6676 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6677 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6678 begin
6679 for xx := x to x+32 do
6680 if CollideLevel(xx*sx, PLAYER_RECT.Height) then
6681 begin
6682 Result := True;
6683 Exit;
6684 end;
6685 end;
6687 Result := False;
6688 end;
6690 function NearDeepHole(): Boolean;
6691 var
6692 x, sx, y: Integer;
6693 begin
6694 Result := False;
6696 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6697 y := 3;
6699 for x := 1 to PLAYER_RECT.Width do
6700 if (not StayOnStep(x*sx, 0)) and
6701 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6702 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6703 begin
6704 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6705 begin
6706 if CollideLevel(x*sx, PLAYER_RECT.Height*y) then Exit;
6707 y := y+1;
6708 end;
6710 Result := True;
6711 end else Result := False;
6712 end;
6714 function OverDeepHole(): Boolean;
6715 var
6716 y: Integer;
6717 begin
6718 Result := False;
6720 y := 1;
6721 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6722 begin
6723 if CollideLevel(0, PLAYER_RECT.Height*y) then Exit;
6724 y := y+1;
6725 end;
6727 Result := True;
6728 end;
6730 function OnGround(): Boolean;
6731 begin
6732 Result := StayOnStep(0, 0) or CollideLevel(0, 1);
6733 end;
6735 function OnLadder(): Boolean;
6736 begin
6737 Result := FullInStep(0, 0);
6738 end;
6740 function BelowLadder(): Boolean;
6741 begin
6742 Result := (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) and
6743 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6744 (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) and
6745 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6746 end;
6748 function BelowLiftUp(): Boolean;
6749 begin
6750 Result := ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) = -1) and
6751 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6752 ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) = -1) and
6753 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6754 end;
6756 function OnTopLift(): Boolean;
6757 begin
6758 Result := (FullInLift(0, 0) = -1) and (FullInLift(0, -32) = 0);
6759 end;
6761 function CanJumpOver(): Boolean;
6762 var
6763 sx, y: Integer;
6764 begin
6765 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6767 Result := False;
6769 if not CollideLevel(sx, 0) then Exit;
6771 for y := 1 to BOT_MAXJUMP do
6772 if CollideLevel(0, -y) then Exit else
6773 if not CollideLevel(sx, -y) then
6774 begin
6775 Result := True;
6776 Exit;
6777 end;
6778 end;
6780 function CanJumpUp(Dist: ShortInt): Boolean;
6781 var
6782 y, yy: Integer;
6783 c: Boolean;
6784 begin
6785 Result := False;
6787 if CollideLevel(Dist, 0) then Exit;
6789 c := False;
6790 for y := 0 to BOT_MAXJUMP do
6791 if CollideLevel(Dist, -y) then
6792 begin
6793 c := True;
6794 Break;
6795 end;
6797 if not c then Exit;
6799 c := False;
6800 for yy := y+1 to BOT_MAXJUMP do
6801 if not CollideLevel(Dist, -yy) then
6802 begin
6803 c := True;
6804 Break;
6805 end;
6807 if not c then Exit;
6809 c := False;
6810 for y := 0 to BOT_MAXJUMP do
6811 if CollideLevel(0, -y) then
6812 begin
6813 c := True;
6814 Break;
6815 end;
6817 if c then Exit;
6819 if y < yy then Exit;
6821 Result := True;
6822 end;
6824 function IsSafeTrigger(): Boolean;
6825 var
6826 a: Integer;
6827 begin
6828 Result := True;
6829 if gTriggers = nil then
6830 Exit;
6831 for a := 0 to High(gTriggers) do
6832 if Collide(gTriggers[a].X,
6833 gTriggers[a].Y,
6834 gTriggers[a].Width,
6835 gTriggers[a].Height) and
6836 (gTriggers[a].TriggerType in [TRIGGER_EXIT, TRIGGER_CLOSEDOOR,
6837 TRIGGER_CLOSETRAP, TRIGGER_TRAP,
6838 TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF,
6839 TRIGGER_ONOFF, TRIGGER_SPAWNMONSTER,
6840 TRIGGER_DAMAGE, TRIGGER_SHOT]) then
6841 Result := False;
6842 end;
6844 begin
6845 // Возможно, нажимаем кнопку:
6846 if Rnd(16) and IsSafeTrigger() then
6847 PressKey(KEY_OPEN);
6849 // Если под лифтом или ступеньками, то, возможно, прыгаем:
6850 if OnLadder() or ((BelowLadder() or BelowLiftUp()) and Rnd(8)) then
6851 begin
6852 ReleaseKey(KEY_LEFT);
6853 ReleaseKey(KEY_RIGHT);
6854 Jump();
6855 end;
6857 // Идем влево, если надо было:
6858 if GetAIFlag('GOLEFT') <> '' then
6859 begin
6860 RemoveAIFlag('GOLEFT');
6861 if CanRunLeft() then
6862 GoLeft(360);
6863 end;
6865 // Идем вправо, если надо было:
6866 if GetAIFlag('GORIGHT') <> '' then
6867 begin
6868 RemoveAIFlag('GORIGHT');
6869 if CanRunRight() then
6870 GoRight(360);
6871 end;
6873 // Если вылетели за карту, то пробуем вернуться:
6874 if FObj.X < -32 then
6875 GoRight(360)
6876 else
6877 if FObj.X+32 > gMapInfo.Width then
6878 GoLeft(360);
6880 // Прыгаем, если надо было:
6881 if GetAIFlag('NEEDJUMP') <> '' then
6882 begin
6883 Jump(0);
6884 RemoveAIFlag('NEEDJUMP');
6885 end;
6887 // Смотрим вверх, если надо было:
6888 if GetAIFlag('NEEDSEEUP') <> '' then
6889 begin
6890 ReleaseKey(KEY_UP);
6891 ReleaseKey(KEY_DOWN);
6892 PressKey(KEY_UP, 20);
6893 RemoveAIFlag('NEEDSEEUP');
6894 end;
6896 // Смотрим вниз, если надо было:
6897 if GetAIFlag('NEEDSEEDOWN') <> '' then
6898 begin
6899 ReleaseKey(KEY_UP);
6900 ReleaseKey(KEY_DOWN);
6901 PressKey(KEY_DOWN, 20);
6902 RemoveAIFlag('NEEDSEEDOWN');
6903 end;
6905 // Если нужно было в дыру и мы не на земле, то покорно летим:
6906 if GetAIFlag('GOINHOLE') <> '' then
6907 if not OnGround() then
6908 begin
6909 ReleaseKey(KEY_LEFT);
6910 ReleaseKey(KEY_RIGHT);
6911 RemoveAIFlag('GOINHOLE');
6912 SetAIFlag('FALLINHOLE', '1');
6913 end;
6915 // Если падали и достигли земли, то хватит падать:
6916 if GetAIFlag('FALLINHOLE') <> '' then
6917 if OnGround() then
6918 RemoveAIFlag('FALLINHOLE');
6920 // Если летели прямо и сейчас не на лестнице или на вершине лифта, то отходим в сторону:
6921 if not (KeyPressed(KEY_LEFT) or KeyPressed(KEY_RIGHT)) then
6922 if GetAIFlag('FALLINHOLE') = '' then
6923 if (not OnLadder()) or (FObj.Vel.Y >= 0) or (OnTopLift()) then
6924 if Rnd(2) then
6925 GoLeft(360)
6926 else
6927 GoRight(360);
6929 // Если на земле и можно подпрыгнуть, то, возможно, прыгаем:
6930 if OnGround() and
6931 CanJumpUp(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*32) and
6932 Rnd(8) then
6933 Jump();
6935 // Если на земле и возле дыры (глубина > 2 ростов игрока):
6936 if OnGround() and NearHole() then
6937 if NearDeepHole() then // Если это бездна
6938 case Random(6) of
6939 0..3: Turn(); // Бежим обратно
6940 4: Jump(); // Прыгаем
6941 5: begin // Прыгаем обратно
6942 Turn();
6943 Jump();
6944 end;
6945 end
6946 else // Это не бездна и мы еще не летим туда
6947 if GetAIFlag('GOINHOLE') = '' then
6948 case Random(6) of
6949 0: Turn(); // Не нужно туда
6950 1: Jump(); // Вдруг повезет - прыгаем
6951 else // Если яма с границей, то при случае можно туда прыгнуть
6952 if BorderHole() then
6953 SetAIFlag('GOINHOLE', '1');
6954 end;
6956 // Если на земле, но некуда идти:
6957 if (not CanRun()) and OnGround() then
6958 begin
6959 // Если мы на лестнице или можно перепрыгнуть, то прыгаем:
6960 if CanJumpOver() or OnLadder() then
6961 Jump()
6962 else // иначе попытаемся в другую сторону
6963 if Random(2) = 0 then
6964 begin
6965 if IsSafeTrigger() then
6966 PressKey(KEY_OPEN);
6967 end else
6968 Turn();
6969 end;
6971 // Осталось мало воздуха:
6972 if FAir < 36 * 2 then
6973 Jump(20);
6975 // Выбираемся из кислоты, если нет костюма, обожглись, или мало здоровья:
6976 if (FMegaRulez[MR_SUIT] < gTime) and ((FLastHit = HIT_ACID) or (Healthy() <= 1)) then
6977 if BodyInAcid(0, 0) then
6978 Jump();
6979 end;
6981 function TBot.FullInStep(XInc, YInc: Integer): Boolean;
6982 begin
6983 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
6984 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_STEP, False);
6985 end;
6987 {function TBot.NeedItem(Item: Byte): Byte;
6988 begin
6989 Result := 4;
6990 end;}
6992 procedure TBot.SelectWeapon(Dist: Integer);
6993 var
6994 a: Integer;
6996 function HaveAmmo(weapon: Byte): Boolean;
6997 begin
6998 case weapon of
6999 WEAPON_PISTOL: Result := FAmmo[A_BULLETS] >= 1;
7000 WEAPON_SHOTGUN1: Result := FAmmo[A_SHELLS] >= 1;
7001 WEAPON_SHOTGUN2: Result := FAmmo[A_SHELLS] >= 2;
7002 WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS] >= 10;
7003 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS] >= 1;
7004 WEAPON_PLASMA: Result := FAmmo[A_CELLS] >= 10;
7005 WEAPON_BFG: Result := FAmmo[A_CELLS] >= 40;
7006 WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS] >= 1;
7007 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL] >= 1;
7008 else Result := True;
7009 end;
7010 end;
7012 begin
7013 if Dist = -1 then Dist := BOT_LONGDIST;
7015 if Dist > BOT_LONGDIST then
7016 begin // Дальний бой
7017 for a := 0 to 9 do
7018 if FWeapon[FDifficult.WeaponPrior[a]] and HaveAmmo(FDifficult.WeaponPrior[a]) then
7019 begin
7020 FSelectedWeapon := FDifficult.WeaponPrior[a];
7021 Break;
7022 end;
7023 end
7024 else //if Dist > BOT_UNSAFEDIST then
7025 begin // Ближний бой
7026 for a := 0 to 9 do
7027 if FWeapon[FDifficult.CloseWeaponPrior[a]] and HaveAmmo(FDifficult.CloseWeaponPrior[a]) then
7028 begin
7029 FSelectedWeapon := FDifficult.CloseWeaponPrior[a];
7030 Break;
7031 end;
7032 end;
7033 { else
7034 begin
7035 for a := 0 to 9 do
7036 if FWeapon[FDifficult.SafeWeaponPrior[a]] and HaveAmmo(FDifficult.SafeWeaponPrior[a]) then
7037 begin
7038 FSelectedWeapon := FDifficult.SafeWeaponPrior[a];
7039 Break;
7040 end;
7041 end;}
7042 end;
7044 function TBot.PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean;
7045 begin
7046 Result := inherited PickItem(ItemType, force, remove);
7048 if Result then SetAIFlag('SELECTWEAPON', '1');
7049 end;
7051 function TBot.Heal(value: Word; Soft: Boolean): Boolean;
7052 begin
7053 Result := inherited Heal(value, Soft);
7054 end;
7056 function TBot.Healthy(): Byte;
7057 begin
7058 if FMegaRulez[MR_INVUL] >= gTime then Result := 3
7059 else if (FHealth > 80) or ((FHealth > 50) and (FArmor > 20)) then Result := 3
7060 else if (FHealth > 50) then Result := 2
7061 else if (FHealth > 20) then Result := 1
7062 else Result := 0;
7063 end;
7065 function TBot.TargetOnScreen(TX, TY: Integer): Boolean;
7066 begin
7067 Result := (Abs(FObj.X-TX) <= Trunc(gPlayerScreenSize.X*0.6)) and
7068 (Abs(FObj.Y-TY) <= Trunc(gPlayerScreenSize.Y*0.6));
7069 end;
7071 procedure TBot.OnDamage(Angle: SmallInt);
7072 var
7073 pla: TPlayer;
7074 mon: TMonster;
7075 ok: Boolean;
7076 begin
7077 inherited;
7079 if (Angle = 0) or (Angle = 180) then
7080 begin
7081 ok := False;
7082 if (g_GetUIDType(FLastSpawnerUID) = UID_PLAYER) and
7083 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER) then
7084 begin // Игрок
7085 pla := g_Player_Get(FLastSpawnerUID);
7086 ok := not TargetOnScreen(pla.FObj.X + PLAYER_RECT.X,
7087 pla.FObj.Y + PLAYER_RECT.Y);
7088 end
7089 else
7090 if (g_GetUIDType(FLastSpawnerUID) = UID_MONSTER) and
7091 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER) then
7092 begin // Монстр
7093 mon := g_Monsters_ByUID(FLastSpawnerUID);
7094 ok := not TargetOnScreen(mon.Obj.X + mon.Obj.Rect.X,
7095 mon.Obj.Y + mon.Obj.Rect.Y);
7096 end;
7098 if ok then
7099 if Angle = 0 then
7100 SetAIFlag('ATTACKLEFT', '1')
7101 else
7102 SetAIFlag('ATTACKRIGHT', '1');
7103 end;
7104 end;
7106 function TBot.RunDirection(): TDirection;
7107 begin
7108 if Abs(Vel.X) >= 1 then
7109 begin
7110 if Vel.X > 0 then Result := TDirection.D_RIGHT else Result := TDirection.D_LEFT;
7111 end else
7112 Result := FDirection;
7113 end;
7115 function TBot.GetRnd(a: Byte): Boolean;
7116 begin
7117 if a = 0 then Result := False
7118 else if a = 255 then Result := True
7119 else Result := Random(256) > 255-a;
7120 end;
7122 function TBot.GetInterval(a: Byte; radius: SmallInt): SmallInt;
7123 begin
7124 Result := Round((255-a)/255*radius*(Random(2)-1));
7125 end;
7128 procedure TDifficult.save (st: TStream);
7129 begin
7130 utils.writeInt(st, Byte(DiagFire));
7131 utils.writeInt(st, Byte(InvisFire));
7132 utils.writeInt(st, Byte(DiagPrecision));
7133 utils.writeInt(st, Byte(FlyPrecision));
7134 utils.writeInt(st, Byte(Cover));
7135 utils.writeInt(st, Byte(CloseJump));
7136 st.WriteBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7137 st.WriteBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7138 end;
7140 procedure TDifficult.load (st: TStream);
7141 begin
7142 DiagFire := utils.readByte(st);
7143 InvisFire := utils.readByte(st);
7144 DiagPrecision := utils.readByte(st);
7145 FlyPrecision := utils.readByte(st);
7146 Cover := utils.readByte(st);
7147 CloseJump := utils.readByte(st);
7148 st.ReadBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7149 st.ReadBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7150 end;
7153 procedure TBot.SaveState (st: TStream);
7154 var
7155 i: Integer;
7156 dw: Integer;
7157 begin
7158 inherited SaveState(st);
7159 utils.writeSign(st, 'BOT0');
7160 // Выбранное оружие
7161 utils.writeInt(st, Byte(FSelectedWeapon));
7162 // UID цели
7163 utils.writeInt(st, Word(FTargetUID));
7164 // Время потери цели
7165 utils.writeInt(st, LongWord(FLastVisible));
7166 // Количество флагов ИИ
7167 dw := Length(FAIFlags);
7168 utils.writeInt(st, LongInt(dw));
7169 // Флаги ИИ
7170 for i := 0 to dw-1 do
7171 begin
7172 utils.writeStr(st, FAIFlags[i].Name, 20);
7173 utils.writeStr(st, FAIFlags[i].Value, 20);
7174 end;
7175 // Настройки сложности
7176 FDifficult.save(st);
7177 end;
7180 procedure TBot.LoadState (st: TStream);
7181 var
7182 i: Integer;
7183 dw: Integer;
7184 begin
7185 inherited LoadState(st);
7186 if not utils.checkSign(st, 'BOT0') then raise XStreamError.Create('invalid bot signature');
7187 // Выбранное оружие
7188 FSelectedWeapon := utils.readByte(st);
7189 // UID цели
7190 FTargetUID := utils.readWord(st);
7191 // Время потери цели
7192 FLastVisible := utils.readLongWord(st);
7193 // Количество флагов ИИ
7194 dw := utils.readLongInt(st);
7195 if (dw < 0) or (dw > 16384) then raise XStreamError.Create('invalid number of bot AI flags');
7196 SetLength(FAIFlags, dw);
7197 // Флаги ИИ
7198 for i := 0 to dw-1 do
7199 begin
7200 FAIFlags[i].Name := utils.readStr(st, 20);
7201 FAIFlags[i].Value := utils.readStr(st, 20);
7202 end;
7203 // Настройки сложности
7204 FDifficult.load(st);
7205 end;
7208 begin
7209 conRegVar('cheat_berserk_autoswitch', @gBerserkAutoswitch, 'autoswitch to fist when berserk pack taken', '', true, true);
7210 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');
7211 conRegVar('player_indicator_style', @gPlayerIndicatorStyle, 'Visual appearance of indicator', 'Visual appearance of indicator');
7212 end.