DEADSOFTWARE

game: remove unneded render imports
[d2df-sdl.git] / src / game / g_player.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 {$M+}
17 unit g_player;
19 interface
21 uses
22 SysUtils, Classes,
23 {$IFDEF USE_MEMPOOL}mempool,{$ENDIF}
24 g_base, g_playermodel, g_basic, g_textures,
25 g_weapons, g_phys, g_sound, g_saveload, MAPDEF,
26 g_panel;
28 const
29 KEY_LEFT = 1;
30 KEY_RIGHT = 2;
31 KEY_UP = 3;
32 KEY_DOWN = 4;
33 KEY_FIRE = 5;
34 KEY_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 alive: Boolean;
524 SType: Byte;
525 RAngle: Integer;
526 Timeout: Cardinal;
527 Obj: TObj;
529 procedure getMapBox (out x, y, w, h: Integer); inline;
530 procedure moveBy (dx, dy: Integer); inline;
532 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
533 end;
535 TCorpse = class{$IFDEF USE_MEMPOOL}(TPoolObject){$ENDIF}
536 private
537 FMess: Boolean;
538 FState: Byte;
539 FDamage: Byte;
540 FObj: TObj;
541 FPlayerUID: Word;
542 FModel: TPlayerModel;
544 public
545 constructor Create(X, Y: Integer; ModelName: String; aMess: Boolean);
546 destructor Destroy(); override;
547 procedure Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
548 procedure Update();
549 procedure SaveState (st: TStream);
550 procedure LoadState (st: TStream);
552 procedure getMapBox (out x, y, w, h: Integer); inline;
553 procedure moveBy (dx, dy: Integer); inline;
555 procedure positionChanged (); inline; //WARNING! call this after entity position was changed, or coldet will not work right!
557 function ObjPtr (): PObj; inline;
559 property Obj: TObj read FObj; // copies object
560 property State: Byte read FState;
561 property Mess: Boolean read FMess;
562 property Model: TPlayerModel read FModel;
563 end;
565 TTeamStat = Array [TEAM_RED..TEAM_BLUE] of
566 record
567 Goals: SmallInt;
568 end;
570 var
571 gPlayers: Array of TPlayer;
572 gCorpses: Array of TCorpse;
573 gGibs: Array of TGib;
574 gShells: Array of TShell;
575 gTeamStat: TTeamStat;
576 gFly: Boolean = False;
577 gAimLine: Boolean = False;
578 gChatBubble: Integer = 0;
579 gPlayerIndicator: Integer = 1;
580 gPlayerIndicatorStyle: Integer = 0;
581 gNumBots: Word = 0;
582 gSpectLatchPID1: Word = 0;
583 gSpectLatchPID2: Word = 0;
584 MAX_RUNVEL: Integer = 8;
585 VEL_JUMP: Integer = 10;
586 SHELL_TIMEOUT: Cardinal = 60000;
588 function Lerp(X, Y, Factor: Integer): Integer;
590 procedure g_Gibs_SetMax(Count: Word);
591 function g_Gibs_GetMax(): Word;
592 procedure g_Corpses_SetMax(Count: Word);
593 function g_Corpses_GetMax(): Word;
594 procedure g_Shells_SetMax(Count: Word);
595 function g_Shells_GetMax(): Word;
597 procedure g_Player_Init();
598 procedure g_Player_Free();
599 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
600 function g_Player_CreateFromState (st: TStream): Word;
601 procedure g_Player_Remove(UID: Word);
602 procedure g_Player_ResetTeams();
603 procedure g_Player_PreUpdate();
604 procedure g_Player_UpdateAll();
605 procedure g_Player_RememberAll();
606 procedure g_Player_ResetAll(Force, Silent: Boolean);
607 function g_Player_Get(UID: Word): TPlayer;
608 function g_Player_GetCount(): Byte;
609 function g_Player_GetStats(): TPlayerStatArray;
610 function g_Player_ValidName(Name: String): Boolean;
611 function g_Player_CreateCorpse(Player: TPlayer): Integer;
612 procedure g_Player_CreateGibs (fX, fY, mid: Integer; fColor: TRGB);
613 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
614 procedure g_Player_UpdatePhysicalObjects();
615 procedure g_Player_RemoveAllCorpses();
616 procedure g_Player_Corpses_SaveState (st: TStream);
617 procedure g_Player_Corpses_LoadState (st: TStream);
618 procedure g_Player_ResetReady();
619 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
620 procedure g_Bot_AddList(Team: Byte; lname: ShortString; num: Integer = -1; Handicap: Integer = 100);
621 procedure g_Bot_MixNames();
622 procedure g_Bot_RemoveAll();
624 implementation
626 uses
627 {$IFDEF ENABLE_HOLMES}
628 g_holmes,
629 {$ENDIF}
630 e_log, g_map, g_items, g_console, g_gfx, Math, r_playermodel, r_gfx,
631 g_options, g_triggers, g_menu, g_game, g_grid, e_res,
632 wadreader, g_monsters, CONFIG, g_language,
633 g_net, g_netmsg,
634 utils, xstreams;
636 const PLR_SAVE_VERSION = 0;
638 type
639 TBotProfile = record
640 name: ShortString;
641 model: ShortString;
642 team: Byte;
643 color: TRGB;
644 diag_fire: Byte;
645 invis_fire: Byte;
646 diag_precision: Byte;
647 fly_precision: Byte;
648 cover: Byte;
649 close_jump: Byte;
650 w_prior1: Array [WP_FIRST..WP_LAST] of Byte;
651 w_prior2: Array [WP_FIRST..WP_LAST] of Byte;
652 w_prior3: Array [WP_FIRST..WP_LAST] of Byte;
653 end;
655 const
656 TIME_RESPAWN1 = 1500;
657 TIME_RESPAWN2 = 2000;
658 TIME_RESPAWN3 = 3000;
659 PLAYER_SUIT_TIME = 30000;
660 PLAYER_INVUL_TIME = 30000;
661 PLAYER_INVIS_TIME = 35000;
662 FRAG_COMBO_TIME = 3000;
663 VEL_SW = 4;
664 VEL_FLY = 6;
665 PLAYER_HEADRECT: TRectWH = (X:24; Y:12; Width:20; Height:12);
666 BOT_MAXJUMP = 84;
667 BOT_LONGDIST = 300;
668 BOT_UNSAFEDIST = 128;
669 DIFFICULT_EASY: TDifficult = (DiagFire: 32; InvisFire: 32; DiagPrecision: 32;
670 FlyPrecision: 32; Cover: 32; CloseJump: 32;
671 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
672 DIFFICULT_MEDIUM: TDifficult = (DiagFire: 127; InvisFire: 127; DiagPrecision: 127;
673 FlyPrecision: 127; Cover: 127; CloseJump: 127;
674 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
675 DIFFICULT_HARD: TDifficult = (DiagFire: 255; InvisFire: 255; DiagPrecision: 255;
676 FlyPrecision: 255; Cover: 255; CloseJump: 255;
677 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
678 WEAPON_PRIOR1: Array [WP_FIRST..WP_LAST] of Byte =
679 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
680 WEAPON_SHOTGUN2, WEAPON_SHOTGUN1,
681 WEAPON_CHAINGUN, WEAPON_PLASMA, WEAPON_ROCKETLAUNCHER,
682 WEAPON_BFG, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
683 WEAPON_PRIOR2: Array [WP_FIRST..WP_LAST] of Byte =
684 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
685 WEAPON_BFG, WEAPON_ROCKETLAUNCHER,
686 WEAPON_SHOTGUN2, WEAPON_PLASMA, WEAPON_SHOTGUN1,
687 WEAPON_CHAINGUN, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
688 //WEAPON_PRIOR3: Array [WP_FIRST..WP_LAST] of Byte =
689 // (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
690 // WEAPON_BFG, WEAPON_PLASMA, WEAPON_SHOTGUN2,
691 // WEAPON_CHAINGUN, WEAPON_SHOTGUN1, WEAPON_SAW,
692 // WEAPON_ROCKETLAUNCHER, WEAPON_PISTOL, WEAPON_KASTET);
693 WEAPON_RELOAD: Array [WP_FIRST..WP_LAST] of Byte =
694 (5, 2, 6, 18, 36, 2, 12, 2, 14, 2, 2);
696 PLAYER_SIGNATURE = $52594C50; // 'PLYR'
697 CORPSE_SIGNATURE = $50524F43; // 'CORP'
699 BOTNAMES_FILENAME = 'botnames.txt';
700 BOTLIST_FILENAME = 'botlist.txt';
702 var
703 MaxGibs: Word = 150;
704 MaxCorpses: Word = 20;
705 MaxShells: Word = 300;
706 CurrentGib: Integer = 0;
707 CurrentShell: Integer = 0;
708 BotNames: Array of String;
709 BotList: Array of TBotProfile;
710 SavedStates: Array of TPlayerSavedState;
713 function Lerp(X, Y, Factor: Integer): Integer;
714 begin
715 Result := X + ((Y - X) div Factor);
716 end;
718 function SameTeam(UID1, UID2: Word): Boolean;
719 begin
720 Result := False;
722 if (UID1 > UID_MAX_PLAYER) or (UID1 <= UID_MAX_GAME) or
723 (UID2 > UID_MAX_PLAYER) or (UID2 <= UID_MAX_GAME) then Exit;
725 if (g_Player_Get(UID1) = nil) or (g_Player_Get(UID2) = nil) then Exit;
727 if ((g_Player_Get(UID1).Team = TEAM_NONE) or
728 (g_Player_Get(UID2).Team = TEAM_NONE)) then Exit;
730 Result := g_Player_Get(UID1).FTeam = g_Player_Get(UID2).FTeam;
731 end;
733 procedure g_Gibs_SetMax(Count: Word);
734 begin
735 MaxGibs := Count;
736 SetLength(gGibs, Count);
738 if CurrentGib >= Count then
739 CurrentGib := 0;
740 end;
742 function g_Gibs_GetMax(): Word;
743 begin
744 Result := MaxGibs;
745 end;
747 procedure g_Shells_SetMax(Count: Word);
748 begin
749 MaxShells := Count;
750 SetLength(gShells, Count);
752 if CurrentShell >= Count then
753 CurrentShell := 0;
754 end;
756 function g_Shells_GetMax(): Word;
757 begin
758 Result := MaxShells;
759 end;
762 procedure g_Corpses_SetMax(Count: Word);
763 begin
764 MaxCorpses := Count;
765 SetLength(gCorpses, Count);
766 end;
768 function g_Corpses_GetMax(): Word;
769 begin
770 Result := MaxCorpses;
771 end;
773 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
774 var
775 a: Integer;
776 ok: Boolean;
777 begin
778 Result := 0;
780 ok := False;
781 a := 0;
783 // Есть ли место в gPlayers:
784 if gPlayers <> nil then
785 for a := 0 to High(gPlayers) do
786 if gPlayers[a] = nil then
787 begin
788 ok := True;
789 Break;
790 end;
792 // Нет места - расширяем gPlayers:
793 if not ok then
794 begin
795 SetLength(gPlayers, Length(gPlayers)+1);
796 a := High(gPlayers);
797 end;
799 // Создаем объект игрока:
800 if Bot then
801 gPlayers[a] := TBot.Create()
802 else
803 gPlayers[a] := TPlayer.Create();
806 gPlayers[a].FActualModelName := ModelName;
807 gPlayers[a].SetModel(ModelName);
809 // Нет модели - создание не возможно:
810 if gPlayers[a].FModel = nil then
811 begin
812 gPlayers[a].Free();
813 gPlayers[a] := nil;
814 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], [ModelName]));
815 Exit;
816 end;
818 if not (Team in [TEAM_RED, TEAM_BLUE]) then
819 if Random(2) = 0 then
820 Team := TEAM_RED
821 else
822 Team := TEAM_BLUE;
823 gPlayers[a].FPreferredTeam := Team;
825 case gGameSettings.GameMode of
826 GM_DM: gPlayers[a].FTeam := TEAM_NONE;
827 GM_TDM,
828 GM_CTF: gPlayers[a].FTeam := gPlayers[a].FPreferredTeam;
829 GM_SINGLE,
830 GM_COOP: gPlayers[a].FTeam := TEAM_COOP;
831 end;
833 // Если командная игра - красим модель в цвет команды:
834 gPlayers[a].FColor := Color;
835 if gPlayers[a].FTeam in [TEAM_RED, TEAM_BLUE] then
836 gPlayers[a].FModel.Color := TEAMCOLOR[gPlayers[a].FTeam]
837 else
838 gPlayers[a].FModel.Color := Color;
840 gPlayers[a].FUID := g_CreateUID(UID_PLAYER);
841 gPlayers[a].FAlive := False;
843 Result := gPlayers[a].FUID;
844 end;
846 function g_Player_CreateFromState (st: TStream): Word;
847 var
848 a, i: Integer;
849 ok, Bot: Boolean;
850 b: Byte;
851 begin
852 result := 0;
853 if (st = nil) then exit; //???
855 // Сигнатура игрока
856 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
857 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
859 // Бот или человек:
860 Bot := utils.readBool(st);
862 ok := false;
863 a := 0;
865 // Есть ли место в gPlayers:
866 for a := 0 to High(gPlayers) do if (gPlayers[a] = nil) then begin ok := true; break; end;
868 // Нет места - расширяем gPlayers
869 if not ok then
870 begin
871 SetLength(gPlayers, Length(gPlayers)+1);
872 a := High(gPlayers);
873 end;
875 // Создаем объект игрока
876 if Bot then
877 gPlayers[a] := TBot.Create()
878 else
879 gPlayers[a] := TPlayer.Create();
880 gPlayers[a].FIamBot := Bot;
881 gPlayers[a].FPhysics := True;
883 // UID игрока
884 gPlayers[a].FUID := utils.readWord(st);
885 // Имя игрока
886 gPlayers[a].FName := utils.readStr(st);
887 // Команда
888 gPlayers[a].FTeam := utils.readByte(st);
889 gPlayers[a].FPreferredTeam := gPlayers[a].FTeam;
890 // Жив ли
891 gPlayers[a].FAlive := utils.readBool(st);
892 // Израсходовал ли все жизни
893 gPlayers[a].FNoRespawn := utils.readBool(st);
894 // Направление
895 b := utils.readByte(st);
896 if b = 1 then gPlayers[a].FDirection := TDirection.D_LEFT else gPlayers[a].FDirection := TDirection.D_RIGHT; // b = 2
897 // Здоровье
898 gPlayers[a].FHealth := utils.readLongInt(st);
899 // Фора
900 gPlayers[a].FHandicap := utils.readLongInt(st);
901 // Жизни
902 gPlayers[a].FLives := utils.readByte(st);
903 // Броня
904 gPlayers[a].FArmor := utils.readLongInt(st);
905 // Запас воздуха
906 gPlayers[a].FAir := utils.readLongInt(st);
907 // Запас горючего
908 gPlayers[a].FJetFuel := utils.readLongInt(st);
909 // Боль
910 gPlayers[a].FPain := utils.readLongInt(st);
911 // Убил
912 gPlayers[a].FKills := utils.readLongInt(st);
913 // Убил монстров
914 gPlayers[a].FMonsterKills := utils.readLongInt(st);
915 // Фрагов
916 gPlayers[a].FFrags := utils.readLongInt(st);
917 // Фрагов подряд
918 gPlayers[a].FFragCombo := utils.readByte(st);
919 // Время последнего фрага
920 gPlayers[a].FLastFrag := utils.readLongWord(st);
921 // Смертей
922 gPlayers[a].FDeath := utils.readLongInt(st);
923 // Какой флаг несет
924 gPlayers[a].FFlag := utils.readByte(st);
925 // Нашел секретов
926 gPlayers[a].FSecrets := utils.readLongInt(st);
927 // Текущее оружие
928 gPlayers[a].FCurrWeap := utils.readByte(st);
929 // Следующее желаемое оружие
930 gPlayers[a].FNextWeap := utils.readWord(st);
931 // ...и пауза
932 gPlayers[a].FNextWeapDelay := utils.readByte(st);
933 // Время зарядки BFG
934 gPlayers[a].FBFGFireCounter := utils.readSmallInt(st);
935 // Буфер урона
936 gPlayers[a].FDamageBuffer := utils.readLongInt(st);
937 // Последний ударивший
938 gPlayers[a].FLastSpawnerUID := utils.readWord(st);
939 // Тип последнего полученного урона
940 gPlayers[a].FLastHit := utils.readByte(st);
941 // Объект игрока:
942 Obj_LoadState(@gPlayers[a].FObj, st);
943 // Текущее количество патронов
944 for i := A_BULLETS to A_HIGH do gPlayers[a].FAmmo[i] := utils.readWord(st);
945 // Максимальное количество патронов
946 for i := A_BULLETS to A_HIGH do gPlayers[a].FMaxAmmo[i] := utils.readWord(st);
947 // Наличие оружия
948 for i := WP_FIRST to WP_LAST do gPlayers[a].FWeapon[i] := utils.readBool(st);
949 // Время перезарядки оружия
950 for i := WP_FIRST to WP_LAST do gPlayers[a].FReloading[i] := utils.readWord(st);
951 // Наличие рюкзака
952 if utils.readBool(st) then Include(gPlayers[a].FRulez, R_ITEM_BACKPACK);
953 // Наличие красного ключа
954 if utils.readBool(st) then Include(gPlayers[a].FRulez, R_KEY_RED);
955 // Наличие зеленого ключа
956 if utils.readBool(st) then Include(gPlayers[a].FRulez, R_KEY_GREEN);
957 // Наличие синего ключа
958 if utils.readBool(st) then Include(gPlayers[a].FRulez, R_KEY_BLUE);
959 // Наличие берсерка
960 if utils.readBool(st) then Include(gPlayers[a].FRulez, R_BERSERK);
961 // Время действия специальных предметов
962 for i := MR_SUIT to MR_MAX do gPlayers[a].FMegaRulez[i] := utils.readLongWord(st);
963 // Время до повторного респауна, смены оружия, исользования, захвата флага
964 for i := T_RESPAWN to T_FLAGCAP do gPlayers[a].FTime[i] := utils.readLongWord(st);
966 // Название модели:
967 gPlayers[a].FActualModelName := utils.readStr(st);
968 // Цвет модели
969 gPlayers[a].FColor.R := utils.readByte(st);
970 gPlayers[a].FColor.G := utils.readByte(st);
971 gPlayers[a].FColor.B := utils.readByte(st);
972 // Обновляем модель игрока
973 gPlayers[a].SetModel(gPlayers[a].FActualModelName);
975 // Нет модели - создание невозможно
976 if (gPlayers[a].FModel = nil) then
977 begin
978 gPlayers[a].Free();
979 gPlayers[a] := nil;
980 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], [gPlayers[a].FActualModelName]));
981 exit;
982 end;
984 // Если командная игра - красим модель в цвет команды
985 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
986 gPlayers[a].FModel.Color := TEAMCOLOR[gPlayers[a].FTeam]
987 else
988 gPlayers[a].FModel.Color := gPlayers[a].FColor;
990 result := gPlayers[a].FUID;
991 end;
994 procedure g_Player_ResetTeams();
995 var
996 a: Integer;
997 begin
998 if g_Game_IsClient then
999 Exit;
1000 if gPlayers = nil then
1001 Exit;
1002 for a := Low(gPlayers) to High(gPlayers) do
1003 if gPlayers[a] <> nil then
1004 case gGameSettings.GameMode of
1005 GM_DM:
1006 gPlayers[a].ChangeTeam(TEAM_NONE);
1007 GM_TDM, GM_CTF:
1008 if not (gPlayers[a].Team in [TEAM_RED, TEAM_BLUE]) then
1009 if gPlayers[a].FPreferredTeam in [TEAM_RED, TEAM_BLUE] then
1010 gPlayers[a].ChangeTeam(gPlayers[a].FPreferredTeam)
1011 else
1012 if a mod 2 = 0 then
1013 gPlayers[a].ChangeTeam(TEAM_RED)
1014 else
1015 gPlayers[a].ChangeTeam(TEAM_BLUE);
1016 GM_SINGLE,
1017 GM_COOP:
1018 gPlayers[a].ChangeTeam(TEAM_COOP);
1019 end;
1020 end;
1022 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
1023 var
1024 m: SSArray;
1025 _name, _model: String;
1026 a, tr, tb: Integer;
1027 begin
1028 if not g_Game_IsServer then Exit;
1030 // Список названий моделей:
1031 m := g_PlayerModel_GetNames();
1032 if m = nil then
1033 Exit;
1035 // Команда:
1036 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
1037 Team := TEAM_COOP // COOP
1038 else
1039 if gGameSettings.GameMode = GM_DM then
1040 Team := TEAM_NONE // DM
1041 else
1042 if Team = TEAM_NONE then // CTF / TDM
1043 begin
1044 // Автобаланс команд:
1045 tr := 0;
1046 tb := 0;
1048 for a := 0 to High(gPlayers) do
1049 if gPlayers[a] <> nil then
1050 begin
1051 if gPlayers[a].Team = TEAM_RED then
1052 Inc(tr)
1053 else
1054 if gPlayers[a].Team = TEAM_BLUE then
1055 Inc(tb);
1056 end;
1058 if tr > tb then
1059 Team := TEAM_BLUE
1060 else
1061 if tb > tr then
1062 Team := TEAM_RED
1063 else // tr = tb
1064 if Random(2) = 0 then
1065 Team := TEAM_RED
1066 else
1067 Team := TEAM_BLUE;
1068 end;
1070 // Выбираем боту имя:
1071 _name := '';
1072 if BotNames <> nil then
1073 for a := 0 to High(BotNames) do
1074 if g_Player_ValidName(BotNames[a]) then
1075 begin
1076 _name := BotNames[a];
1077 Break;
1078 end;
1080 // Выбираем случайную модель:
1081 _model := m[Random(Length(m))];
1083 // Создаем бота:
1084 with g_Player_Get(g_Player_Create(_model,
1085 _RGB(Min(Random(9)*32, 255),
1086 Min(Random(9)*32, 255),
1087 Min(Random(9)*32, 255)),
1088 Team, True)) as TBot do
1089 begin
1090 // Если имени нет, делаем его из UID бота
1091 if _name = '' then
1092 Name := Format('DFBOT%.5d', [UID])
1093 else
1094 Name := _name;
1096 case Difficult of
1097 1: FDifficult := DIFFICULT_EASY;
1098 2: FDifficult := DIFFICULT_MEDIUM;
1099 else FDifficult := DIFFICULT_HARD;
1100 end;
1102 for a := WP_FIRST to WP_LAST do
1103 begin
1104 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
1105 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
1106 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
1107 end;
1109 FHandicap := Handicap;
1111 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1113 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1114 if g_Game_IsServer and (gGameSettings.MaxLives > 0) then
1115 Spectate();
1116 end;
1117 end;
1119 procedure g_Bot_AddList(Team: Byte; lName: ShortString; num: Integer = -1; Handicap: Integer = 100);
1120 var
1121 m: SSArray;
1122 _name, _model: String;
1123 a: Integer;
1124 begin
1125 if not g_Game_IsServer then Exit;
1127 // Список названий моделей:
1128 m := g_PlayerModel_GetNames();
1129 if m = nil then
1130 Exit;
1132 // Команда:
1133 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
1134 Team := TEAM_COOP // COOP
1135 else
1136 if gGameSettings.GameMode = GM_DM then
1137 Team := TEAM_NONE // DM
1138 else
1139 if Team = TEAM_NONE then
1140 Team := BotList[num].team; // CTF / TDM
1142 // Выбираем настройки бота из списка по номеру или имени:
1143 lName := AnsiLowerCase(lName);
1144 if (num < 0) or (num > Length(BotList)-1) then
1145 num := -1;
1146 if (num = -1) and (lName <> '') and (BotList <> nil) then
1147 for a := 0 to High(BotList) do
1148 if AnsiLowerCase(BotList[a].name) = lName then
1149 begin
1150 num := a;
1151 Break;
1152 end;
1153 if num = -1 then
1154 Exit;
1156 // Имя бота:
1157 _name := BotList[num].name;
1158 // Занято - выбираем случайное:
1159 if not g_Player_ValidName(_name) then
1160 repeat
1161 _name := Format('DFBOT%.2d', [Random(100)]);
1162 until g_Player_ValidName(_name);
1164 // Модель:
1165 _model := BotList[num].model;
1166 // Нет такой - выбираем случайную:
1167 if not InSArray(_model, m) then
1168 _model := m[Random(Length(m))];
1170 // Создаем бота:
1171 with g_Player_Get(g_Player_Create(_model, BotList[num].color, Team, True)) as TBot do
1172 begin
1173 Name := _name;
1175 FDifficult.DiagFire := BotList[num].diag_fire;
1176 FDifficult.InvisFire := BotList[num].invis_fire;
1177 FDifficult.DiagPrecision := BotList[num].diag_precision;
1178 FDifficult.FlyPrecision := BotList[num].fly_precision;
1179 FDifficult.Cover := BotList[num].cover;
1180 FDifficult.CloseJump := BotList[num].close_jump;
1182 FHandicap := Handicap;
1184 for a := WP_FIRST to WP_LAST do
1185 begin
1186 FDifficult.WeaponPrior[a] := BotList[num].w_prior1[a];
1187 FDifficult.CloseWeaponPrior[a] := BotList[num].w_prior2[a];
1188 //FDifficult.SafeWeaponPrior[a] := BotList[num].w_prior3[a];
1189 end;
1191 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1193 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1194 end;
1195 end;
1197 procedure g_Bot_RemoveAll();
1198 var
1199 a: Integer;
1200 begin
1201 if not g_Game_IsServer then Exit;
1202 if gPlayers = nil then Exit;
1204 for a := 0 to High(gPlayers) do
1205 if gPlayers[a] <> nil then
1206 if gPlayers[a] is TBot then
1207 begin
1208 gPlayers[a].Lives := 0;
1209 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
1210 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
1211 g_Player_Remove(gPlayers[a].FUID);
1212 end;
1214 g_Bot_MixNames();
1215 end;
1217 procedure g_Bot_MixNames();
1218 var
1219 s: String;
1220 a, b: Integer;
1221 begin
1222 if BotNames <> nil then
1223 for a := 0 to High(BotNames) do
1224 begin
1225 b := Random(Length(BotNames));
1226 s := BotNames[a];
1227 Botnames[a] := BotNames[b];
1228 BotNames[b] := s;
1229 end;
1230 end;
1232 procedure g_Player_Remove(UID: Word);
1233 var
1234 i: Integer;
1235 begin
1236 if gPlayers = nil then Exit;
1238 if g_Game_IsServer and g_Game_IsNet then
1239 MH_SEND_PlayerDelete(UID);
1241 for i := 0 to High(gPlayers) do
1242 if gPlayers[i] <> nil then
1243 if gPlayers[i].FUID = UID then
1244 begin
1245 if gPlayers[i] is TPlayer then
1246 TPlayer(gPlayers[i]).Free()
1247 else
1248 TBot(gPlayers[i]).Free();
1249 gPlayers[i] := nil;
1250 Exit;
1251 end;
1252 end;
1254 procedure g_Player_Init();
1255 var
1256 F: TextFile;
1257 s: String;
1258 a, b: Integer;
1259 config: TConfig;
1260 sa: SSArray;
1261 path: AnsiString;
1262 begin
1263 BotNames := nil;
1265 path := BOTNAMES_FILENAME;
1266 if e_FindResource(DataDirs, path) = false then
1267 Exit;
1269 // Читаем возможные имена ботов из файла:
1270 AssignFile(F, path);
1271 Reset(F);
1273 while not EOF(F) do
1274 begin
1275 ReadLn(F, s);
1277 s := Trim(s);
1278 if s = '' then
1279 Continue;
1281 SetLength(BotNames, Length(BotNames)+1);
1282 BotNames[High(BotNames)] := s;
1283 end;
1285 CloseFile(F);
1287 // Перемешиваем их:
1288 g_Bot_MixNames();
1290 // Читаем файл с параметрами ботов:
1291 config := TConfig.CreateFile(path);
1292 BotList := nil;
1293 a := 0;
1295 while config.SectionExists(IntToStr(a)) do
1296 begin
1297 SetLength(BotList, Length(BotList)+1);
1299 with BotList[High(BotList)] do
1300 begin
1301 // Имя бота:
1302 name := config.ReadStr(IntToStr(a), 'name', '');
1303 // Модель:
1304 model := config.ReadStr(IntToStr(a), 'model', '');
1305 // Команда:
1306 if config.ReadStr(IntToStr(a), 'team', 'red') = 'red' then
1307 team := TEAM_RED
1308 else
1309 team := TEAM_BLUE;
1310 // Цвет модели:
1311 sa := parse(config.ReadStr(IntToStr(a), 'color', ''));
1312 color.R := StrToIntDef(sa[0], 0);
1313 color.G := StrToIntDef(sa[1], 0);
1314 color.B := StrToIntDef(sa[2], 0);
1315 // Вероятность стрельбы под углом:
1316 diag_fire := config.ReadInt(IntToStr(a), 'diag_fire', 0);
1317 // Вероятность ответного огня по невидимому сопернику:
1318 invis_fire := config.ReadInt(IntToStr(a), 'invis_fire', 0);
1319 // Точность стрельбы под углом:
1320 diag_precision := config.ReadInt(IntToStr(a), 'diag_precision', 0);
1321 // Точность стрельбы в полете:
1322 fly_precision := config.ReadInt(IntToStr(a), 'fly_precision', 0);
1323 // Точность уклонения от снарядов:
1324 cover := config.ReadInt(IntToStr(a), 'cover', 0);
1325 // Вероятность прыжка при приближении соперника:
1326 close_jump := config.ReadInt(IntToStr(a), 'close_jump', 0);
1327 // Приоритеты оружия для дальнего боя:
1328 sa := parse(config.ReadStr(IntToStr(a), 'w_prior1', ''));
1329 if Length(sa) = 10 then
1330 for b := 0 to 9 do
1331 w_prior1[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1332 // Приоритеты оружия для ближнего боя:
1333 sa := parse(config.ReadStr(IntToStr(a), 'w_prior2', ''));
1334 if Length(sa) = 10 then
1335 for b := 0 to 9 do
1336 w_prior2[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1338 {sa := parse(config.ReadStr(IntToStr(a), 'w_prior3', ''));
1339 if Length(sa) = 10 then
1340 for b := 0 to 9 do
1341 w_prior3[b] := EnsureRange(StrToInt(sa[b]), 0, 9);}
1342 end;
1344 a := a + 1;
1345 end;
1347 config.Free();
1348 SetLength(SavedStates, 0);
1349 end;
1351 procedure g_Player_Free();
1352 var
1353 i: Integer;
1354 begin
1355 if gPlayers <> nil then
1356 begin
1357 for i := 0 to High(gPlayers) do
1358 if gPlayers[i] <> nil then
1359 begin
1360 if gPlayers[i] is TPlayer then
1361 TPlayer(gPlayers[i]).Free()
1362 else
1363 TBot(gPlayers[i]).Free();
1364 gPlayers[i] := nil;
1365 end;
1367 gPlayers := nil;
1368 end;
1370 gPlayer1 := nil;
1371 gPlayer2 := nil;
1372 SetLength(SavedStates, 0);
1373 end;
1375 procedure g_Player_PreUpdate();
1376 var
1377 i: Integer;
1378 begin
1379 if gPlayers = nil then Exit;
1380 for i := 0 to High(gPlayers) do
1381 if gPlayers[i] <> nil then
1382 gPlayers[i].PreUpdate();
1383 end;
1385 procedure g_Player_UpdateAll();
1386 var
1387 i: Integer;
1388 begin
1389 if gPlayers = nil then Exit;
1391 //e_WriteLog('***g_Player_UpdateAll: ENTER', MSG_WARNING);
1392 for i := 0 to High(gPlayers) do
1393 begin
1394 if gPlayers[i] <> nil then
1395 begin
1396 if gPlayers[i] is TPlayer then
1397 begin
1398 gPlayers[i].Update();
1399 gPlayers[i].RealizeCurrentWeapon(); // WARNING! DO NOT MOVE THIS INTO `Update()`!
1400 end
1401 else
1402 begin
1403 // bot updates weapons in `UpdateCombat()`
1404 TBot(gPlayers[i]).Update();
1405 end;
1406 end;
1407 end;
1408 //e_WriteLog('***g_Player_UpdateAll: EXIT', MSG_WARNING);
1409 end;
1411 function g_Player_Get(UID: Word): TPlayer;
1412 var
1413 a: Integer;
1414 begin
1415 Result := nil;
1417 if gPlayers = nil then
1418 Exit;
1420 for a := 0 to High(gPlayers) do
1421 if gPlayers[a] <> nil then
1422 if gPlayers[a].FUID = UID then
1423 begin
1424 Result := gPlayers[a];
1425 Exit;
1426 end;
1427 end;
1429 function g_Player_GetCount(): Byte;
1430 var
1431 a: Integer;
1432 begin
1433 Result := 0;
1435 if gPlayers = nil then
1436 Exit;
1438 for a := 0 to High(gPlayers) do
1439 if gPlayers[a] <> nil then
1440 Result := Result + 1;
1441 end;
1443 function g_Player_GetStats(): TPlayerStatArray;
1444 var
1445 a: Integer;
1446 begin
1447 Result := nil;
1449 if gPlayers = nil then Exit;
1451 for a := 0 to High(gPlayers) do
1452 if gPlayers[a] <> nil then
1453 begin
1454 SetLength(Result, Length(Result)+1);
1455 with Result[High(Result)] do
1456 begin
1457 Num := a;
1458 Ping := gPlayers[a].FPing;
1459 Loss := gPlayers[a].FLoss;
1460 Name := gPlayers[a].FName;
1461 Team := gPlayers[a].FTeam;
1462 Frags := gPlayers[a].FFrags;
1463 Deaths := gPlayers[a].FDeath;
1464 Kills := gPlayers[a].FKills;
1465 Color := gPlayers[a].FModel.Color;
1466 Lives := gPlayers[a].FLives;
1467 Spectator := gPlayers[a].FSpectator;
1468 UID := gPlayers[a].FUID;
1469 end;
1470 end;
1471 end;
1473 procedure g_Player_ResetReady();
1474 var
1475 a: Integer;
1476 begin
1477 if not g_Game_IsServer then Exit;
1478 if gPlayers = nil then Exit;
1480 for a := 0 to High(gPlayers) do
1481 if gPlayers[a] <> nil then
1482 begin
1483 gPlayers[a].FReady := False;
1484 if g_Game_IsNet then
1485 MH_SEND_GameEvent(NET_EV_INTER_READY, gPlayers[a].UID, 'N');
1486 end;
1487 end;
1489 procedure g_Player_RememberAll;
1490 var
1491 i: Integer;
1492 begin
1493 for i := Low(gPlayers) to High(gPlayers) do
1494 if (gPlayers[i] <> nil) and gPlayers[i].alive then
1495 gPlayers[i].RememberState;
1496 end;
1498 procedure g_Player_ResetAll(Force, Silent: Boolean);
1499 var
1500 i: Integer;
1501 begin
1502 gTeamStat[TEAM_RED].Goals := 0;
1503 gTeamStat[TEAM_BLUE].Goals := 0;
1505 if gPlayers <> nil then
1506 for i := 0 to High(gPlayers) do
1507 if gPlayers[i] <> nil then
1508 begin
1509 gPlayers[i].Reset(Force);
1511 if gPlayers[i] is TPlayer then
1512 begin
1513 if (not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame then
1514 gPlayers[i].Respawn(Silent)
1515 else
1516 gPlayers[i].Spectate();
1517 end
1518 else
1519 TBot(gPlayers[i]).Respawn(Silent);
1520 end;
1521 end;
1523 function g_Player_CreateCorpse(Player: TPlayer): Integer;
1524 var
1525 i: Integer;
1526 find_id: DWORD;
1527 ok: Boolean;
1528 begin
1529 Result := -1;
1531 if Player.alive then
1532 Exit;
1534 // Разрываем связь с прежним трупом:
1535 i := Player.FCorpse;
1536 if (i >= 0) and (i < Length(gCorpses)) then
1537 begin
1538 if (gCorpses[i] <> nil) and (gCorpses[i].FPlayerUID = Player.FUID) then
1539 gCorpses[i].FPlayerUID := 0;
1540 end;
1542 if Player.FObj.Y >= gMapInfo.Height+128 then
1543 Exit;
1545 with Player do
1546 begin
1547 if (FHealth >= -50) or (gGibsCount = 0) then
1548 begin
1549 if (gCorpses = nil) or (Length(gCorpses) = 0) then
1550 Exit;
1552 ok := False;
1553 for find_id := 0 to High(gCorpses) do
1554 if gCorpses[find_id] = nil then
1555 begin
1556 ok := True;
1557 Break;
1558 end;
1560 if not ok then
1561 find_id := Random(Length(gCorpses));
1563 gCorpses[find_id] := TCorpse.Create(FObj.X, FObj.Y, FModel.GetName(), FHealth < -20);
1564 gCorpses[find_id].FModel.Color := FModel.Color;
1565 gCorpses[find_id].FObj.Vel := FObj.Vel;
1566 gCorpses[find_id].FObj.Accel := FObj.Accel;
1567 gCorpses[find_id].FPlayerUID := FUID;
1569 Result := find_id;
1570 end
1571 else
1572 g_Player_CreateGibs(FObj.X + PLAYER_RECT_CX, FObj.Y + PLAYER_RECT_CY, FModel.id, FModel.Color);
1573 end;
1574 end;
1576 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
1577 begin
1578 if (gShells = nil) or (Length(gShells) = 0) then
1579 Exit;
1581 with gShells[CurrentShell] do
1582 begin
1583 g_Obj_Init(@Obj);
1584 Obj.Rect.X := 0;
1585 Obj.Rect.Y := 0;
1586 if T = SHELL_BULLET then
1587 begin
1588 Obj.Rect.Width := 4;
1589 Obj.Rect.Height := 2;
1590 end
1591 else
1592 begin
1593 Obj.Rect.Width := 7;
1594 Obj.Rect.Height := 3;
1595 end;
1596 SType := T;
1597 alive := True;
1598 Obj.X := fX;
1599 Obj.Y := fY;
1600 g_Obj_Push(@Obj, dX + Random(4)-Random(4), dY-Random(4));
1601 positionChanged(); // this updates spatial accelerators
1602 RAngle := Random(360);
1603 Timeout := gTime + SHELL_TIMEOUT;
1605 if CurrentShell >= High(gShells) then
1606 CurrentShell := 0
1607 else
1608 Inc(CurrentShell);
1609 end;
1610 end;
1612 procedure g_Player_CreateGibs (fX, fY, mid: Integer; fColor: TRGB);
1613 var
1614 a: Integer;
1615 GibsArray: TGibsArray;
1616 Blood: TModelBlood;
1617 begin
1618 if mid = -1 then
1619 Exit;
1620 if (gGibs = nil) or (Length(gGibs) = 0) then
1621 Exit;
1622 if not g_PlayerModel_GetGibs(mid, GibsArray) then
1623 Exit;
1624 Blood := PlayerModelsArray[mid].Blood;
1626 for a := 0 to High(GibsArray) do
1627 with gGibs[CurrentGib] do
1628 begin
1629 ModelID := mid;
1630 GibID := GibsArray[a];
1631 Color := fColor;
1632 alive := True;
1633 g_Obj_Init(@Obj);
1634 Obj.Rect := r_PlayerModel_GetGibRect(ModelID, GibID);
1635 Obj.X := fX - Obj.Rect.X - (Obj.Rect.Width div 2);
1636 Obj.Y := fY - Obj.Rect.Y - (Obj.Rect.Height div 2);
1637 g_Obj_PushA(@Obj, 25 + Random(10), Random(361));
1638 positionChanged(); // this updates spatial accelerators
1639 RAngle := Random(360);
1641 if gBloodCount > 0 then
1642 g_GFX_Blood(fX, fY, 16*gBloodCount+Random(5*gBloodCount), -16+Random(33), -16+Random(33),
1643 Random(48), Random(48), Blood.R, Blood.G, Blood.B, Blood.Kind);
1645 if CurrentGib >= High(gGibs) then
1646 CurrentGib := 0
1647 else
1648 Inc(CurrentGib);
1649 end;
1650 end;
1652 procedure g_Player_UpdatePhysicalObjects();
1653 var
1654 i: Integer;
1655 vel: TPoint2i;
1656 mr: Word;
1658 procedure ShellSound_Bounce(X, Y: Integer; T: Byte);
1659 var
1660 k: Integer;
1661 begin
1662 k := 1 + Random(2);
1663 if T = SHELL_BULLET then
1664 g_Sound_PlayExAt('SOUND_PLAYER_CASING' + IntToStr(k), X, Y)
1665 else
1666 g_Sound_PlayExAt('SOUND_PLAYER_SHELL' + IntToStr(k), X, Y);
1667 end;
1669 begin
1670 // Куски мяса:
1671 if gGibs <> nil then
1672 for i := 0 to High(gGibs) do
1673 if gGibs[i].alive then
1674 with gGibs[i] do
1675 begin
1676 Obj.oldX := Obj.X;
1677 Obj.oldY := Obj.Y;
1679 vel := Obj.Vel;
1680 mr := g_Obj_Move(@Obj, True, False, True);
1681 positionChanged(); // this updates spatial accelerators
1683 if WordBool(mr and MOVE_FALLOUT) then
1684 begin
1685 alive := False;
1686 Continue;
1687 end;
1689 // Отлетает от удара о стену/потолок/пол:
1690 if WordBool(mr and MOVE_HITWALL) then
1691 Obj.Vel.X := -(vel.X div 2);
1692 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1693 Obj.Vel.Y := -(vel.Y div 2);
1695 if (Obj.Vel.X >= 0) then
1696 begin // Clockwise
1697 RAngle := RAngle + Abs(Obj.Vel.X)*6 + Abs(Obj.Vel.Y);
1698 if RAngle >= 360 then
1699 RAngle := RAngle mod 360;
1700 end else begin // Counter-clockwise
1701 RAngle := RAngle - Abs(Obj.Vel.X)*6 - Abs(Obj.Vel.Y);
1702 if RAngle < 0 then
1703 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1704 end;
1706 // Сопротивление воздуха для куска трупа:
1707 if gTime mod (GAME_TICK*3) = 0 then
1708 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
1709 end;
1711 // Трупы:
1712 if gCorpses <> nil then
1713 for i := 0 to High(gCorpses) do
1714 if gCorpses[i] <> nil then
1715 if gCorpses[i].State = CORPSE_STATE_REMOVEME then
1716 begin
1717 gCorpses[i].Free();
1718 gCorpses[i] := nil;
1719 end
1720 else
1721 gCorpses[i].Update();
1723 // Гильзы:
1724 if gShells <> nil then
1725 for i := 0 to High(gShells) do
1726 if gShells[i].alive then
1727 with gShells[i] do
1728 begin
1729 Obj.oldX := Obj.X;
1730 Obj.oldY := Obj.Y;
1732 vel := Obj.Vel;
1733 mr := g_Obj_Move(@Obj, True, False, True);
1734 positionChanged(); // this updates spatial accelerators
1736 if WordBool(mr and MOVE_FALLOUT) or (gShells[i].Timeout < gTime) then
1737 begin
1738 alive := False;
1739 Continue;
1740 end;
1742 // Отлетает от удара о стену/потолок/пол:
1743 if WordBool(mr and MOVE_HITWALL) then
1744 begin
1745 Obj.Vel.X := -(vel.X div 2);
1746 if not WordBool(mr and MOVE_INWATER) then
1747 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1748 end;
1749 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1750 begin
1751 Obj.Vel.Y := -(vel.Y div 2);
1752 if Obj.Vel.X <> 0 then Obj.Vel.X := Obj.Vel.X div 2;
1753 if (Obj.Vel.X = 0) and (Obj.Vel.Y = 0) then
1754 begin
1755 if RAngle mod 90 <> 0 then
1756 RAngle := (RAngle div 90) * 90;
1757 end
1758 else if not WordBool(mr and MOVE_INWATER) then
1759 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1760 end;
1762 if (Obj.Vel.X >= 0) then
1763 begin // Clockwise
1764 RAngle := RAngle + Abs(Obj.Vel.X)*8 + Abs(Obj.Vel.Y);
1765 if RAngle >= 360 then
1766 RAngle := RAngle mod 360;
1767 end else begin // Counter-clockwise
1768 RAngle := RAngle - Abs(Obj.Vel.X)*8 - Abs(Obj.Vel.Y);
1769 if RAngle < 0 then
1770 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1771 end;
1772 end;
1773 end;
1776 procedure TGib.getMapBox (out x, y, w, h: Integer); inline;
1777 begin
1778 x := Obj.X+Obj.Rect.X;
1779 y := Obj.Y+Obj.Rect.Y;
1780 w := Obj.Rect.Width;
1781 h := Obj.Rect.Height;
1782 end;
1784 procedure TGib.moveBy (dx, dy: Integer); inline;
1785 begin
1786 if (dx <> 0) or (dy <> 0) then
1787 begin
1788 Obj.X += dx;
1789 Obj.Y += dy;
1790 positionChanged();
1791 end;
1792 end;
1795 procedure TShell.getMapBox (out x, y, w, h: Integer); inline;
1796 begin
1797 x := Obj.X;
1798 y := Obj.Y;
1799 w := Obj.Rect.Width;
1800 h := Obj.Rect.Height;
1801 end;
1803 procedure TShell.moveBy (dx, dy: Integer); inline;
1804 begin
1805 if (dx <> 0) or (dy <> 0) then
1806 begin
1807 Obj.X += dx;
1808 Obj.Y += dy;
1809 positionChanged();
1810 end;
1811 end;
1814 procedure TGib.positionChanged (); inline; begin end;
1815 procedure TShell.positionChanged (); inline; begin end;
1818 procedure g_Player_RemoveAllCorpses();
1819 var
1820 i: Integer;
1821 begin
1822 gGibs := nil;
1823 gShells := nil;
1824 SetLength(gGibs, MaxGibs);
1825 SetLength(gShells, MaxGibs);
1826 CurrentGib := 0;
1827 CurrentShell := 0;
1829 if gCorpses <> nil then
1830 for i := 0 to High(gCorpses) do
1831 gCorpses[i].Free();
1833 gCorpses := nil;
1834 SetLength(gCorpses, MaxCorpses);
1835 end;
1837 procedure g_Player_Corpses_SaveState (st: TStream);
1838 var
1839 count, i: Integer;
1840 begin
1841 // Считаем количество существующих трупов
1842 count := 0;
1843 for i := 0 to High(gCorpses) do if (gCorpses[i] <> nil) then Inc(count);
1845 // Количество трупов
1846 utils.writeInt(st, LongInt(count));
1848 if (count = 0) then exit;
1850 // Сохраняем трупы
1851 for i := 0 to High(gCorpses) do
1852 begin
1853 if gCorpses[i] <> nil then
1854 begin
1855 // Название модели
1856 utils.writeStr(st, gCorpses[i].FModel.GetName());
1857 // Тип смерти
1858 utils.writeBool(st, gCorpses[i].Mess);
1859 // Сохраняем данные трупа:
1860 gCorpses[i].SaveState(st);
1861 end;
1862 end;
1863 end;
1866 procedure g_Player_Corpses_LoadState (st: TStream);
1867 var
1868 count, i: Integer;
1869 str: String;
1870 b: Boolean;
1871 begin
1872 assert(st <> nil);
1874 g_Player_RemoveAllCorpses();
1876 // Количество трупов:
1877 count := utils.readLongInt(st);
1878 if (count < 0) or (count > Length(gCorpses)) then raise XStreamError.Create('invalid number of corpses');
1880 if (count = 0) then exit;
1882 // Загружаем трупы
1883 for i := 0 to count-1 do
1884 begin
1885 // Название модели:
1886 str := utils.readStr(st);
1887 // Тип смерти
1888 b := utils.readBool(st);
1889 // Создаем труп
1890 gCorpses[i] := TCorpse.Create(0, 0, str, b);
1891 // Загружаем данные трупа
1892 gCorpses[i].LoadState(st);
1893 end;
1894 end;
1897 { T P l a y e r : }
1899 function TPlayer.isValidViewPort (): Boolean; inline; begin result := (viewPortW > 0) and (viewPortH > 0); end;
1901 procedure TPlayer.BFGHit();
1902 begin
1903 g_Weapon_BFGHit(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1904 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2));
1905 if g_Game_IsServer and g_Game_IsNet then
1906 MH_SEND_Effect(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1907 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
1908 0, NET_GFX_BFGHIT);
1909 end;
1911 procedure TPlayer.ChangeModel(ModelName: string);
1912 var
1913 locModel: TPlayerModel;
1914 begin
1915 locModel := g_PlayerModel_Get(ModelName);
1916 if locModel = nil then Exit;
1918 FModel.Free();
1919 FModel := locModel;
1920 end;
1922 procedure TPlayer.SetModel(ModelName: string);
1923 var
1924 m: TPlayerModel;
1925 begin
1926 m := g_PlayerModel_Get(ModelName);
1927 if m = nil then
1928 begin
1929 g_SimpleError(Format(_lc[I_GAME_ERROR_MODEL_FALLBACK], [ModelName]));
1930 m := g_PlayerModel_Get('doomer');
1931 if m = nil then
1932 begin
1933 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], ['doomer']));
1934 Exit;
1935 end;
1936 end;
1938 if FModel <> nil then
1939 FModel.Free();
1941 FModel := m;
1943 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1944 FModel.Color := FColor
1945 else
1946 FModel.Color := TEAMCOLOR[FTeam];
1947 FModel.SetWeapon(FCurrWeap);
1948 FModel.SetFlag(FFlag);
1949 SetDirection(FDirection);
1950 end;
1952 procedure TPlayer.SetColor(Color: TRGB);
1953 begin
1954 FColor := Color;
1955 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1956 if FModel <> nil then FModel.Color := Color;
1957 end;
1959 function TPlayer.GetColor(): TRGB;
1960 begin
1961 result := FModel.Color;
1962 end;
1964 procedure TPlayer.SwitchTeam;
1965 begin
1966 if g_Game_IsClient then
1967 Exit;
1968 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then Exit;
1970 if gGameOn and FAlive then
1971 Kill(K_SIMPLEKILL, FUID, HIT_SELF);
1973 if FTeam = TEAM_RED then
1974 begin
1975 ChangeTeam(TEAM_BLUE);
1976 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_BLUE], [FName]), True);
1977 if g_Game_IsNet then
1978 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_BLUE, FName);
1979 end
1980 else
1981 begin
1982 ChangeTeam(TEAM_RED);
1983 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_RED], [FName]), True);
1984 if g_Game_IsNet then
1985 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_RED, FName);
1986 end;
1987 FPreferredTeam := FTeam;
1988 end;
1990 procedure TPlayer.ChangeTeam(Team: Byte);
1991 var
1992 OldTeam: Byte;
1993 begin
1994 OldTeam := FTeam;
1995 FTeam := Team;
1996 case Team of
1997 TEAM_RED, TEAM_BLUE:
1998 FModel.Color := TEAMCOLOR[Team];
1999 else
2000 FModel.Color := FColor;
2001 end;
2002 if (FTeam <> OldTeam) and g_Game_IsNet and g_Game_IsServer then
2003 MH_SEND_PlayerStats(FUID);
2004 end;
2007 procedure TPlayer.CollideItem();
2008 var
2009 i: Integer;
2010 r: Boolean;
2011 begin
2012 if gItems = nil then Exit;
2013 if not FAlive then Exit;
2015 for i := 0 to High(gItems) do
2016 with gItems[i] do
2017 begin
2018 if (ItemType <> ITEM_NONE) and alive then
2019 if g_Obj_Collide(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
2020 PLAYER_RECT.Height, @Obj) then
2021 begin
2022 if not PickItem(ItemType, gItems[i].Respawnable, r) then Continue;
2024 if ItemType in [ITEM_SPHERE_BLUE, ITEM_SPHERE_WHITE, ITEM_INVUL] then
2025 g_Sound_PlayExAt('SOUND_ITEM_GETRULEZ', FObj.X, FObj.Y)
2026 else if ItemType in [ITEM_MEDKIT_SMALL, ITEM_MEDKIT_LARGE, ITEM_MEDKIT_BLACK] then
2027 g_Sound_PlayExAt('SOUND_ITEM_GETMED', FObj.X, FObj.Y)
2028 else g_Sound_PlayExAt('SOUND_ITEM_GETITEM', FObj.X, FObj.Y);
2030 // Надо убрать с карты, если это не ключ, которым нужно поделится с другим игроком:
2031 if r and not ((ItemType in [ITEM_KEY_RED, ITEM_KEY_GREEN, ITEM_KEY_BLUE]) and
2032 (gGameSettings.GameType = GT_SINGLE) and
2033 (g_Player_GetCount() > 1)) then
2034 if not Respawnable then g_Items_Remove(i) else g_Items_Pick(i);
2035 end;
2036 end;
2037 end;
2040 function TPlayer.CollideLevel(XInc, YInc: Integer): Boolean;
2041 begin
2042 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
2043 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_WALL,
2044 False);
2045 end;
2047 constructor TPlayer.Create();
2048 begin
2049 viewPortX := 0;
2050 viewPortY := 0;
2051 viewPortW := 0;
2052 viewPortH := 0;
2053 mEDamageType := HIT_SOME;
2055 FIamBot := False;
2056 FDummy := False;
2057 FSpawned := False;
2059 FSawSound := TPlayableSound.Create();
2060 FSawSoundIdle := TPlayableSound.Create();
2061 FSawSoundHit := TPlayableSound.Create();
2062 FSawSoundSelect := TPlayableSound.Create();
2063 FFlameSoundOn := TPlayableSound.Create();
2064 FFlameSoundOff := TPlayableSound.Create();
2065 FFlameSoundWork := TPlayableSound.Create();
2066 FJetSoundFly := TPlayableSound.Create();
2067 FJetSoundOn := TPlayableSound.Create();
2068 FJetSoundOff := TPlayableSound.Create();
2070 FSawSound.SetByName('SOUND_WEAPON_FIRESAW');
2071 FSawSoundIdle.SetByName('SOUND_WEAPON_IDLESAW');
2072 FSawSoundHit.SetByName('SOUND_WEAPON_HITSAW');
2073 FSawSoundSelect.SetByName('SOUND_WEAPON_SELECTSAW');
2074 FFlameSoundOn.SetByName('SOUND_WEAPON_FLAMEON');
2075 FFlameSoundOff.SetByName('SOUND_WEAPON_FLAMEOFF');
2076 FFlameSoundWork.SetByName('SOUND_WEAPON_FLAMEWORK');
2077 FJetSoundFly.SetByName('SOUND_PLAYER_JETFLY');
2078 FJetSoundOn.SetByName('SOUND_PLAYER_JETON');
2079 FJetSoundOff.SetByName('SOUND_PLAYER_JETOFF');
2081 FSpectatePlayer := -1;
2082 FClientID := -1;
2083 FPing := 0;
2084 FLoss := 0;
2085 FSavedStateNum := -1;
2086 FShellTimer := -1;
2087 FFireTime := 0;
2088 FFirePainTime := 0;
2089 FFireAttacker := 0;
2090 FHandicap := 100;
2091 FCorpse := -1;
2093 FActualModelName := 'doomer';
2095 g_Obj_Init(@FObj);
2096 FObj.Rect := PLAYER_RECT;
2098 FBFGFireCounter := -1;
2099 FJustTeleported := False;
2100 FNetTime := 0;
2102 FWaitForFirstSpawn := false;
2103 FPunchAnim := TAnimationState.Create(False, 1, 4);
2104 FPunchAnim.Disable;
2106 resetWeaponQueue();
2107 end;
2109 procedure TPlayer.positionChanged (); inline;
2110 begin
2111 end;
2113 procedure TPlayer.doDamage (v: Integer);
2114 begin
2115 if (v <= 0) then exit;
2116 if (v > 32767) then v := 32767;
2117 Damage(v, 0, 0, 0, mEDamageType);
2118 end;
2120 procedure TPlayer.Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte);
2121 var
2122 c: Word;
2123 begin
2124 if (not g_Game_IsClient) and (not FAlive) then
2125 Exit;
2127 FLastHit := t;
2129 // Неуязвимость не спасает от ловушек:
2130 if ((t = HIT_TRAP) or (t = HIT_SELF)) and (not FGodMode) then
2131 begin
2132 if not g_Game_IsClient then
2133 begin
2134 FArmor := 0;
2135 if t = HIT_TRAP then
2136 begin
2137 // Ловушка убивает сразу:
2138 FHealth := -100;
2139 Kill(K_EXTRAHARDKILL, SpawnerUID, t);
2140 end;
2141 if t = HIT_SELF then
2142 begin
2143 // Самоубийство:
2144 FHealth := 0;
2145 Kill(K_SIMPLEKILL, SpawnerUID, t);
2146 end;
2147 end;
2148 // Обнулить действия примочек, чтобы фон пропал
2149 FMegaRulez[MR_SUIT] := 0;
2150 FMegaRulez[MR_INVUL] := 0;
2151 FMegaRulez[MR_INVIS] := 0;
2152 FSpawnInvul := 0;
2153 FBerserk := 0;
2154 end;
2156 // Но от остального спасает:
2157 if FMegaRulez[MR_INVUL] >= gTime then
2158 Exit;
2160 // Чит-код "ГОРЕЦ":
2161 if FGodMode then
2162 Exit;
2164 // Если есть урон своим, или ранил сам себя, или тебя ранил противник:
2165 if LongBool(gGameSettings.Options and GAME_OPTION_TEAMDAMAGE) or
2166 (SpawnerUID = FUID) or
2167 (not SameTeam(FUID, SpawnerUID)) then
2168 begin
2169 FLastSpawnerUID := SpawnerUID;
2171 // Кровь (пузырьки, если в воде):
2172 if gBloodCount > 0 then
2173 begin
2174 c := Min(value, 200)*gBloodCount + Random(Min(value, 200) div 2);
2175 if value div 4 <= c then
2176 c := c - (value div 4)
2177 else
2178 c := 0;
2180 if (t = HIT_SOME) and (vx = 0) and (vy = 0) then
2181 MakeBloodSimple(c)
2182 else
2183 case t of
2184 HIT_TRAP, HIT_ACID, HIT_FLAME, HIT_SELF: MakeBloodSimple(c);
2185 HIT_BFG, HIT_ROCKET, HIT_SOME: MakeBloodVector(c, vx, vy);
2186 end;
2188 if t = HIT_WATER then
2189 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
2190 FObj.Y+PLAYER_RECT.Y-4, value div 2, 8, 4);
2191 end;
2193 // Буфер урона:
2194 if FAlive then
2195 Inc(FDamageBuffer, value);
2197 // Вспышка боли:
2198 if gFlash <> 0 then
2199 FPain := FPain + value;
2200 end;
2202 if g_Game_IsServer and g_Game_IsNet then
2203 begin
2204 MH_SEND_PlayerDamage(FUID, t, SpawnerUID, value, vx, vy);
2205 MH_SEND_PlayerStats(FUID);
2206 MH_SEND_PlayerPos(False, FUID);
2207 end;
2208 end;
2210 function TPlayer.Heal(value: Word; Soft: Boolean): Boolean;
2211 begin
2212 Result := False;
2213 if g_Game_IsClient then
2214 Exit;
2215 if not FAlive then
2216 Exit;
2218 if Soft and (FHealth < PLAYER_HP_SOFT) then
2219 begin
2220 IncMax(FHealth, value, PLAYER_HP_SOFT);
2221 Result := True;
2222 end;
2223 if (not Soft) and (FHealth < PLAYER_HP_LIMIT) then
2224 begin
2225 IncMax(FHealth, value, PLAYER_HP_LIMIT);
2226 Result := True;
2227 end;
2229 if Result and g_Game_IsServer and g_Game_IsNet then
2230 MH_SEND_PlayerStats(FUID);
2231 end;
2233 destructor TPlayer.Destroy();
2234 begin
2235 if (gPlayer1 <> nil) and (gPlayer1.FUID = FUID) then
2236 gPlayer1 := nil;
2237 if (gPlayer2 <> nil) and (gPlayer2.FUID = FUID) then
2238 gPlayer2 := nil;
2240 FSawSound.Free();
2241 FSawSoundIdle.Free();
2242 FSawSoundHit.Free();
2243 FSawSoundSelect.Free();
2244 FFlameSoundOn.Free();
2245 FFlameSoundOff.Free();
2246 FFlameSoundWork.Free();
2247 FJetSoundFly.Free();
2248 FJetSoundOn.Free();
2249 FJetSoundOff.Free();
2250 FModel.Free();
2251 FPunchAnim.Free();
2253 inherited;
2254 end;
2256 procedure TPlayer.DoPunch();
2257 begin
2258 FPunchAnim.Reset;
2259 FPunchAnim.Enable;
2260 end;
2262 procedure TPlayer.Fire();
2263 var
2264 f, DidFire: Boolean;
2265 wx, wy, xd, yd: Integer;
2266 locobj: TObj;
2267 begin
2268 if g_Game_IsClient then Exit;
2269 // FBFGFireCounter - время перед выстрелом (для BFG)
2270 // FReloading - время после выстрела (для всего)
2272 if FSpectator then
2273 begin
2274 Respawn(False);
2275 Exit;
2276 end;
2278 if FReloading[FCurrWeap] <> 0 then Exit;
2280 DidFire := False;
2282 f := False;
2283 wx := FObj.X+WEAPONPOINT[FDirection].X;
2284 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
2285 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
2286 yd := wy+firediry();
2288 case FCurrWeap of
2289 WEAPON_KASTET:
2290 begin
2291 DoPunch();
2292 if R_BERSERK in FRulez then
2293 begin
2294 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
2295 locobj.X := FObj.X+FObj.Rect.X;
2296 locobj.Y := FObj.Y+FObj.Rect.Y;
2297 locobj.rect.X := 0;
2298 locobj.rect.Y := 0;
2299 locobj.rect.Width := 39;
2300 locobj.rect.Height := 52;
2301 locobj.Vel.X := (xd-wx) div 2;
2302 locobj.Vel.Y := (yd-wy) div 2;
2303 locobj.Accel.X := xd-wx;
2304 locobj.Accel.y := yd-wy;
2306 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
2307 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
2308 else
2309 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
2311 if (gFlash = 1) and (FPain < 50) then FPain := min(FPain + 25, 50);
2312 end
2313 else
2314 begin
2315 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
2316 end;
2318 DidFire := True;
2319 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2320 end;
2322 WEAPON_SAW:
2323 begin
2324 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
2325 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
2326 begin
2327 FSawSoundSelect.Stop();
2328 FSawSound.Stop();
2329 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
2330 end
2331 else if not FSawSoundHit.IsPlaying() then
2332 begin
2333 FSawSoundSelect.Stop();
2334 FSawSound.PlayAt(FObj.X, FObj.Y);
2335 end;
2337 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2338 DidFire := True;
2339 f := True;
2340 end;
2342 WEAPON_PISTOL:
2343 if FAmmo[A_BULLETS] > 0 then
2344 begin
2345 g_Weapon_pistol(wx, wy, xd, yd, FUID);
2346 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2347 Dec(FAmmo[A_BULLETS]);
2348 FFireAngle := FAngle;
2349 f := True;
2350 DidFire := True;
2351 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2352 GameVelX, GameVelY-2, SHELL_BULLET);
2353 end;
2355 WEAPON_SHOTGUN1:
2356 if FAmmo[A_SHELLS] > 0 then
2357 begin
2358 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2359 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', wx, wy);
2360 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2361 Dec(FAmmo[A_SHELLS]);
2362 FFireAngle := FAngle;
2363 f := True;
2364 DidFire := True;
2365 FShellTimer := 10;
2366 FShellType := SHELL_SHELL;
2367 end;
2369 WEAPON_SHOTGUN2:
2370 if FAmmo[A_SHELLS] >= 2 then
2371 begin
2372 g_Weapon_dshotgun(wx, wy, xd, yd, FUID);
2373 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2374 Dec(FAmmo[A_SHELLS], 2);
2375 FFireAngle := FAngle;
2376 f := True;
2377 DidFire := True;
2378 FShellTimer := 13;
2379 FShellType := SHELL_DBLSHELL;
2380 end;
2382 WEAPON_CHAINGUN:
2383 if FAmmo[A_BULLETS] > 0 then
2384 begin
2385 g_Weapon_mgun(wx, wy, xd, yd, FUID);
2386 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', wx, wy);
2387 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2388 Dec(FAmmo[A_BULLETS]);
2389 FFireAngle := FAngle;
2390 f := True;
2391 DidFire := True;
2392 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2393 GameVelX, GameVelY-2, SHELL_BULLET);
2394 end;
2396 WEAPON_ROCKETLAUNCHER:
2397 if FAmmo[A_ROCKETS] > 0 then
2398 begin
2399 g_Weapon_rocket(wx, wy, xd, yd, FUID);
2400 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2401 Dec(FAmmo[A_ROCKETS]);
2402 FFireAngle := FAngle;
2403 f := True;
2404 DidFire := True;
2405 end;
2407 WEAPON_PLASMA:
2408 if FAmmo[A_CELLS] > 0 then
2409 begin
2410 g_Weapon_plasma(wx, wy, xd, yd, FUID);
2411 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2412 Dec(FAmmo[A_CELLS]);
2413 FFireAngle := FAngle;
2414 f := True;
2415 DidFire := True;
2416 end;
2418 WEAPON_BFG:
2419 if (FAmmo[A_CELLS] >= 40) and (FBFGFireCounter = -1) then
2420 begin
2421 FBFGFireCounter := 17;
2422 if not FNoReload then
2423 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', FObj.X, FObj.Y);
2424 Dec(FAmmo[A_CELLS], 40);
2425 DidFire := True;
2426 end;
2428 WEAPON_SUPERPULEMET:
2429 if FAmmo[A_SHELLS] > 0 then
2430 begin
2431 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2432 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', wx, wy);
2433 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2434 Dec(FAmmo[A_SHELLS]);
2435 FFireAngle := FAngle;
2436 f := True;
2437 DidFire := True;
2438 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2439 GameVelX, GameVelY-2, SHELL_SHELL);
2440 end;
2442 WEAPON_FLAMETHROWER:
2443 if FAmmo[A_FUEL] > 0 then
2444 begin
2445 g_Weapon_flame(wx, wy, xd, yd, FUID);
2446 FlamerOn;
2447 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2448 Dec(FAmmo[A_FUEL]);
2449 FFireAngle := FAngle;
2450 f := True;
2451 DidFire := True;
2452 end
2453 else
2454 begin
2455 FlamerOff;
2456 if g_Game_IsNet and g_Game_IsServer then MH_SEND_PlayerStats(FUID);
2457 end;
2458 end;
2460 if g_Game_IsNet then
2461 begin
2462 if DidFire then
2463 begin
2464 if FCurrWeap <> WEAPON_BFG then
2465 MH_SEND_PlayerFire(FUID, FCurrWeap, wx, wy, xd, yd, LastShotID)
2466 else
2467 if not FNoReload then
2468 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_WEAPON_STARTFIREBFG');
2469 end;
2471 MH_SEND_PlayerStats(FUID);
2472 end;
2474 if not f then Exit;
2476 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
2477 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
2478 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
2479 end;
2481 function TPlayer.GetAmmoByWeapon(Weapon: Byte): Word;
2482 begin
2483 case Weapon of
2484 WEAPON_PISTOL, WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS];
2485 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS];
2486 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS];
2487 WEAPON_PLASMA, WEAPON_BFG: Result := FAmmo[A_CELLS];
2488 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL];
2489 else Result := 0;
2490 end;
2491 end;
2493 function TPlayer.HeadInLiquid(XInc, YInc: Integer): Boolean;
2494 begin
2495 Result := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X+XInc, FObj.Y+PLAYER_HEADRECT.Y+YInc,
2496 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
2497 PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, True);
2498 end;
2500 procedure TPlayer.FlamerOn;
2501 begin
2502 FFlameSoundOff.Stop();
2503 FFlameSoundOff.SetPosition(0);
2504 if FFlaming then
2505 begin
2506 if (not FFlameSoundOn.IsPlaying()) and (not FFlameSoundWork.IsPlaying()) then
2507 FFlameSoundWork.PlayAt(FObj.X, FObj.Y);
2508 end
2509 else
2510 begin
2511 FFlameSoundOn.PlayAt(FObj.X, FObj.Y);
2512 FFlaming := True;
2513 end;
2514 end;
2516 procedure TPlayer.FlamerOff;
2517 begin
2518 if FFlaming then
2519 begin
2520 FFlameSoundOn.Stop();
2521 FFlameSoundOn.SetPosition(0);
2522 FFlameSoundWork.Stop();
2523 FFlameSoundWork.SetPosition(0);
2524 FFlameSoundOff.PlayAt(FObj.X, FObj.Y);
2525 FFlaming := False;
2526 end;
2527 end;
2529 procedure TPlayer.JetpackOn;
2530 begin
2531 FJetSoundFly.Stop;
2532 FJetSoundOff.Stop;
2533 FJetSoundOn.SetPosition(0);
2534 FJetSoundOn.PlayAt(FObj.X, FObj.Y);
2535 FlySmoke(8);
2536 end;
2538 procedure TPlayer.JetpackOff;
2539 begin
2540 FJetSoundFly.Stop;
2541 FJetSoundOn.Stop;
2542 FJetSoundOff.SetPosition(0);
2543 FJetSoundOff.PlayAt(FObj.X, FObj.Y);
2544 end;
2546 procedure TPlayer.CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
2547 begin
2548 if Timeout <= 0 then
2549 exit;
2550 if (FMegaRulez[MR_SUIT] > gTime) or (FMegaRulez[MR_INVUL] > gTime) then
2551 exit; // Не загораемся когда есть защита
2552 if g_Obj_CollidePanel(@FObj, 0, 0, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2) then
2553 exit; // Не подгораем в воде на всякий случай
2554 if FFireTime <= 0 then
2555 g_Sound_PlayExAt('SOUND_IGNITE', FObj.X, FObj.Y);
2556 FFireTime := Timeout;
2557 FFireAttacker := Attacker;
2558 if g_Game_IsNet and g_Game_IsServer then
2559 MH_SEND_PlayerStats(FUID);
2560 end;
2562 procedure TPlayer.Jump();
2563 begin
2564 if gFly or FJetpack then
2565 begin
2566 // Полет (чит-код или джетпак):
2567 if FObj.Vel.Y > -VEL_FLY then
2568 FObj.Vel.Y := FObj.Vel.Y - 3;
2569 if FJetpack then
2570 begin
2571 if FJetFuel > 0 then
2572 Dec(FJetFuel);
2573 if (FJetFuel < 1) and g_Game_IsServer then
2574 begin
2575 FJetpack := False;
2576 JetpackOff;
2577 if g_Game_IsNet then
2578 MH_SEND_PlayerStats(FUID);
2579 end;
2580 end;
2581 Exit;
2582 end;
2584 // Не включать джетпак в режиме прохождения сквозь стены
2585 if FGhost then
2586 FCanJetpack := False;
2588 // Прыгаем или всплываем:
2589 if (CollideLevel(0, 1) or
2590 g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y+36, PLAYER_RECT.Width,
2591 PLAYER_RECT.Height-33, PANEL_STEP, False)
2592 ) and (FObj.Accel.Y = 0) then // Не прыгать, если есть вертикальное ускорение
2593 begin
2594 FObj.Vel.Y := -VEL_JUMP;
2595 FCanJetpack := False;
2596 end
2597 else
2598 begin
2599 if BodyInLiquid(0, 0) then
2600 FObj.Vel.Y := -VEL_SW
2601 else if (FJetFuel > 0) and FCanJetpack and
2602 g_Game_IsServer and (not g_Obj_CollideLiquid(@FObj, 0, 0)) then
2603 begin
2604 FJetpack := True;
2605 JetpackOn;
2606 if g_Game_IsNet then
2607 MH_SEND_PlayerStats(FUID);
2608 end;
2609 end;
2610 end;
2612 procedure TPlayer.Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
2613 var
2614 a, i, k, ab, ar: Byte;
2615 s: String;
2616 mon: TMonster;
2617 plr: TPlayer;
2618 srv, netsrv: Boolean;
2619 DoFrags: Boolean;
2620 OldLR: Byte;
2621 KP: TPlayer;
2622 it: PItem;
2624 procedure PushItem(t: Byte);
2625 var
2626 id: DWORD;
2627 begin
2628 id := g_Items_Create(FObj.X, FObj.Y, t, True, False);
2629 it := g_Items_ByIdx(id);
2630 if KillType = K_EXTRAHARDKILL then // -7..+7; -8..0
2631 begin
2632 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-7+Random(15),
2633 (FObj.Vel.Y div 2)-Random(9));
2634 it.positionChanged(); // this updates spatial accelerators
2635 end
2636 else
2637 begin
2638 if KillType = K_HARDKILL then // -5..+5; -5..0
2639 begin
2640 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-5+Random(11),
2641 (FObj.Vel.Y div 2)-Random(6));
2642 end
2643 else // -3..+3; -3..0
2644 begin
2645 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-3+Random(7),
2646 (FObj.Vel.Y div 2)-Random(4));
2647 end;
2648 it.positionChanged(); // this updates spatial accelerators
2649 end;
2651 if g_Game_IsNet and g_Game_IsServer then
2652 MH_SEND_ItemSpawn(True, id);
2653 end;
2655 begin
2656 DoFrags := (gGameSettings.MaxLives = 0) or (gGameSettings.GameMode = GM_COOP);
2657 Srv := g_Game_IsServer;
2658 Netsrv := g_Game_IsServer and g_Game_IsNet;
2659 if Srv then FDeath := FDeath + 1;
2660 if FAlive then
2661 begin
2662 if FGhost then
2663 FGhost := False;
2664 if not FPhysics then
2665 FPhysics := True;
2666 FAlive := False;
2667 end;
2668 FShellTimer := -1;
2670 if (gGameSettings.MaxLives > 0) and Srv and (gLMSRespawn = LMS_RESPAWN_NONE) then
2671 begin
2672 if FLives > 0 then FLives := FLives - 1;
2673 if FLives = 0 then FNoRespawn := True;
2674 end;
2676 // Номер типа смерти:
2677 a := 1;
2678 case KillType of
2679 K_SIMPLEKILL: a := 1;
2680 K_HARDKILL: a := 2;
2681 K_EXTRAHARDKILL: a := 3;
2682 K_FALLKILL: a := 4;
2683 end;
2685 // Звук смерти:
2686 if not FModel.PlaySound(MODELSOUND_DIE, a, FObj.X, FObj.Y) then
2687 for i := 1 to 3 do
2688 if FModel.PlaySound(MODELSOUND_DIE, i, FObj.X, FObj.Y) then
2689 Break;
2691 // Время респауна:
2692 if Srv then
2693 case KillType of
2694 K_SIMPLEKILL:
2695 FTime[T_RESPAWN] := gTime + TIME_RESPAWN1;
2696 K_HARDKILL:
2697 FTime[T_RESPAWN] := gTime + TIME_RESPAWN2;
2698 K_EXTRAHARDKILL, K_FALLKILL:
2699 FTime[T_RESPAWN] := gTime + TIME_RESPAWN3;
2700 end;
2702 // Переключаем состояние:
2703 case KillType of
2704 K_SIMPLEKILL:
2705 SetAction(A_DIE1);
2706 K_HARDKILL, K_EXTRAHARDKILL:
2707 SetAction(A_DIE2);
2708 end;
2710 // Реакция монстров на смерть игрока:
2711 if (KillType <> K_FALLKILL) and (Srv) then
2712 g_Monsters_killedp();
2714 if SpawnerUID = FUID then
2715 begin // Самоубился
2716 if Srv and (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2717 begin
2718 Dec(FFrags);
2719 FLastFrag := 0;
2720 end;
2721 g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2722 end
2723 else
2724 if g_GetUIDType(SpawnerUID) = UID_PLAYER then
2725 begin // Убит другим игроком
2726 KP := g_Player_Get(SpawnerUID);
2727 if (KP <> nil) and Srv then
2728 begin
2729 if (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2730 if SameTeam(FUID, SpawnerUID) then
2731 begin
2732 Dec(KP.FFrags);
2733 KP.FLastFrag := 0;
2734 end else
2735 begin
2736 Inc(KP.FFrags);
2737 KP.FragCombo();
2738 end;
2740 if (gGameSettings.GameMode = GM_TDM) and DoFrags then
2741 Inc(gTeamStat[KP.Team].Goals,
2742 IfThen(SameTeam(FUID, SpawnerUID), -1, 1));
2744 if netsrv then MH_SEND_PlayerStats(SpawnerUID);
2745 end;
2747 plr := g_Player_Get(SpawnerUID);
2748 if plr = nil then
2749 s := '?'
2750 else
2751 s := plr.FName;
2753 case KillType of
2754 K_HARDKILL:
2755 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2756 [FName, s]),
2757 gShowKillMsg);
2758 K_EXTRAHARDKILL:
2759 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2760 [FName, s]),
2761 gShowKillMsg);
2762 else
2763 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2764 [FName, s]),
2765 gShowKillMsg);
2766 end;
2767 end
2768 else if g_GetUIDType(SpawnerUID) = UID_MONSTER then
2769 begin // Убит монстром
2770 mon := g_Monsters_ByUID(SpawnerUID);
2771 if mon = nil then
2772 s := '?'
2773 else
2774 s := g_Mons_GetKilledByTypeId(mon.MonsterType);
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 // Особые типы смерти
2792 case t of
2793 HIT_DISCON: ;
2794 HIT_SELF: g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2795 HIT_FALL: g_Console_Add(Format(_lc[I_PLAYER_KILL_FALL], [FName]), True);
2796 HIT_WATER: g_Console_Add(Format(_lc[I_PLAYER_KILL_WATER], [FName]), True);
2797 HIT_ACID: g_Console_Add(Format(_lc[I_PLAYER_KILL_ACID], [FName]), True);
2798 HIT_TRAP: g_Console_Add(Format(_lc[I_PLAYER_KILL_TRAP], [FName]), True);
2799 else g_Console_Add(Format(_lc[I_PLAYER_DIED], [FName]), True);
2800 end;
2802 if Srv then
2803 begin
2804 // Выброс оружия:
2805 for a := WP_FIRST to WP_LAST do
2806 if FWeapon[a] then
2807 begin
2808 case a of
2809 WEAPON_SAW: i := ITEM_WEAPON_SAW;
2810 WEAPON_SHOTGUN1: i := ITEM_WEAPON_SHOTGUN1;
2811 WEAPON_SHOTGUN2: i := ITEM_WEAPON_SHOTGUN2;
2812 WEAPON_CHAINGUN: i := ITEM_WEAPON_CHAINGUN;
2813 WEAPON_ROCKETLAUNCHER: i := ITEM_WEAPON_ROCKETLAUNCHER;
2814 WEAPON_PLASMA: i := ITEM_WEAPON_PLASMA;
2815 WEAPON_BFG: i := ITEM_WEAPON_BFG;
2816 WEAPON_SUPERPULEMET: i := ITEM_WEAPON_SUPERPULEMET;
2817 WEAPON_FLAMETHROWER: i := ITEM_WEAPON_FLAMETHROWER;
2818 else i := 0;
2819 end;
2821 if i <> 0 then
2822 PushItem(i);
2823 end;
2825 // Выброс рюкзака:
2826 if R_ITEM_BACKPACK in FRulez then
2827 PushItem(ITEM_AMMO_BACKPACK);
2829 // Выброс ракетного ранца:
2830 if FJetFuel > 0 then
2831 PushItem(ITEM_JETPACK);
2833 // Выброс ключей:
2834 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) or
2835 (not LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS)) then
2836 begin
2837 if R_KEY_RED in FRulez then
2838 PushItem(ITEM_KEY_RED);
2840 if R_KEY_GREEN in FRulez then
2841 PushItem(ITEM_KEY_GREEN);
2843 if R_KEY_BLUE in FRulez then
2844 PushItem(ITEM_KEY_BLUE);
2845 end;
2847 // Выброс флага:
2848 DropFlag(KillType = K_FALLKILL);
2849 end;
2851 FCorpse := g_Player_CreateCorpse(Self);
2853 if Srv and (gGameSettings.MaxLives > 0) and FNoRespawn and
2854 (gLMSRespawn = LMS_RESPAWN_NONE) then
2855 begin
2856 a := 0;
2857 k := 0;
2858 ar := 0;
2859 ab := 0;
2860 for i := Low(gPlayers) to High(gPlayers) do
2861 begin
2862 if gPlayers[i] = nil then continue;
2863 if (not gPlayers[i].FNoRespawn) and (not gPlayers[i].FSpectator) then
2864 begin
2865 Inc(a);
2866 if gPlayers[i].FTeam = TEAM_RED then Inc(ar)
2867 else if gPlayers[i].FTeam = TEAM_BLUE then Inc(ab);
2868 k := i;
2869 end;
2870 end;
2872 OldLR := gLMSRespawn;
2873 if (gGameSettings.GameMode = GM_COOP) then
2874 begin
2875 if (a = 0) then
2876 begin
2877 // everyone is dead, restart the map
2878 g_Game_Message(_lc[I_MESSAGE_LMS_LOSE], 144);
2879 if Netsrv then
2880 MH_SEND_GameEvent(NET_EV_LMS_LOSE);
2881 gLMSRespawn := LMS_RESPAWN_FINAL;
2882 gLMSRespawnTime := gTime + 5000;
2883 end
2884 else if (a = 1) then
2885 begin
2886 if (gPlayers[k] <> nil) and not (gPlayers[k] is TBot) then
2887 if (gPlayers[k] = gPlayer1) or
2888 (gPlayers[k] = gPlayer2) then
2889 g_Console_Add('*** ' + _lc[I_MESSAGE_LMS_SURVIVOR] + ' ***', True)
2890 else if Netsrv and (gPlayers[k].FClientID >= 0) then
2891 MH_SEND_GameEvent(NET_EV_LMS_SURVIVOR, 0, 'N', gPlayers[k].FClientID);
2892 end;
2893 end
2894 else if (gGameSettings.GameMode = GM_TDM) then
2895 begin
2896 if (ab = 0) and (ar <> 0) then
2897 begin
2898 // blu team ded
2899 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 144);
2900 if Netsrv then
2901 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_RED);
2902 Inc(gTeamStat[TEAM_RED].Goals);
2903 gLMSRespawn := LMS_RESPAWN_FINAL;
2904 gLMSRespawnTime := gTime + 5000;
2905 end
2906 else if (ar = 0) and (ab <> 0) then
2907 begin
2908 // red team ded
2909 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 144);
2910 if Netsrv then
2911 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_BLUE);
2912 Inc(gTeamStat[TEAM_BLUE].Goals);
2913 gLMSRespawn := LMS_RESPAWN_FINAL;
2914 gLMSRespawnTime := gTime + 5000;
2915 end
2916 else if (ar = 0) and (ab = 0) then
2917 begin
2918 // everyone ded
2919 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2920 if Netsrv then
2921 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2922 gLMSRespawn := LMS_RESPAWN_FINAL;
2923 gLMSRespawnTime := gTime + 5000;
2924 end;
2925 end
2926 else if (gGameSettings.GameMode = GM_DM) then
2927 begin
2928 if (a = 1) then
2929 begin
2930 if gPlayers[k] <> nil then
2931 with gPlayers[k] do
2932 begin
2933 // survivor is the winner
2934 g_Game_Message(Format(_lc[I_MESSAGE_LMS_WIN], [AnsiUpperCase(FName)]), 144);
2935 if Netsrv then
2936 MH_SEND_GameEvent(NET_EV_LMS_WIN, 0, FName);
2937 Inc(FFrags);
2938 end;
2939 gLMSRespawn := LMS_RESPAWN_FINAL;
2940 gLMSRespawnTime := gTime + 5000;
2941 end
2942 else if (a = 0) then
2943 begin
2944 // everyone is dead, restart the map
2945 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2946 if Netsrv then
2947 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2948 gLMSRespawn := LMS_RESPAWN_FINAL;
2949 gLMSRespawnTime := gTime + 5000;
2950 end;
2951 end;
2952 if srv and (OldLR = LMS_RESPAWN_NONE) and (gLMSRespawn > LMS_RESPAWN_NONE) then
2953 begin
2954 if NetMode = NET_SERVER then
2955 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime)
2956 else
2957 g_Console_Add(Format(_lc[I_MSG_WARMUP_START], [(gLMSRespawnTime - gTime) div 1000]), True);
2958 end;
2959 end;
2961 if Netsrv then
2962 begin
2963 MH_SEND_PlayerStats(FUID);
2964 MH_SEND_PlayerDeath(FUID, KillType, t, SpawnerUID);
2965 if gGameSettings.GameMode = GM_TDM then MH_SEND_GameStats;
2966 end;
2968 if srv and FNoRespawn then Spectate(True);
2969 FWantsInGame := True;
2970 end;
2972 function TPlayer.BodyInLiquid(XInc, YInc: Integer): Boolean;
2973 begin
2974 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
2975 PLAYER_RECT.Height-20, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, False);
2976 end;
2978 function TPlayer.BodyInAcid(XInc, YInc: Integer): Boolean;
2979 begin
2980 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
2981 PLAYER_RECT.Height-20, PANEL_ACID1 or PANEL_ACID2, False);
2982 end;
2984 procedure TPlayer.MakeBloodSimple(Count: Word);
2985 var Blood: TModelBlood;
2986 begin
2987 Blood := SELF.FModel.GetBlood();
2988 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)+8,
2989 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
2990 Count div 2, 3, -1, 16, (PLAYER_RECT.Height*2 div 3),
2991 Blood.R, Blood.G, Blood.B, Blood.Kind);
2992 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-8,
2993 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
2994 Count div 2, -3, -1, 16, (PLAYER_RECT.Height*2) div 3,
2995 Blood.R, Blood.G, Blood.B, Blood.Kind);
2996 end;
2998 procedure TPlayer.MakeBloodVector(Count: Word; VelX, VelY: Integer);
2999 var Blood: TModelBlood;
3000 begin
3001 Blood := SELF.FModel.GetBlood();
3002 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
3003 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3004 Count, VelX, VelY, 16, (PLAYER_RECT.Height*2) div 3,
3005 Blood.R, Blood.G, Blood.B, Blood.Kind);
3006 end;
3008 procedure TPlayer.QueueWeaponSwitch(Weapon: Byte);
3009 begin
3010 if g_Game_IsClient then Exit;
3011 if Weapon > High(FWeapon) then Exit;
3012 FNextWeap := FNextWeap or (1 shl Weapon);
3013 end;
3015 procedure TPlayer.resetWeaponQueue ();
3016 begin
3017 FNextWeap := 0;
3018 FNextWeapDelay := 0;
3019 end;
3021 function TPlayer.hasAmmoForWeapon (weapon: Byte): Boolean;
3022 begin
3023 result := false;
3024 case weapon of
3025 WEAPON_KASTET, WEAPON_SAW: result := true;
3026 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3027 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3028 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3029 WEAPON_PLASMA, WEAPON_BFG: result := (FAmmo[A_CELLS] > 0);
3030 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3031 else result := (weapon < length(FWeapon));
3032 end;
3033 end;
3035 // return 255 for "no switch"
3036 function TPlayer.getNextWeaponIndex (): Byte;
3037 var
3038 i: Word;
3039 wantThisWeapon: array[0..64] of Boolean;
3040 wwc: Integer = 0; //HACK!
3041 dir, cwi: Integer;
3042 begin
3043 result := 255; // default result: "no switch"
3044 // had weapon cycling on previous frame? remove that flag
3045 if (FNextWeap and $2000) <> 0 then
3046 begin
3047 FNextWeap := FNextWeap and $1FFF;
3048 FNextWeapDelay := 0;
3049 end;
3050 // cycling has priority
3051 if (FNextWeap and $C000) <> 0 then
3052 begin
3053 if (FNextWeap and $8000) <> 0 then
3054 dir := 1
3055 else
3056 dir := -1;
3057 FNextWeap := FNextWeap or $2000; // we need this
3058 if FNextWeapDelay > 0 then
3059 exit; // cooldown time
3060 cwi := FCurrWeap;
3061 for i := 0 to High(FWeapon) do
3062 begin
3063 cwi := (cwi+length(FWeapon)+dir) mod length(FWeapon);
3064 if FWeapon[cwi] then
3065 begin
3066 //e_WriteLog(Format(' SWITCH: cur=%d; new=%d', [FCurrWeap, cwi]), MSG_WARNING);
3067 result := Byte(cwi);
3068 FNextWeapDelay := WEAPON_DELAY;
3069 exit;
3070 end;
3071 end;
3072 resetWeaponQueue();
3073 exit;
3074 end;
3075 // no cycling
3076 for i := 0 to High(wantThisWeapon) do
3077 wantThisWeapon[i] := false;
3078 for i := 0 to High(FWeapon) do
3079 if (FNextWeap and (1 shl i)) <> 0 then
3080 begin
3081 wantThisWeapon[i] := true;
3082 Inc(wwc);
3083 end;
3084 // exclude currently selected weapon from the set
3085 wantThisWeapon[FCurrWeap] := false;
3086 // slow down alterations a little
3087 if wwc > 1 then
3088 begin
3089 //e_WriteLog(Format(' FNextWeap=%x; delay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3090 // more than one weapon requested, assume "alteration" and check alteration delay
3091 if FNextWeapDelay > 0 then
3092 begin
3093 FNextWeap := 0;
3094 exit;
3095 end; // yeah
3096 end;
3097 // do not reset weapon queue, it will be done in `RealizeCurrentWeapon()`
3098 // but clear all counters if no weapon should be switched
3099 if wwc < 1 then
3100 begin
3101 resetWeaponQueue();
3102 exit;
3103 end;
3104 //e_WriteLog(Format('wwc=%d', [wwc]), MSG_WARNING);
3105 // try weapons in descending order
3106 for i := High(FWeapon) downto 0 do
3107 begin
3108 if wantThisWeapon[i] and FWeapon[i] and ((wwc = 1) or hasAmmoForWeapon(i)) then
3109 begin
3110 // i found her!
3111 result := Byte(i);
3112 resetWeaponQueue();
3113 FNextWeapDelay := WEAPON_DELAY * 2; // anyway, 'cause why not
3114 exit;
3115 end;
3116 end;
3117 // no suitable weapon found, so reset the queue, to avoid accidental "queuing" of weapon w/o ammo
3118 resetWeaponQueue();
3119 end;
3121 procedure TPlayer.RealizeCurrentWeapon();
3122 function switchAllowed (): Boolean;
3123 var
3124 i: Byte;
3125 begin
3126 result := false;
3127 if FBFGFireCounter <> -1 then
3128 exit;
3129 if FTime[T_SWITCH] > gTime then
3130 exit;
3131 for i := WP_FIRST to WP_LAST do
3132 if FReloading[i] > 0 then
3133 exit;
3134 result := true;
3135 end;
3137 var
3138 nw: Byte;
3139 begin
3140 //e_WriteLog(Format('***RealizeCurrentWeapon: FNextWeap=%x; FNextWeapDelay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3141 //FNextWeap := FNextWeap and $1FFF;
3142 if FNextWeapDelay > 0 then Dec(FNextWeapDelay); // "alteration delay"
3144 if not switchAllowed then
3145 begin
3146 //HACK for weapon cycling
3147 if (FNextWeap and $E000) <> 0 then FNextWeap := 0;
3148 exit;
3149 end;
3151 nw := getNextWeaponIndex();
3152 if nw = 255 then exit; // don't reset anything here
3153 if nw > High(FWeapon) then
3154 begin
3155 // don't forget to reset queue here!
3156 //e_WriteLog(' RealizeCurrentWeapon: WUTAFUUUU', MSG_WARNING);
3157 resetWeaponQueue();
3158 exit;
3159 end;
3161 if FWeapon[nw] then
3162 begin
3163 FCurrWeap := nw;
3164 FTime[T_SWITCH] := gTime+156;
3165 if FCurrWeap = WEAPON_SAW then FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3166 FModel.SetWeapon(FCurrWeap);
3167 if g_Game_IsNet then MH_SEND_PlayerStats(FUID);
3168 end;
3169 end;
3171 procedure TPlayer.NextWeapon();
3172 begin
3173 if g_Game_IsClient then Exit;
3174 FNextWeap := $8000;
3175 end;
3177 procedure TPlayer.PrevWeapon();
3178 begin
3179 if g_Game_IsClient then Exit;
3180 FNextWeap := $4000;
3181 end;
3183 procedure TPlayer.SetWeapon(W: Byte);
3184 begin
3185 if FCurrWeap <> W then
3186 if W = WEAPON_SAW then
3187 FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3189 FCurrWeap := W;
3190 FModel.SetWeapon(CurrWeap);
3191 resetWeaponQueue();
3192 end;
3194 function TPlayer.PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean;
3196 function allowBerserkSwitching (): Boolean;
3197 begin
3198 if (FBFGFireCounter <> -1) then begin result := false; exit; end;
3199 result := true;
3200 if gBerserkAutoswitch then exit;
3201 if not conIsCheatsEnabled then exit;
3202 result := false;
3203 end;
3205 var
3206 a: Boolean;
3207 begin
3208 Result := False;
3209 if g_Game_IsClient then Exit;
3211 // a = true - место спавна предмета:
3212 a := LongBool(gGameSettings.Options and GAME_OPTION_WEAPONSTAY) and arespawn;
3213 remove := not a;
3215 case ItemType of
3216 ITEM_MEDKIT_SMALL:
3217 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3218 begin
3219 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
3220 Result := True;
3221 remove := True;
3222 FFireTime := 0;
3223 if gFlash = 2 then Inc(FPickup, 5);
3224 end;
3226 ITEM_MEDKIT_LARGE:
3227 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3228 begin
3229 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
3230 Result := True;
3231 remove := True;
3232 FFireTime := 0;
3233 if gFlash = 2 then Inc(FPickup, 5);
3234 end;
3236 ITEM_ARMOR_GREEN:
3237 if FArmor < PLAYER_AP_SOFT then
3238 begin
3239 FArmor := PLAYER_AP_SOFT;
3240 Result := True;
3241 remove := True;
3242 if gFlash = 2 then Inc(FPickup, 5);
3243 end;
3245 ITEM_ARMOR_BLUE:
3246 if FArmor < PLAYER_AP_LIMIT then
3247 begin
3248 FArmor := PLAYER_AP_LIMIT;
3249 Result := True;
3250 remove := True;
3251 if gFlash = 2 then Inc(FPickup, 5);
3252 end;
3254 ITEM_SPHERE_BLUE:
3255 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3256 begin
3257 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
3258 Result := True;
3259 remove := True;
3260 FFireTime := 0;
3261 if gFlash = 2 then Inc(FPickup, 5);
3262 end;
3264 ITEM_SPHERE_WHITE:
3265 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) or (FFireTime > 0) then
3266 begin
3267 if FHealth < PLAYER_HP_LIMIT then
3268 FHealth := PLAYER_HP_LIMIT;
3269 if FArmor < PLAYER_AP_LIMIT then
3270 FArmor := PLAYER_AP_LIMIT;
3271 Result := True;
3272 remove := True;
3273 FFireTime := 0;
3274 if gFlash = 2 then Inc(FPickup, 5);
3275 end;
3277 ITEM_WEAPON_SAW:
3278 if (not FWeapon[WEAPON_SAW]) or ((not arespawn) and (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) then
3279 begin
3280 FWeapon[WEAPON_SAW] := True;
3281 Result := True;
3282 if gFlash = 2 then Inc(FPickup, 5);
3283 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3284 end;
3286 ITEM_WEAPON_SHOTGUN1:
3287 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN1] then
3288 begin
3289 // Нужно, чтобы не взять все пули сразу:
3290 if a and FWeapon[WEAPON_SHOTGUN1] then Exit;
3292 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3293 FWeapon[WEAPON_SHOTGUN1] := True;
3294 Result := True;
3295 if gFlash = 2 then Inc(FPickup, 5);
3296 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3297 end;
3299 ITEM_WEAPON_SHOTGUN2:
3300 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN2] then
3301 begin
3302 if a and FWeapon[WEAPON_SHOTGUN2] then Exit;
3304 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3305 FWeapon[WEAPON_SHOTGUN2] := True;
3306 Result := True;
3307 if gFlash = 2 then Inc(FPickup, 5);
3308 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3309 end;
3311 ITEM_WEAPON_CHAINGUN:
3312 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or not FWeapon[WEAPON_CHAINGUN] then
3313 begin
3314 if a and FWeapon[WEAPON_CHAINGUN] then Exit;
3316 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3317 FWeapon[WEAPON_CHAINGUN] := True;
3318 Result := True;
3319 if gFlash = 2 then Inc(FPickup, 5);
3320 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3321 end;
3323 ITEM_WEAPON_ROCKETLAUNCHER:
3324 if (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or not FWeapon[WEAPON_ROCKETLAUNCHER] then
3325 begin
3326 if a and FWeapon[WEAPON_ROCKETLAUNCHER] then Exit;
3328 IncMax(FAmmo[A_ROCKETS], 2, FMaxAmmo[A_ROCKETS]);
3329 FWeapon[WEAPON_ROCKETLAUNCHER] := True;
3330 Result := True;
3331 if gFlash = 2 then Inc(FPickup, 5);
3332 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3333 end;
3335 ITEM_WEAPON_PLASMA:
3336 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_PLASMA] then
3337 begin
3338 if a and FWeapon[WEAPON_PLASMA] then Exit;
3340 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3341 FWeapon[WEAPON_PLASMA] := True;
3342 Result := True;
3343 if gFlash = 2 then Inc(FPickup, 5);
3344 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3345 end;
3347 ITEM_WEAPON_BFG:
3348 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_BFG] then
3349 begin
3350 if a and FWeapon[WEAPON_BFG] then Exit;
3352 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3353 FWeapon[WEAPON_BFG] := True;
3354 Result := True;
3355 if gFlash = 2 then Inc(FPickup, 5);
3356 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3357 end;
3359 ITEM_WEAPON_SUPERPULEMET:
3360 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SUPERPULEMET] then
3361 begin
3362 if a and FWeapon[WEAPON_SUPERPULEMET] then Exit;
3364 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3365 FWeapon[WEAPON_SUPERPULEMET] := True;
3366 Result := True;
3367 if gFlash = 2 then Inc(FPickup, 5);
3368 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3369 end;
3371 ITEM_WEAPON_FLAMETHROWER:
3372 if (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) or not FWeapon[WEAPON_FLAMETHROWER] then
3373 begin
3374 if a and FWeapon[WEAPON_FLAMETHROWER] then Exit;
3376 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3377 FWeapon[WEAPON_FLAMETHROWER] := True;
3378 Result := True;
3379 if gFlash = 2 then Inc(FPickup, 5);
3380 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3381 end;
3383 ITEM_AMMO_BULLETS:
3384 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3385 begin
3386 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3387 Result := True;
3388 remove := True;
3389 if gFlash = 2 then Inc(FPickup, 5);
3390 end;
3392 ITEM_AMMO_BULLETS_BOX:
3393 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3394 begin
3395 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3396 Result := True;
3397 remove := True;
3398 if gFlash = 2 then Inc(FPickup, 5);
3399 end;
3401 ITEM_AMMO_SHELLS:
3402 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3403 begin
3404 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3405 Result := True;
3406 remove := True;
3407 if gFlash = 2 then Inc(FPickup, 5);
3408 end;
3410 ITEM_AMMO_SHELLS_BOX:
3411 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3412 begin
3413 IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
3414 Result := True;
3415 remove := True;
3416 if gFlash = 2 then Inc(FPickup, 5);
3417 end;
3419 ITEM_AMMO_ROCKET:
3420 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3421 begin
3422 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3423 Result := True;
3424 remove := True;
3425 if gFlash = 2 then Inc(FPickup, 5);
3426 end;
3428 ITEM_AMMO_ROCKET_BOX:
3429 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3430 begin
3431 IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
3432 Result := True;
3433 remove := True;
3434 if gFlash = 2 then Inc(FPickup, 5);
3435 end;
3437 ITEM_AMMO_CELL:
3438 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3439 begin
3440 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3441 Result := True;
3442 remove := True;
3443 if gFlash = 2 then Inc(FPickup, 5);
3444 end;
3446 ITEM_AMMO_CELL_BIG:
3447 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3448 begin
3449 IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
3450 Result := True;
3451 remove := True;
3452 if gFlash = 2 then Inc(FPickup, 5);
3453 end;
3455 ITEM_AMMO_FUELCAN:
3456 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3457 begin
3458 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3459 Result := True;
3460 remove := True;
3461 if gFlash = 2 then Inc(FPickup, 5);
3462 end;
3464 ITEM_AMMO_BACKPACK:
3465 if not(R_ITEM_BACKPACK in FRulez) or
3466 (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
3467 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
3468 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
3469 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
3470 (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) then
3471 begin
3472 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
3473 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
3474 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
3475 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
3476 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
3478 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3479 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3480 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3481 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3482 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3483 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3484 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3485 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3486 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3487 IncMax(FAmmo[A_FUEL], 50, FMaxAmmo[A_FUEL]);
3489 FRulez := FRulez + [R_ITEM_BACKPACK];
3490 Result := True;
3491 remove := True;
3492 if gFlash = 2 then Inc(FPickup, 5);
3493 end;
3495 ITEM_KEY_RED:
3496 if not(R_KEY_RED in FRulez) then
3497 begin
3498 Include(FRulez, R_KEY_RED);
3499 Result := True;
3500 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3501 if gFlash = 2 then Inc(FPickup, 5);
3502 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3503 end;
3505 ITEM_KEY_GREEN:
3506 if not(R_KEY_GREEN in FRulez) then
3507 begin
3508 Include(FRulez, R_KEY_GREEN);
3509 Result := True;
3510 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3511 if gFlash = 2 then Inc(FPickup, 5);
3512 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3513 end;
3515 ITEM_KEY_BLUE:
3516 if not(R_KEY_BLUE in FRulez) then
3517 begin
3518 Include(FRulez, R_KEY_BLUE);
3519 Result := True;
3520 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3521 if gFlash = 2 then Inc(FPickup, 5);
3522 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3523 end;
3525 ITEM_SUIT:
3526 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
3527 begin
3528 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
3529 Result := True;
3530 remove := True;
3531 FFireTime := 0;
3532 if gFlash = 2 then Inc(FPickup, 5);
3533 end;
3535 ITEM_OXYGEN:
3536 if FAir < AIR_MAX then
3537 begin
3538 FAir := AIR_MAX;
3539 Result := True;
3540 remove := True;
3541 if gFlash = 2 then Inc(FPickup, 5);
3542 end;
3544 ITEM_MEDKIT_BLACK:
3545 begin
3546 if not (R_BERSERK in FRulez) then
3547 begin
3548 Include(FRulez, R_BERSERK);
3549 if allowBerserkSwitching then
3550 begin
3551 FCurrWeap := WEAPON_KASTET;
3552 resetWeaponQueue();
3553 FModel.SetWeapon(WEAPON_KASTET);
3554 end;
3555 if gFlash <> 0 then
3556 begin
3557 Inc(FPain, 100);
3558 if gFlash = 2 then Inc(FPickup, 5);
3559 end;
3560 FBerserk := gTime+30000;
3561 Result := True;
3562 remove := True;
3563 FFireTime := 0;
3564 end;
3565 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3566 begin
3567 if FHealth < PLAYER_HP_SOFT then FHealth := PLAYER_HP_SOFT;
3568 FBerserk := gTime+30000;
3569 Result := True;
3570 remove := True;
3571 FFireTime := 0;
3572 end;
3573 end;
3575 ITEM_INVUL:
3576 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
3577 begin
3578 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
3579 FSpawnInvul := 0;
3580 Result := True;
3581 remove := True;
3582 if gFlash = 2 then Inc(FPickup, 5);
3583 end;
3585 ITEM_BOTTLE:
3586 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3587 begin
3588 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
3589 Result := True;
3590 remove := True;
3591 FFireTime := 0;
3592 if gFlash = 2 then Inc(FPickup, 5);
3593 end;
3595 ITEM_HELMET:
3596 if FArmor < PLAYER_AP_LIMIT then
3597 begin
3598 IncMax(FArmor, 5, PLAYER_AP_LIMIT);
3599 Result := True;
3600 remove := True;
3601 if gFlash = 2 then Inc(FPickup, 5);
3602 end;
3604 ITEM_JETPACK:
3605 if FJetFuel < JET_MAX then
3606 begin
3607 FJetFuel := JET_MAX;
3608 Result := True;
3609 remove := True;
3610 if gFlash = 2 then Inc(FPickup, 5);
3611 end;
3613 ITEM_INVIS:
3614 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
3615 begin
3616 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
3617 Result := True;
3618 remove := True;
3619 if gFlash = 2 then Inc(FPickup, 5);
3620 end;
3621 end;
3622 end;
3624 procedure TPlayer.Touch();
3625 begin
3626 if not FAlive then
3627 Exit;
3628 //FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
3629 if FIamBot then
3630 begin
3631 // Бросить флаг товарищу:
3632 if gGameSettings.GameMode = GM_CTF then
3633 DropFlag();
3634 end;
3635 end;
3637 procedure TPlayer.Push(vx, vy: Integer);
3638 begin
3639 if (not FPhysics) and FGhost then
3640 Exit;
3641 FObj.Accel.X := FObj.Accel.X + vx;
3642 FObj.Accel.Y := FObj.Accel.Y + vy;
3643 if g_Game_IsNet and g_Game_IsServer then
3644 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3645 end;
3647 procedure TPlayer.Reset(Force: Boolean);
3648 begin
3649 if Force then
3650 FAlive := False;
3652 FSpawned := False;
3653 FTime[T_RESPAWN] := 0;
3654 FTime[T_FLAGCAP] := 0;
3655 FGodMode := False;
3656 FNoTarget := False;
3657 FNoReload := False;
3658 FFrags := 0;
3659 FLastFrag := 0;
3660 FComboEvnt := -1;
3661 FKills := 0;
3662 FMonsterKills := 0;
3663 FDeath := 0;
3664 FSecrets := 0;
3665 FSpawnInvul := 0;
3666 FCorpse := -1;
3667 FReady := False;
3668 if FNoRespawn then
3669 begin
3670 FSpectator := False;
3671 FGhost := False;
3672 FPhysics := True;
3673 FSpectatePlayer := -1;
3674 FNoRespawn := False;
3675 end;
3676 FLives := gGameSettings.MaxLives;
3678 SetFlag(FLAG_NONE);
3679 end;
3681 procedure TPlayer.SoftReset();
3682 begin
3683 ReleaseKeys();
3685 FDamageBuffer := 0;
3686 FSlopeOld := 0;
3687 FIncCamOld := 0;
3688 FIncCam := 0;
3689 FBFGFireCounter := -1;
3690 FShellTimer := -1;
3691 FPain := 0;
3692 FLastHit := 0;
3693 FLastFrag := 0;
3694 FComboEvnt := -1;
3696 SetFlag(FLAG_NONE);
3697 SetAction(A_STAND, True);
3698 end;
3700 function TPlayer.GetRespawnPoint(): Byte;
3701 var
3702 c: Byte;
3703 begin
3704 Result := 255;
3705 // На будущее: FSpawn - игрок уже играл и перерождается
3707 // Одиночная игра/кооператив
3708 if gGameSettings.GameMode in [GM_COOP, GM_SINGLE] then
3709 begin
3710 if Self = gPlayer1 then
3711 begin
3712 // player 1 should try to spawn on the player 1 point
3713 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3714 Exit(RESPAWNPOINT_PLAYER1)
3715 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3716 Exit(RESPAWNPOINT_PLAYER2);
3717 end
3718 else if Self = gPlayer2 then
3719 begin
3720 // player 2 should try to spawn on the player 2 point
3721 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3722 Exit(RESPAWNPOINT_PLAYER2)
3723 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3724 Exit(RESPAWNPOINT_PLAYER1);
3725 end
3726 else
3727 begin
3728 // other players randomly pick either the first or the second point
3729 c := IfThen((Random(2) = 0), RESPAWNPOINT_PLAYER1, RESPAWNPOINT_PLAYER2);
3730 if g_Map_GetPointCount(c) > 0 then
3731 Exit(c);
3732 // try the other one
3733 c := IfThen((c = RESPAWNPOINT_PLAYER1), RESPAWNPOINT_PLAYER2, RESPAWNPOINT_PLAYER1);
3734 if g_Map_GetPointCount(c) > 0 then
3735 Exit(c);
3736 end;
3737 end;
3739 // Мясоповал
3740 if gGameSettings.GameMode = GM_DM then
3741 begin
3742 // try DM points first
3743 if g_Map_GetPointCount(RESPAWNPOINT_DM) > 0 then
3744 Exit(RESPAWNPOINT_DM);
3745 end;
3747 // Командные
3748 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3749 begin
3750 // try team points first
3751 c := RESPAWNPOINT_DM;
3752 if FTeam = TEAM_RED then
3753 c := RESPAWNPOINT_RED
3754 else if FTeam = TEAM_BLUE then
3755 c := RESPAWNPOINT_BLUE;
3756 if g_Map_GetPointCount(c) > 0 then
3757 Exit(c);
3758 end;
3760 // still haven't found a spawnpoint, try random shit
3761 Result := g_Map_GetRandomPointType();
3762 end;
3764 procedure TPlayer.Respawn(Silent: Boolean; Force: Boolean = False);
3765 var
3766 RespawnPoint: TRespawnPoint;
3767 a, b, c: Byte;
3768 begin
3769 FSlopeOld := 0;
3770 FIncCamOld := 0;
3771 FIncCam := 0;
3772 FBFGFireCounter := -1;
3773 FShellTimer := -1;
3774 FPain := 0;
3775 FLastHit := 0;
3776 FSpawnInvul := 0;
3777 FCorpse := -1;
3779 if not g_Game_IsServer then
3780 Exit;
3781 if FDummy then
3782 Exit;
3783 FWantsInGame := True;
3784 FJustTeleported := True;
3785 if Force then
3786 begin
3787 FTime[T_RESPAWN] := 0;
3788 FAlive := False;
3789 end;
3790 FNetTime := 0;
3791 // if server changes MaxLives we gotta be ready
3792 if gGameSettings.MaxLives = 0 then FNoRespawn := False;
3794 // Еще нельзя возродиться:
3795 if FTime[T_RESPAWN] > gTime then
3796 Exit;
3798 // Просрал все жизни:
3799 if FNoRespawn then
3800 begin
3801 if not FSpectator then Spectate(True);
3802 FWantsInGame := True;
3803 Exit;
3804 end;
3806 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.GameMode <> GM_COOP) then
3807 begin // "Своя игра"
3808 // Берсерк не сохраняется между уровнями:
3809 FRulez := FRulez-[R_BERSERK];
3810 end
3811 else // "Одиночная игра"/"Кооп"
3812 begin
3813 // Берсерк и ключи не сохраняются между уровнями:
3814 FRulez := FRulez-[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE, R_BERSERK];
3815 end;
3817 // Получаем точку спауна игрока:
3818 c := GetRespawnPoint();
3820 ReleaseKeys();
3821 SetFlag(FLAG_NONE);
3823 // Воскрешение без оружия:
3824 if not FAlive then
3825 begin
3826 FHealth := Round(PLAYER_HP_SOFT * (FHandicap / 100));
3827 FArmor := 0;
3828 FAlive := True;
3829 FAir := AIR_DEF;
3830 FJetFuel := 0;
3832 for a := WP_FIRST to WP_LAST do
3833 begin
3834 FWeapon[a] := False;
3835 FReloading[a] := 0;
3836 end;
3838 FWeapon[WEAPON_PISTOL] := True;
3839 FWeapon[WEAPON_KASTET] := True;
3840 FCurrWeap := WEAPON_PISTOL;
3841 resetWeaponQueue();
3843 FModel.SetWeapon(FCurrWeap);
3845 for b := A_BULLETS to A_HIGH do
3846 FAmmo[b] := 0;
3848 FAmmo[A_BULLETS] := 50;
3850 FMaxAmmo[A_BULLETS] := AmmoLimits[0, A_BULLETS];
3851 FMaxAmmo[A_SHELLS] := AmmoLimits[0, A_SHELLS];
3852 FMaxAmmo[A_ROCKETS] := AmmoLimits[0, A_SHELLS];
3853 FMaxAmmo[A_CELLS] := AmmoLimits[0, A_CELLS];
3854 FMaxAmmo[A_FUEL] := AmmoLimits[0, A_FUEL];
3856 if (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) and
3857 LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS) then
3858 FRulez := [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE]
3859 else
3860 FRulez := [];
3861 end;
3863 // Получаем координаты точки возрождения:
3864 if not g_Map_GetPoint(c, RespawnPoint) then
3865 begin
3866 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3867 Exit;
3868 end;
3870 // Установка координат и сброс всех параметров:
3871 FObj.X := RespawnPoint.X-PLAYER_RECT.X;
3872 FObj.Y := RespawnPoint.Y-PLAYER_RECT.Y;
3873 FObj.oldX := FObj.X; // don't interpolate after respawn
3874 FObj.oldY := FObj.Y;
3875 FObj.Vel.X := 0;
3876 FObj.Vel.Y := 0;
3877 FObj.Accel.X := 0;
3878 FObj.Accel.Y := 0;
3880 FDirection := RespawnPoint.Direction;
3881 if FDirection = TDirection.D_LEFT then
3882 FAngle := 180
3883 else
3884 FAngle := 0;
3886 SetAction(A_STAND, True);
3887 FModel.Direction := FDirection;
3889 for a := Low(FTime) to High(FTime) do
3890 FTime[a] := 0;
3892 for a := Low(FMegaRulez) to High(FMegaRulez) do
3893 FMegaRulez[a] := 0;
3895 // Respawn invulnerability
3896 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.SpawnInvul > 0) then
3897 begin
3898 FMegaRulez[MR_INVUL] := gTime + gGameSettings.SpawnInvul * 1000;
3899 FSpawnInvul := FMegaRulez[MR_INVUL];
3900 end;
3902 FDamageBuffer := 0;
3903 FJetpack := False;
3904 FCanJetpack := False;
3905 FFlaming := False;
3906 FFireTime := 0;
3907 FFirePainTime := 0;
3908 FFireAttacker := 0;
3910 // Анимация возрождения:
3911 if (not gLoadGameMode) and (not Silent) then
3912 r_GFX_OnceAnim(
3913 R_GFX_TELEPORT_FAST,
3914 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
3915 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
3916 );
3918 FSpectator := False;
3919 FGhost := False;
3920 FPhysics := True;
3921 FSpectatePlayer := -1;
3922 FSpawned := True;
3924 if (gPlayer1 = nil) and (gSpectLatchPID1 = FUID) then
3925 gPlayer1 := self;
3926 if (gPlayer2 = nil) and (gSpectLatchPID2 = FUID) then
3927 gPlayer2 := self;
3929 if g_Game_IsNet then
3930 begin
3931 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3932 MH_SEND_PlayerStats(FUID, NET_EVERYONE);
3933 if not Silent then
3934 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
3935 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32,
3936 0, NET_GFX_TELE);
3937 end;
3938 end;
3940 procedure TPlayer.Spectate(NoMove: Boolean = False);
3941 begin
3942 if FAlive then
3943 Kill(K_EXTRAHARDKILL, FUID, HIT_SOME)
3944 else if (not NoMove) then
3945 begin
3946 GameX := gMapInfo.Width div 2;
3947 GameY := gMapInfo.Height div 2;
3948 end;
3949 FXTo := GameX;
3950 FYTo := GameY;
3952 FAlive := False;
3953 FSpectator := True;
3954 FGhost := True;
3955 FPhysics := False;
3956 FWantsInGame := False;
3957 FSpawned := False;
3958 FCorpse := -1;
3960 if FNoRespawn then
3961 begin
3962 if Self = gPlayer1 then
3963 begin
3964 gSpectLatchPID1 := FUID;
3965 gPlayer1 := nil;
3966 end
3967 else if Self = gPlayer2 then
3968 begin
3969 gSpectLatchPID2 := FUID;
3970 gPlayer2 := nil;
3971 end;
3972 end;
3974 if g_Game_IsNet then
3975 MH_SEND_PlayerStats(FUID);
3976 end;
3978 procedure TPlayer.SwitchNoClip;
3979 begin
3980 if not FAlive then
3981 Exit;
3982 FGhost := not FGhost;
3983 FPhysics := not FGhost;
3984 if FGhost then
3985 begin
3986 FXTo := FObj.X;
3987 FYTo := FObj.Y;
3988 end else
3989 begin
3990 FObj.Accel.X := 0;
3991 FObj.Accel.Y := 0;
3992 end;
3993 end;
3995 procedure TPlayer.Run(Direction: TDirection);
3996 var
3997 a, b: Integer;
3998 begin
3999 if MAX_RUNVEL > 8 then
4000 FlySmoke();
4002 // Бежим:
4003 if Direction = TDirection.D_LEFT then
4004 begin
4005 if FObj.Vel.X > -MAX_RUNVEL then
4006 FObj.Vel.X := FObj.Vel.X - (MAX_RUNVEL shr 3);
4007 end
4008 else
4009 if FObj.Vel.X < MAX_RUNVEL then
4010 FObj.Vel.X := FObj.Vel.X + (MAX_RUNVEL shr 3);
4012 // Возможно, пинаем куски:
4013 if (FObj.Vel.X <> 0) and (gGibs <> nil) then
4014 begin
4015 b := Abs(FObj.Vel.X);
4016 if b > 1 then b := b * (Random(8 div b) + 1);
4017 for a := 0 to High(gGibs) do
4018 begin
4019 if gGibs[a].alive and
4020 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
4021 FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
4022 begin
4023 // Пинаем куски
4024 if FObj.Vel.X < 0 then
4025 begin
4026 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)+120) // налево
4027 end
4028 else
4029 begin
4030 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)); // направо
4031 end;
4032 gGibs[a].positionChanged(); // this updates spatial accelerators
4033 end;
4034 end;
4035 end;
4037 SetAction(A_WALK);
4038 end;
4040 procedure TPlayer.SeeDown();
4041 begin
4042 SetAction(A_SEEDOWN);
4044 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTDOWN else FAngle := ANGLE_RIGHTDOWN;
4046 if FIncCam > -120 then DecMin(FIncCam, 5, -120);
4047 end;
4049 procedure TPlayer.SeeUp();
4050 begin
4051 SetAction(A_SEEUP);
4053 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTUP else FAngle := ANGLE_RIGHTUP;
4055 if FIncCam < 120 then IncMax(FIncCam, 5, 120);
4056 end;
4058 procedure TPlayer.SetAction(Action: Byte; Force: Boolean = False);
4059 var
4060 Prior: Byte;
4061 begin
4062 case Action of
4063 A_WALK: Prior := 3;
4064 A_DIE1: Prior := 5;
4065 A_DIE2: Prior := 5;
4066 A_ATTACK: Prior := 2;
4067 A_SEEUP: Prior := 1;
4068 A_SEEDOWN: Prior := 1;
4069 A_ATTACKUP: Prior := 2;
4070 A_ATTACKDOWN: Prior := 2;
4071 A_PAIN: Prior := 4;
4072 else Prior := 0;
4073 end;
4075 if (Prior > FActionPrior) or Force then
4076 if not ((Prior = 2) and (FCurrWeap = WEAPON_SAW)) then
4077 begin
4078 FActionPrior := Prior;
4079 FActionAnim := Action;
4080 FActionForce := Force;
4081 FActionChanged := True;
4082 end;
4084 if Action in [A_ATTACK, A_ATTACKUP, A_ATTACKDOWN] then FModel.SetFire(True);
4085 end;
4087 function TPlayer.StayOnStep(XInc, YInc: Integer): Boolean;
4088 begin
4089 Result := not g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height-1,
4090 PLAYER_RECT.Width, 1, PANEL_STEP, False)
4091 and g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height,
4092 PLAYER_RECT.Width, 1, PANEL_STEP, False);
4093 end;
4095 function TPlayer.TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
4096 begin
4097 Result := False;
4099 if g_CollideLevel(X, Y, PLAYER_RECT.Width, PLAYER_RECT.Height) then
4100 begin
4101 g_Sound_PlayExAt('SOUND_GAME_NOTELEPORT', FObj.X, FObj.Y);
4102 if g_Game_IsServer and g_Game_IsNet then
4103 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_GAME_NOTELEPORT');
4104 Exit;
4105 end;
4107 FJustTeleported := True;
4109 if not silent then
4110 begin
4111 g_Sound_PlayExAt('SOUND_GAME_TELEPORT', FObj.X, FObj.Y);
4112 r_GFX_OnceAnim(
4113 R_GFX_TELEPORT_FAST,
4114 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4115 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4116 );
4117 if g_Game_IsServer and g_Game_IsNet then
4118 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4119 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 1,
4120 NET_GFX_TELE);
4121 end;
4123 FObj.X := X-PLAYER_RECT.X;
4124 FObj.Y := Y-PLAYER_RECT.Y;
4125 FObj.oldX := FObj.X; // don't interpolate after respawn
4126 FObj.oldY := FObj.Y;
4127 if FAlive and FGhost then
4128 begin
4129 FXTo := FObj.X;
4130 FYTo := FObj.Y;
4131 end;
4133 if not g_Game_IsNet then
4134 begin
4135 if dir = 1 then
4136 begin
4137 SetDirection(TDirection.D_LEFT);
4138 FAngle := 180;
4139 end
4140 else
4141 if dir = 2 then
4142 begin
4143 SetDirection(TDirection.D_RIGHT);
4144 FAngle := 0;
4145 end
4146 else
4147 if dir = 3 then
4148 begin // обратное
4149 if FDirection = TDirection.D_RIGHT then
4150 begin
4151 SetDirection(TDirection.D_LEFT);
4152 FAngle := 180;
4153 end
4154 else
4155 begin
4156 SetDirection(TDirection.D_RIGHT);
4157 FAngle := 0;
4158 end;
4159 end;
4160 end;
4162 if not silent then
4163 begin
4164 r_GFX_OnceAnim(
4165 R_GFX_TELEPORT_FAST,
4166 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4167 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4168 );
4169 if g_Game_IsServer and g_Game_IsNet then
4170 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4171 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 0,
4172 NET_GFX_TELE);
4173 end;
4175 Result := True;
4176 end;
4178 function nonz(a: Single): Single;
4179 begin
4180 if a <> 0 then
4181 Result := a
4182 else
4183 Result := 1;
4184 end;
4186 function TPlayer.refreshCorpse(): Boolean;
4187 var
4188 i: Integer;
4189 begin
4190 Result := False;
4191 FCorpse := -1;
4192 if FAlive or FSpectator then
4193 Exit;
4194 if (gCorpses = nil) or (Length(gCorpses) = 0) then
4195 Exit;
4196 for i := 0 to High(gCorpses) do
4197 if gCorpses[i] <> nil then
4198 if gCorpses[i].FPlayerUID = FUID then
4199 begin
4200 Result := True;
4201 FCorpse := i;
4202 break;
4203 end;
4204 end;
4206 function TPlayer.getCameraObj(): TObj;
4207 begin
4208 if (not FAlive) and (not FSpectator) and
4209 (FCorpse >= 0) and (FCorpse < Length(gCorpses)) and
4210 (gCorpses[FCorpse] <> nil) and (gCorpses[FCorpse].FPlayerUID = FUID) then
4211 begin
4212 gCorpses[FCorpse].FObj.slopeUpLeft := FObj.slopeUpLeft;
4213 Result := gCorpses[FCorpse].FObj;
4214 end
4215 else
4216 begin
4217 Result := FObj;
4218 end;
4219 end;
4221 procedure TPlayer.PreUpdate();
4222 begin
4223 FSlopeOld := FObj.slopeUpLeft;
4224 FIncCamOld := FIncCam;
4225 FObj.oldX := FObj.X;
4226 FObj.oldY := FObj.Y;
4227 end;
4229 procedure TPlayer.Update();
4230 var
4231 b: Byte;
4232 i, ii, wx, wy, xd, yd, k: Integer;
4233 blockmon, headwater, dospawn: Boolean;
4234 NetServer: Boolean;
4235 AnyServer: Boolean;
4236 SetSpect: Boolean;
4237 begin
4238 NetServer := g_Game_IsNet and g_Game_IsServer;
4239 AnyServer := g_Game_IsServer;
4241 if g_Game_IsClient and (NetInterpLevel > 0) then
4242 DoLerp(NetInterpLevel + 1)
4243 else
4244 if FGhost then
4245 DoLerp(4);
4247 if NetServer then
4248 if FClientID >= 0 then
4249 begin
4250 FPing := NetClients[FClientID].Peer^.lastRoundTripTime;
4251 if NetClients[FClientID].Peer^.packetsSent > 0 then
4252 FLoss := Round(100*NetClients[FClientID].Peer^.packetsLost/NetClients[FClientID].Peer^.packetsSent)
4253 else
4254 FLoss := 0;
4255 end else
4256 begin
4257 FPing := 0;
4258 FLoss := 0;
4259 end;
4261 if FAlive then
4262 FPunchAnim.Update;
4263 if FPunchAnim.played then
4264 FPunchAnim.Disable;
4266 if FAlive and (gFly or FJetpack) then
4267 FlySmoke();
4269 if FDirection = TDirection.D_LEFT then
4270 FAngle := 180
4271 else
4272 FAngle := 0;
4274 if FAlive and (not FGhost) then
4275 begin
4276 if FKeys[KEY_UP].Pressed then
4277 SeeUp();
4278 if FKeys[KEY_DOWN].Pressed then
4279 SeeDown();
4280 end;
4282 if (not (FKeys[KEY_UP].Pressed or FKeys[KEY_DOWN].Pressed)) and
4283 (FIncCam <> 0) then
4284 begin
4285 i := g_basic.Sign(FIncCam);
4286 FIncCam := Abs(FIncCam);
4287 DecMin(FIncCam, 5, 0);
4288 FIncCam := FIncCam*i;
4289 end;
4291 // no need to do that each second frame, weapon queue will take care of it
4292 if FAlive and FKeys[KEY_NEXTWEAPON].Pressed and AnyServer then NextWeapon();
4293 if FAlive and FKeys[KEY_PREVWEAPON].Pressed and AnyServer then PrevWeapon();
4295 if gTime mod (GAME_TICK*2) <> 0 then
4296 begin
4297 if (FObj.Vel.X = 0) and FAlive then
4298 begin
4299 if FKeys[KEY_LEFT].Pressed then
4300 Run(TDirection.D_LEFT);
4301 if FKeys[KEY_RIGHT].Pressed then
4302 Run(TDirection.D_RIGHT);
4303 end;
4305 if FPhysics then
4306 begin
4307 g_Obj_Move(@FObj, True, True, True);
4308 positionChanged(); // this updates spatial accelerators
4309 end;
4311 Exit;
4312 end;
4314 FActionChanged := False;
4316 if FAlive then
4317 begin
4318 // Let alive player do some actions
4319 if FKeys[KEY_LEFT].Pressed then Run(TDirection.D_LEFT);
4320 if FKeys[KEY_RIGHT].Pressed then Run(TDirection.D_RIGHT);
4321 //if FKeys[KEY_NEXTWEAPON].Pressed and AnyServer then NextWeapon();
4322 //if FKeys[KEY_PREVWEAPON].Pressed and AnyServer then PrevWeapon();
4323 if FKeys[KEY_FIRE].Pressed and AnyServer then Fire()
4324 else
4325 begin
4326 if AnyServer then
4327 begin
4328 FlamerOff;
4329 if NetServer then MH_SEND_PlayerStats(FUID);
4330 end;
4331 end;
4332 if FKeys[KEY_OPEN].Pressed and AnyServer then Use();
4333 if FKeys[KEY_JUMP].Pressed then Jump()
4334 else
4335 begin
4336 if AnyServer and FJetpack then
4337 begin
4338 FJetpack := False;
4339 JetpackOff;
4340 if NetServer then MH_SEND_PlayerStats(FUID);
4341 end;
4342 FCanJetpack := True;
4343 end;
4344 end
4345 else // Dead
4346 begin
4347 dospawn := False;
4348 if not FGhost then
4349 for k := Low(FKeys) to KEY_CHAT-1 do
4350 begin
4351 if FKeys[k].Pressed then
4352 begin
4353 dospawn := True;
4354 break;
4355 end;
4356 end;
4357 if dospawn then
4358 begin
4359 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
4360 Respawn(False)
4361 else // Single
4362 if (FTime[T_RESPAWN] <= gTime) and
4363 gGameOn and (not FAlive) then
4364 begin
4365 if (g_Player_GetCount() > 1) then
4366 Respawn(False)
4367 else
4368 begin
4369 gExit := EXIT_RESTART;
4370 Exit;
4371 end;
4372 end;
4373 end;
4374 // Dead spectator actions
4375 if FGhost then
4376 begin
4377 if FKeys[KEY_OPEN].Pressed and AnyServer then Fire();
4378 if FKeys[KEY_FIRE].Pressed and AnyServer then
4379 begin
4380 if FSpectator then
4381 begin
4382 if (FSpectatePlayer >= High(gPlayers)) then
4383 FSpectatePlayer := -1
4384 else
4385 begin
4386 SetSpect := False;
4387 for I := FSpectatePlayer + 1 to High(gPlayers) do
4388 if gPlayers[I] <> nil then
4389 if gPlayers[I].alive then
4390 if gPlayers[I].UID <> FUID then
4391 begin
4392 FSpectatePlayer := I;
4393 SetSpect := True;
4394 break;
4395 end;
4397 if not SetSpect then FSpectatePlayer := -1;
4398 end;
4400 ReleaseKeys;
4401 end;
4402 end;
4403 end;
4404 end;
4405 // No clipping
4406 if FGhost then
4407 begin
4408 if FKeys[KEY_UP].Pressed or FKeys[KEY_JUMP].Pressed then
4409 begin
4410 FYTo := FObj.Y - 32;
4411 FSpectatePlayer := -1;
4412 end;
4413 if FKeys[KEY_DOWN].Pressed then
4414 begin
4415 FYTo := FObj.Y + 32;
4416 FSpectatePlayer := -1;
4417 end;
4418 if FKeys[KEY_LEFT].Pressed then
4419 begin
4420 FXTo := FObj.X - 32;
4421 FSpectatePlayer := -1;
4422 end;
4423 if FKeys[KEY_RIGHT].Pressed then
4424 begin
4425 FXTo := FObj.X + 32;
4426 FSpectatePlayer := -1;
4427 end;
4429 if (FXTo < -64) then
4430 FXTo := -64
4431 else if (FXTo > gMapInfo.Width + 32) then
4432 FXTo := gMapInfo.Width + 32;
4433 if (FYTo < -72) then
4434 FYTo := -72
4435 else if (FYTo > gMapInfo.Height + 32) then
4436 FYTo := gMapInfo.Height + 32;
4437 end;
4439 if FPhysics then
4440 begin
4441 g_Obj_Move(@FObj, True, True, True);
4442 positionChanged(); // this updates spatial accelerators
4443 end
4444 else
4445 begin
4446 FObj.Vel.X := 0;
4447 FObj.Vel.Y := 0;
4448 if FSpectator then
4449 if (FSpectatePlayer <= High(gPlayers)) and (FSpectatePlayer >= 0) then
4450 if gPlayers[FSpectatePlayer] <> nil then
4451 if gPlayers[FSpectatePlayer].alive then
4452 begin
4453 FXTo := gPlayers[FSpectatePlayer].GameX;
4454 FYTo := gPlayers[FSpectatePlayer].GameY;
4455 end;
4456 end;
4458 blockmon := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X, FObj.Y+PLAYER_HEADRECT.Y,
4459 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
4460 PANEL_BLOCKMON, True);
4461 headwater := HeadInLiquid(0, 0);
4463 // Сопротивление воздуха:
4464 if (not FAlive) or not (FKeys[KEY_LEFT].Pressed or FKeys[KEY_RIGHT].Pressed) then
4465 if FObj.Vel.X <> 0 then
4466 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
4468 if (FLastHit = HIT_TRAP) and (FPain > 90) then FPain := 90;
4469 DecMin(FPain, 5, 0);
4470 DecMin(FPickup, 1, 0);
4472 if FAlive and (FObj.Y > Integer(gMapInfo.Height)+128) and AnyServer then
4473 begin
4474 // Обнулить действия примочек, чтобы фон пропал
4475 FMegaRulez[MR_SUIT] := 0;
4476 FMegaRulez[MR_INVUL] := 0;
4477 FMegaRulez[MR_INVIS] := 0;
4478 Kill(K_FALLKILL, 0, HIT_FALL);
4479 end;
4481 i := 9;
4483 if FAlive then
4484 begin
4485 if FCurrWeap = WEAPON_SAW then
4486 if not (FSawSound.IsPlaying() or FSawSoundHit.IsPlaying() or
4487 FSawSoundSelect.IsPlaying()) then
4488 FSawSoundIdle.PlayAt(FObj.X, FObj.Y);
4490 if FJetpack then
4491 if (not FJetSoundFly.IsPlaying()) and (not FJetSoundOn.IsPlaying()) and
4492 (not FJetSoundOff.IsPlaying()) then
4493 begin
4494 FJetSoundFly.SetPosition(0);
4495 FJetSoundFly.PlayAt(FObj.X, FObj.Y);
4496 end;
4498 for b := WP_FIRST to WP_LAST do
4499 if FReloading[b] > 0 then
4500 if FNoReload then
4501 FReloading[b] := 0
4502 else
4503 Dec(FReloading[b]);
4505 if FShellTimer > -1 then
4506 if FShellTimer = 0 then
4507 begin
4508 if FShellType = SHELL_SHELL then
4509 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4510 GameVelX, GameVelY-2, SHELL_SHELL)
4511 else if FShellType = SHELL_DBLSHELL then
4512 begin
4513 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4514 GameVelX+1, GameVelY-2, SHELL_SHELL);
4515 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4516 GameVelX-1, GameVelY-2, SHELL_SHELL);
4517 end;
4518 FShellTimer := -1;
4519 end else Dec(FShellTimer);
4521 if (FBFGFireCounter > -1) then
4522 if FBFGFireCounter = 0 then
4523 begin
4524 if AnyServer then
4525 begin
4526 wx := FObj.X+WEAPONPOINT[FDirection].X;
4527 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
4528 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
4529 yd := wy+firediry();
4530 g_Weapon_bfgshot(wx, wy, xd, yd, FUID);
4531 if NetServer then MH_SEND_PlayerFire(FUID, WEAPON_BFG, wx, wy, xd, yd);
4532 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4533 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4534 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4535 end;
4537 FReloading[WEAPON_BFG] := WEAPON_RELOAD[WEAPON_BFG];
4538 FBFGFireCounter := -1;
4539 end else
4540 if FNoReload then
4541 FBFGFireCounter := 0
4542 else
4543 Dec(FBFGFireCounter);
4545 if (FMegaRulez[MR_SUIT] < gTime) and AnyServer then
4546 begin
4547 b := g_GetAcidHit(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width, PLAYER_RECT.Height);
4549 if (b > 0) and (gTime mod (15*GAME_TICK) = 0) then Damage(b, 0, 0, 0, HIT_ACID);
4550 end;
4552 if (headwater or blockmon) then
4553 begin
4554 Dec(FAir);
4556 if FAir < -9 then
4557 begin
4558 if AnyServer then Damage(10, 0, 0, 0, HIT_WATER);
4559 FAir := 0;
4560 end
4561 else if (FAir mod 31 = 0) and not blockmon then
4562 begin
4563 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2), FObj.Y+PLAYER_RECT.Y-4, 5+Random(6), 8, 4);
4564 if Random(2) = 0 then
4565 g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
4566 else
4567 g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
4568 end;
4569 end else if FAir < AIR_DEF then
4570 FAir := AIR_DEF;
4572 if FFireTime > 0 then
4573 begin
4574 if BodyInLiquid(0, 0) then
4575 begin
4576 FFireTime := 0;
4577 FFirePainTime := 0;
4578 end
4579 else if FMegaRulez[MR_SUIT] >= gTime then
4580 begin
4581 if FMegaRulez[MR_SUIT] = gTime then
4582 FFireTime := 1;
4583 FFirePainTime := 0;
4584 end
4585 else
4586 begin
4587 OnFireFlame(1);
4588 if FFirePainTime <= 0 then
4589 begin
4590 if g_Game_IsServer then
4591 Damage(2, FFireAttacker, 0, 0, HIT_FLAME);
4592 FFirePainTime := 12 - FFireTime div 12;
4593 end;
4594 FFirePainTime := FFirePainTime - 1;
4595 FFireTime := FFireTime - 1;
4596 if ((FFireTime mod 33) = 0) and (FMegaRulez[MR_INVUL] < gTime) then
4597 FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
4598 if (FFireTime = 0) and g_Game_IsNet and g_Game_IsServer then
4599 MH_SEND_PlayerStats(FUID);
4600 end;
4601 end;
4603 if FDamageBuffer > 0 then
4604 begin
4605 if FDamageBuffer >= 9 then
4606 begin
4607 SetAction(A_PAIN);
4609 if FDamageBuffer < 30 then i := 9
4610 else if FDamageBuffer < 100 then i := 18
4611 else i := 27;
4612 end;
4614 ii := Round(FDamageBuffer*FHealth / nonz(FArmor*(3/4)+FHealth));
4615 FArmor := FArmor-(FDamageBuffer-ii);
4616 FHealth := FHealth-ii;
4617 if FArmor < 0 then
4618 begin
4619 FHealth := FHealth+FArmor;
4620 FArmor := 0;
4621 end;
4623 if AnyServer then
4624 if FHealth <= 0 then
4625 if FHealth > -30 then Kill(K_SIMPLEKILL, FLastSpawnerUID, FLastHit)
4626 else if FHealth > -50 then Kill(K_HARDKILL, FLastSpawnerUID, FLastHit)
4627 else Kill(K_EXTRAHARDKILL, FLastSpawnerUID, FLastHit);
4629 if FAlive and ((FLastHit <> HIT_FLAME) or (FFireTime <= 0)) then
4630 begin
4631 if FDamageBuffer <= 20 then FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y)
4632 else if FDamageBuffer <= 55 then FModel.PlaySound(MODELSOUND_PAIN, 2, FObj.X, FObj.Y)
4633 else if FDamageBuffer <= 120 then FModel.PlaySound(MODELSOUND_PAIN, 3, FObj.X, FObj.Y)
4634 else FModel.PlaySound(MODELSOUND_PAIN, 4, FObj.X, FObj.Y);
4635 end;
4637 FDamageBuffer := 0;
4638 end;
4640 {CollideItem();}
4641 end; // if FAlive then ...
4643 if (FActionAnim = A_PAIN) and (FModel.Animation <> A_PAIN) then
4644 begin
4645 FModel.ChangeAnimation(FActionAnim, FActionForce);
4646 FModel.AnimState.MinLength := i;
4647 end else FModel.ChangeAnimation(FActionAnim, FActionForce and (FModel.Animation <> A_STAND));
4649 if (FModel.AnimState.Played or ((not FActionChanged) and (FModel.Animation = A_WALK)))
4650 then SetAction(A_STAND, True);
4652 if not ((FModel.Animation = A_WALK) and (Abs(FObj.Vel.X) < 4) and not FModel.GetFire()) then FModel.Update;
4654 for b := Low(FKeys) to High(FKeys) do
4655 if FKeys[b].Time = 0 then FKeys[b].Pressed := False else Dec(FKeys[b].Time);
4656 end;
4659 procedure TPlayer.getMapBox (out x, y, w, h: Integer); inline;
4660 begin
4661 x := FObj.X+PLAYER_RECT.X;
4662 y := FObj.Y+PLAYER_RECT.Y;
4663 w := PLAYER_RECT.Width;
4664 h := PLAYER_RECT.Height;
4665 end;
4668 procedure TPlayer.moveBy (dx, dy: Integer); inline;
4669 begin
4670 if (dx <> 0) or (dy <> 0) then
4671 begin
4672 FObj.X += dx;
4673 FObj.Y += dy;
4674 positionChanged();
4675 end;
4676 end;
4679 function TPlayer.Collide(X, Y: Integer; Width, Height: Word): Boolean;
4680 begin
4681 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4682 FObj.Y+PLAYER_RECT.Y,
4683 PLAYER_RECT.Width,
4684 PLAYER_RECT.Height,
4685 X, Y,
4686 Width, Height);
4687 end;
4689 function TPlayer.Collide(Panel: TPanel): Boolean;
4690 begin
4691 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4692 FObj.Y+PLAYER_RECT.Y,
4693 PLAYER_RECT.Width,
4694 PLAYER_RECT.Height,
4695 Panel.X, Panel.Y,
4696 Panel.Width, Panel.Height);
4697 end;
4699 function TPlayer.Collide(X, Y: Integer): Boolean;
4700 begin
4701 X := X-FObj.X-PLAYER_RECT.X;
4702 Y := Y-FObj.Y-PLAYER_RECT.Y;
4703 Result := (x >= 0) and (x <= PLAYER_RECT.Width) and
4704 (y >= 0) and (y <= PLAYER_RECT.Height);
4705 end;
4707 function g_Player_ValidName(Name: string): Boolean;
4708 var
4709 a: Integer;
4710 begin
4711 Result := True;
4713 if gPlayers = nil then Exit;
4715 for a := 0 to High(gPlayers) do
4716 if gPlayers[a] <> nil then
4717 if LowerCase(Name) = LowerCase(gPlayers[a].FName) then
4718 begin
4719 Result := False;
4720 Exit;
4721 end;
4722 end;
4724 procedure TPlayer.SetDirection(Direction: TDirection);
4725 var
4726 d: TDirection;
4727 begin
4728 d := FModel.Direction;
4730 FModel.Direction := Direction;
4731 if d <> Direction then FModel.ChangeAnimation(FModel.Animation, True);
4733 FDirection := Direction;
4734 end;
4736 function TPlayer.GetKeys(): Byte;
4737 begin
4738 Result := 0;
4740 if R_KEY_RED in FRulez then Result := KEY_RED;
4741 if R_KEY_GREEN in FRulez then Result := Result or KEY_GREEN;
4742 if R_KEY_BLUE in FRulez then Result := Result or KEY_BLUE;
4744 if FTeam = TEAM_RED then Result := Result or KEY_REDTEAM;
4745 if FTeam = TEAM_BLUE then Result := Result or KEY_BLUETEAM;
4746 end;
4748 procedure TPlayer.Use();
4749 var
4750 a: Integer;
4751 begin
4752 if FTime[T_USE] > gTime then Exit;
4754 g_Triggers_PressR(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
4755 PLAYER_RECT.Height, FUID, ACTIVATE_PLAYERPRESS);
4757 for a := 0 to High(gPlayers) do
4758 if (gPlayers[a] <> nil) and (gPlayers[a] <> Self) and
4759 gPlayers[a].alive and SameTeam(FUID, gPlayers[a].FUID) and
4760 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4761 FObj.Rect.Width, FObj.Rect.Height, @gPlayers[a].FObj) then
4762 begin
4763 gPlayers[a].Touch();
4764 if g_Game_IsNet and g_Game_IsServer then
4765 MH_SEND_GameEvent(NET_EV_PLAYER_TOUCH, gPlayers[a].FUID);
4766 end;
4768 FTime[T_USE] := gTime+120;
4769 end;
4771 procedure TPlayer.NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
4772 var
4773 locObj: TObj;
4774 F: Boolean;
4775 WX, WY, XD, YD: Integer;
4776 begin
4777 F := False;
4778 WX := X;
4779 WY := Y;
4780 XD := AX;
4781 YD := AY;
4783 case FCurrWeap of
4784 WEAPON_KASTET:
4785 begin
4786 DoPunch();
4787 if R_BERSERK in FRulez then
4788 begin
4789 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
4790 locobj.X := FObj.X+FObj.Rect.X;
4791 locobj.Y := FObj.Y+FObj.Rect.Y;
4792 locobj.rect.X := 0;
4793 locobj.rect.Y := 0;
4794 locobj.rect.Width := 39;
4795 locobj.rect.Height := 52;
4796 locobj.Vel.X := (xd-wx) div 2;
4797 locobj.Vel.Y := (yd-wy) div 2;
4798 locobj.Accel.X := xd-wx;
4799 locobj.Accel.y := yd-wy;
4801 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
4802 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
4803 else
4804 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
4806 if gFlash = 1 then
4807 if FPain < 50 then
4808 FPain := min(FPain + 25, 50);
4809 end else
4810 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
4811 end;
4813 WEAPON_SAW:
4814 begin
4815 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4816 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
4817 begin
4818 FSawSoundSelect.Stop();
4819 FSawSound.Stop();
4820 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
4821 end
4822 else if not FSawSoundHit.IsPlaying() then
4823 begin
4824 FSawSoundSelect.Stop();
4825 FSawSound.PlayAt(FObj.X, FObj.Y);
4826 end;
4827 f := True;
4828 end;
4830 WEAPON_PISTOL:
4831 begin
4832 g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', GameX, Gamey);
4833 FFireAngle := FAngle;
4834 f := True;
4835 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4836 GameVelX, GameVelY-2, SHELL_BULLET);
4837 end;
4839 WEAPON_SHOTGUN1:
4840 begin
4841 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4842 FFireAngle := FAngle;
4843 f := True;
4844 FShellTimer := 10;
4845 FShellType := SHELL_SHELL;
4846 end;
4848 WEAPON_SHOTGUN2:
4849 begin
4850 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN2', Gamex, Gamey);
4851 FFireAngle := FAngle;
4852 f := True;
4853 FShellTimer := 13;
4854 FShellType := SHELL_DBLSHELL;
4855 end;
4857 WEAPON_CHAINGUN:
4858 begin
4859 g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', Gamex, Gamey);
4860 FFireAngle := FAngle;
4861 f := True;
4862 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4863 GameVelX, GameVelY-2, SHELL_BULLET);
4864 end;
4866 WEAPON_ROCKETLAUNCHER:
4867 begin
4868 g_Weapon_Rocket(wx, wy, xd, yd, FUID, WID);
4869 FFireAngle := FAngle;
4870 f := True;
4871 end;
4873 WEAPON_PLASMA:
4874 begin
4875 g_Weapon_Plasma(wx, wy, xd, yd, FUID, WID);
4876 FFireAngle := FAngle;
4877 f := True;
4878 end;
4880 WEAPON_BFG:
4881 begin
4882 g_Weapon_BFGShot(wx, wy, xd, yd, FUID, WID);
4883 FFireAngle := FAngle;
4884 f := True;
4885 end;
4887 WEAPON_SUPERPULEMET:
4888 begin
4889 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4890 FFireAngle := FAngle;
4891 f := True;
4892 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4893 GameVelX, GameVelY-2, SHELL_SHELL);
4894 end;
4896 WEAPON_FLAMETHROWER:
4897 begin
4898 g_Weapon_flame(wx, wy, xd, yd, FUID, WID);
4899 FlamerOn;
4900 FFireAngle := FAngle;
4901 f := True;
4902 end;
4903 end;
4905 if not f then Exit;
4907 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4908 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4909 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4910 end;
4912 procedure TPlayer.DoLerp(Level: Integer = 2);
4913 begin
4914 if FObj.X <> FXTo then FObj.X := Lerp(FObj.X, FXTo, Level);
4915 if FObj.Y <> FYTo then FObj.Y := Lerp(FObj.Y, FYTo, Level);
4916 end;
4918 procedure TPlayer.SetLerp(XTo, YTo: Integer);
4919 var
4920 AX, AY: Integer;
4921 begin
4922 FXTo := XTo;
4923 FYTo := YTo;
4924 if FJustTeleported or (NetInterpLevel < 1) then
4925 begin
4926 FObj.X := XTo;
4927 FObj.Y := YTo;
4928 if FJustTeleported then
4929 begin
4930 FObj.oldX := FObj.X;
4931 FObj.oldY := FObj.Y;
4932 end;
4933 end
4934 else
4935 begin
4936 AX := Abs(FXTo - FObj.X);
4937 AY := Abs(FYTo - FObj.Y);
4938 if (AX > 32) or (AX <= NetInterpLevel) then
4939 FObj.X := FXTo;
4940 if (AY > 32) or (AY <= NetInterpLevel) then
4941 FObj.Y := FYTo;
4942 end;
4943 end;
4945 function TPlayer.FullInLift(XInc, YInc: Integer): Integer;
4946 begin
4947 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
4948 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
4949 PANEL_LIFTUP, False) then Result := -1
4950 else
4951 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
4952 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
4953 PANEL_LIFTDOWN, False) then Result := 1
4954 else Result := 0;
4955 end;
4957 function TPlayer.GetFlag(Flag: Byte): Boolean;
4958 var
4959 s, ts: String;
4960 evtype, a: Byte;
4961 begin
4962 Result := False;
4964 if Flag = FLAG_NONE then
4965 Exit;
4967 if not g_Game_IsServer then Exit;
4969 // Принес чужой флаг на свою базу:
4970 if (Flag = FTeam) and
4971 (gFlags[Flag].State = FLAG_STATE_NORMAL) and
4972 (FFlag <> FLAG_NONE) then
4973 begin
4974 if FFlag = FLAG_RED then
4975 s := _lc[I_PLAYER_FLAG_RED]
4976 else
4977 s := _lc[I_PLAYER_FLAG_BLUE];
4979 evtype := FLAG_STATE_SCORED;
4981 ts := Format('%.4d', [gFlags[FFlag].CaptureTime]);
4982 Insert('.', ts, Length(ts) + 1 - 3);
4983 g_Console_Add(Format(_lc[I_PLAYER_FLAG_CAPTURE], [FName, s, ts]), True);
4985 g_Map_ResetFlag(FFlag);
4986 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_CAPTURE], [AnsiUpperCase(s)]), 144);
4988 if ((Self = gPlayer1) or (Self = gPlayer2)
4989 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
4990 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
4991 a := 0
4992 else
4993 a := 1;
4995 if not sound_cap_flag[a].IsPlaying() then
4996 sound_cap_flag[a].Play();
4998 gTeamStat[FTeam].Goals := gTeamStat[FTeam].Goals + 1;
5000 Result := True;
5001 if g_Game_IsNet then
5002 begin
5003 MH_SEND_FlagEvent(evtype, FFlag, FUID, False);
5004 MH_SEND_GameStats;
5005 end;
5007 gFlags[FFlag].CaptureTime := 0;
5008 SetFlag(FLAG_NONE);
5009 Exit;
5010 end;
5012 // Подобрал свой флаг - вернул его на базу:
5013 if (Flag = FTeam) and
5014 (gFlags[Flag].State = FLAG_STATE_DROPPED) then
5015 begin
5016 if Flag = FLAG_RED then
5017 s := _lc[I_PLAYER_FLAG_RED]
5018 else
5019 s := _lc[I_PLAYER_FLAG_BLUE];
5021 evtype := FLAG_STATE_RETURNED;
5022 gFlags[Flag].CaptureTime := 0;
5024 g_Console_Add(Format(_lc[I_PLAYER_FLAG_RETURN], [FName, s]), True);
5026 g_Map_ResetFlag(Flag);
5027 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
5029 if ((Self = gPlayer1) or (Self = gPlayer2)
5030 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5031 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5032 a := 0
5033 else
5034 a := 1;
5036 if not sound_ret_flag[a].IsPlaying() then
5037 sound_ret_flag[a].Play();
5039 Result := True;
5040 if g_Game_IsNet then
5041 begin
5042 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5043 MH_SEND_GameStats;
5044 end;
5045 Exit;
5046 end;
5048 // Подобрал чужой флаг:
5049 if (Flag <> FTeam) and (FTime[T_FLAGCAP] <= gTime) then
5050 begin
5051 SetFlag(Flag);
5053 if Flag = FLAG_RED then
5054 s := _lc[I_PLAYER_FLAG_RED]
5055 else
5056 s := _lc[I_PLAYER_FLAG_BLUE];
5058 evtype := FLAG_STATE_CAPTURED;
5060 g_Console_Add(Format(_lc[I_PLAYER_FLAG_GET], [FName, s]), True);
5062 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_GET], [AnsiUpperCase(s)]), 144);
5064 gFlags[Flag].State := FLAG_STATE_CAPTURED;
5066 if ((Self = gPlayer1) or (Self = gPlayer2)
5067 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5068 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5069 a := 0
5070 else
5071 a := 1;
5073 if not sound_get_flag[a].IsPlaying() then
5074 sound_get_flag[a].Play();
5076 Result := True;
5077 if g_Game_IsNet then
5078 begin
5079 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5080 MH_SEND_GameStats;
5081 end;
5082 end;
5083 end;
5085 procedure TPlayer.SetFlag(Flag: Byte);
5086 begin
5087 FFlag := Flag;
5088 if FModel <> nil then
5089 FModel.SetFlag(FFlag);
5090 end;
5092 function TPlayer.DropFlag(Silent: Boolean = True): Boolean;
5093 var
5094 s: String;
5095 a: Byte;
5096 begin
5097 Result := False;
5098 if (not g_Game_IsServer) or (FFlag = FLAG_NONE) then
5099 Exit;
5100 FTime[T_FLAGCAP] := gTime + 2000;
5101 with gFlags[FFlag] do
5102 begin
5103 Obj.X := FObj.X;
5104 Obj.Y := FObj.Y;
5105 Direction := FDirection;
5106 State := FLAG_STATE_DROPPED;
5107 Count := FLAG_TIME;
5108 g_Obj_Push(@Obj, (FObj.Vel.X div 2)-2+Random(5),
5109 (FObj.Vel.Y div 2)-2+Random(5));
5110 positionChanged(); // this updates spatial accelerators
5112 if FFlag = FLAG_RED then
5113 s := _lc[I_PLAYER_FLAG_RED]
5114 else
5115 s := _lc[I_PLAYER_FLAG_BLUE];
5117 g_Console_Add(Format(_lc[I_PLAYER_FLAG_DROP], [FName, s]), True);
5118 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_DROP], [AnsiUpperCase(s)]), 144);
5120 if ((Self = gPlayer1) or (Self = gPlayer2)
5121 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5122 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5123 a := 0
5124 else
5125 a := 1;
5127 if (not Silent) and (not sound_lost_flag[a].IsPlaying()) then
5128 sound_lost_flag[a].Play();
5130 if g_Game_IsNet then
5131 MH_SEND_FlagEvent(FLAG_STATE_DROPPED, Flag, FUID, False);
5132 end;
5133 SetFlag(FLAG_NONE);
5134 Result := True;
5135 end;
5137 procedure TPlayer.GetSecret();
5138 begin
5139 if (self = gPlayer1) or (self = gPlayer2) then
5140 begin
5141 g_Console_Add(Format(_lc[I_PLAYER_SECRET], [FName]), True);
5142 g_Sound_PlayEx('SOUND_GAME_SECRET');
5143 end;
5144 Inc(FSecrets);
5145 end;
5147 procedure TPlayer.PressKey(Key: Byte; Time: Word = 1);
5148 begin
5149 Assert(Key <= High(FKeys));
5151 FKeys[Key].Pressed := True;
5152 FKeys[Key].Time := Time;
5153 end;
5155 function TPlayer.IsKeyPressed(K: Byte): Boolean;
5156 begin
5157 Result := FKeys[K].Pressed;
5158 end;
5160 procedure TPlayer.ReleaseKeys();
5161 var
5162 a: Integer;
5163 begin
5164 for a := Low(FKeys) to High(FKeys) do
5165 begin
5166 FKeys[a].Pressed := False;
5167 FKeys[a].Time := 0;
5168 end;
5169 end;
5171 procedure TPlayer.OnDamage(Angle: SmallInt);
5172 begin
5173 end;
5175 function TPlayer.firediry(): Integer;
5176 begin
5177 if FKeys[KEY_UP].Pressed then Result := -42
5178 else if FKeys[KEY_DOWN].Pressed then Result := 19
5179 else Result := 0;
5180 end;
5182 procedure TPlayer.RememberState();
5183 var
5184 i: Integer;
5185 SavedState: TPlayerSavedState;
5186 begin
5187 SavedState.Health := FHealth;
5188 SavedState.Armor := FArmor;
5189 SavedState.Air := FAir;
5190 SavedState.JetFuel := FJetFuel;
5191 SavedState.CurrWeap := FCurrWeap;
5192 SavedState.NextWeap := FNextWeap;
5193 SavedState.NextWeapDelay := FNextWeapDelay;
5194 for i := Low(FWeapon) to High(FWeapon) do
5195 SavedState.Weapon[i] := FWeapon[i];
5196 for i := Low(FAmmo) to High(FAmmo) do
5197 SavedState.Ammo[i] := FAmmo[i];
5198 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5199 SavedState.MaxAmmo[i] := FMaxAmmo[i];
5200 SavedState.Rulez := FRulez - [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5202 FSavedStateNum := -1;
5203 for i := Low(SavedStates) to High(SavedStates) do
5204 if not SavedStates[i].Used then
5205 begin
5206 FSavedStateNum := i;
5207 break;
5208 end;
5209 if FSavedStateNum < 0 then
5210 begin
5211 SetLength(SavedStates, Length(SavedStates) + 1);
5212 FSavedStateNum := High(SavedStates);
5213 end;
5215 SavedState.Used := True;
5216 SavedStates[FSavedStateNum] := SavedState;
5217 end;
5219 procedure TPlayer.RecallState();
5220 var
5221 i: Integer;
5222 SavedState: TPlayerSavedState;
5223 begin
5224 if(FSavedStateNum < 0) or (FSavedStateNum > High(SavedStates)) then
5225 Exit;
5227 SavedState := SavedStates[FSavedStateNum];
5228 SavedStates[FSavedStateNum].Used := False;
5229 FSavedStateNum := -1;
5231 FHealth := SavedState.Health;
5232 FArmor := SavedState.Armor;
5233 FAir := SavedState.Air;
5234 FJetFuel := SavedState.JetFuel;
5235 FCurrWeap := SavedState.CurrWeap;
5236 FNextWeap := SavedState.NextWeap;
5237 FNextWeapDelay := SavedState.NextWeapDelay;
5238 for i := Low(FWeapon) to High(FWeapon) do
5239 FWeapon[i] := SavedState.Weapon[i];
5240 for i := Low(FAmmo) to High(FAmmo) do
5241 FAmmo[i] := SavedState.Ammo[i];
5242 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5243 FMaxAmmo[i] := SavedState.MaxAmmo[i];
5244 FRulez := SavedState.Rulez;
5246 if gGameSettings.GameType = GT_SERVER then
5247 MH_SEND_PlayerStats(FUID);
5248 end;
5250 procedure TPlayer.SaveState (st: TStream);
5251 var
5252 i: Integer;
5253 b: Byte;
5254 begin
5255 // Сигнатура игрока
5256 utils.writeSign(st, 'PLYR');
5257 utils.writeInt(st, Byte(PLR_SAVE_VERSION)); // version
5258 // Бот или человек
5259 utils.writeBool(st, FIamBot);
5260 // UID игрока
5261 utils.writeInt(st, Word(FUID));
5262 // Имя игрока
5263 utils.writeStr(st, FName);
5264 // Команда
5265 utils.writeInt(st, Byte(FTeam));
5266 // Жив ли
5267 utils.writeBool(st, FAlive);
5268 // Израсходовал ли все жизни
5269 utils.writeBool(st, FNoRespawn);
5270 // Направление
5271 if FDirection = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
5272 utils.writeInt(st, Byte(b));
5273 // Здоровье
5274 utils.writeInt(st, LongInt(FHealth));
5275 // Коэффициент инвалидности
5276 utils.writeInt(st, LongInt(FHandicap));
5277 // Жизни
5278 utils.writeInt(st, Byte(FLives));
5279 // Броня
5280 utils.writeInt(st, LongInt(FArmor));
5281 // Запас воздуха
5282 utils.writeInt(st, LongInt(FAir));
5283 // Запас горючего
5284 utils.writeInt(st, LongInt(FJetFuel));
5285 // Боль
5286 utils.writeInt(st, LongInt(FPain));
5287 // Убил
5288 utils.writeInt(st, LongInt(FKills));
5289 // Убил монстров
5290 utils.writeInt(st, LongInt(FMonsterKills));
5291 // Фрагов
5292 utils.writeInt(st, LongInt(FFrags));
5293 // Фрагов подряд
5294 utils.writeInt(st, Byte(FFragCombo));
5295 // Время последнего фрага
5296 utils.writeInt(st, LongWord(FLastFrag));
5297 // Смертей
5298 utils.writeInt(st, LongInt(FDeath));
5299 // Какой флаг несет
5300 utils.writeInt(st, Byte(FFlag));
5301 // Нашел секретов
5302 utils.writeInt(st, LongInt(FSecrets));
5303 // Текущее оружие
5304 utils.writeInt(st, Byte(FCurrWeap));
5305 // Желаемое оружие
5306 utils.writeInt(st, Word(FNextWeap));
5307 // ...и пауза
5308 utils.writeInt(st, Byte(FNextWeapDelay));
5309 // Время зарядки BFG
5310 utils.writeInt(st, SmallInt(FBFGFireCounter));
5311 // Буфер урона
5312 utils.writeInt(st, LongInt(FDamageBuffer));
5313 // Последний ударивший
5314 utils.writeInt(st, Word(FLastSpawnerUID));
5315 // Тип последнего полученного урона
5316 utils.writeInt(st, Byte(FLastHit));
5317 // Объект игрока
5318 Obj_SaveState(st, @FObj);
5319 // Текущее количество патронов
5320 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FAmmo[i]));
5321 // Максимальное количество патронов
5322 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FMaxAmmo[i]));
5323 // Наличие оружия
5324 for i := WP_FIRST to WP_LAST do utils.writeBool(st, FWeapon[i]);
5325 // Время перезарядки оружия
5326 for i := WP_FIRST to WP_LAST do utils.writeInt(st, Word(FReloading[i]));
5327 // Наличие рюкзака
5328 utils.writeBool(st, (R_ITEM_BACKPACK in FRulez));
5329 // Наличие красного ключа
5330 utils.writeBool(st, (R_KEY_RED in FRulez));
5331 // Наличие зеленого ключа
5332 utils.writeBool(st, (R_KEY_GREEN in FRulez));
5333 // Наличие синего ключа
5334 utils.writeBool(st, (R_KEY_BLUE in FRulez));
5335 // Наличие берсерка
5336 utils.writeBool(st, (R_BERSERK in FRulez));
5337 // Время действия специальных предметов
5338 for i := MR_SUIT to MR_MAX do utils.writeInt(st, LongWord(FMegaRulez[i]));
5339 // Время до повторного респауна, смены оружия, исользования, захвата флага
5340 for i := T_RESPAWN to T_FLAGCAP do utils.writeInt(st, LongWord(FTime[i]));
5341 // Название модели
5342 utils.writeStr(st, FModel.GetName());
5343 // Цвет модели
5344 utils.writeInt(st, Byte(FColor.R));
5345 utils.writeInt(st, Byte(FColor.G));
5346 utils.writeInt(st, Byte(FColor.B));
5347 end;
5350 procedure TPlayer.LoadState (st: TStream);
5351 var
5352 i: Integer;
5353 str: String;
5354 b: Byte;
5355 begin
5356 assert(st <> nil);
5358 // Сигнатура игрока
5359 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
5360 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
5361 // Бот или человек:
5362 FIamBot := utils.readBool(st);
5363 // UID игрока
5364 FUID := utils.readWord(st);
5365 // Имя игрока
5366 str := utils.readStr(st);
5367 if (self <> gPlayer1) and (self <> gPlayer2) then FName := str;
5368 // Команда
5369 FTeam := utils.readByte(st);
5370 // Жив ли
5371 FAlive := utils.readBool(st);
5372 // Израсходовал ли все жизни
5373 FNoRespawn := utils.readBool(st);
5374 // Направление
5375 b := utils.readByte(st);
5376 if b = 1 then FDirection := TDirection.D_LEFT else FDirection := TDirection.D_RIGHT; // b = 2
5377 // Здоровье
5378 FHealth := utils.readLongInt(st);
5379 // Коэффициент инвалидности
5380 FHandicap := utils.readLongInt(st);
5381 // Жизни
5382 FLives := utils.readByte(st);
5383 // Броня
5384 FArmor := utils.readLongInt(st);
5385 // Запас воздуха
5386 FAir := utils.readLongInt(st);
5387 // Запас горючего
5388 FJetFuel := utils.readLongInt(st);
5389 // Боль
5390 FPain := utils.readLongInt(st);
5391 // Убил
5392 FKills := utils.readLongInt(st);
5393 // Убил монстров
5394 FMonsterKills := utils.readLongInt(st);
5395 // Фрагов
5396 FFrags := utils.readLongInt(st);
5397 // Фрагов подряд
5398 FFragCombo := utils.readByte(st);
5399 // Время последнего фрага
5400 FLastFrag := utils.readLongWord(st);
5401 // Смертей
5402 FDeath := utils.readLongInt(st);
5403 // Какой флаг несет
5404 FFlag := utils.readByte(st);
5405 // Нашел секретов
5406 FSecrets := utils.readLongInt(st);
5407 // Текущее оружие
5408 FCurrWeap := utils.readByte(st);
5409 // Желаемое оружие
5410 FNextWeap := utils.readWord(st);
5411 // ...и пауза
5412 FNextWeapDelay := utils.readByte(st);
5413 // Время зарядки BFG
5414 FBFGFireCounter := utils.readSmallInt(st);
5415 // Буфер урона
5416 FDamageBuffer := utils.readLongInt(st);
5417 // Последний ударивший
5418 FLastSpawnerUID := utils.readWord(st);
5419 // Тип последнего полученного урона
5420 FLastHit := utils.readByte(st);
5421 // Объект игрока
5422 Obj_LoadState(@FObj, st);
5423 // Текущее количество патронов
5424 for i := A_BULLETS to A_HIGH do FAmmo[i] := utils.readWord(st);
5425 // Максимальное количество патронов
5426 for i := A_BULLETS to A_HIGH do FMaxAmmo[i] := utils.readWord(st);
5427 // Наличие оружия
5428 for i := WP_FIRST to WP_LAST do FWeapon[i] := utils.readBool(st);
5429 // Время перезарядки оружия
5430 for i := WP_FIRST to WP_LAST do FReloading[i] := utils.readWord(st);
5431 // Наличие рюкзака
5432 if utils.readBool(st) then Include(FRulez, R_ITEM_BACKPACK);
5433 // Наличие красного ключа
5434 if utils.readBool(st) then Include(FRulez, R_KEY_RED);
5435 // Наличие зеленого ключа
5436 if utils.readBool(st) then Include(FRulez, R_KEY_GREEN);
5437 // Наличие синего ключа
5438 if utils.readBool(st) then Include(FRulez, R_KEY_BLUE);
5439 // Наличие берсерка
5440 if utils.readBool(st) then Include(FRulez, R_BERSERK);
5441 // Время действия специальных предметов
5442 for i := MR_SUIT to MR_MAX do FMegaRulez[i] := utils.readLongWord(st);
5443 // Время до повторного респауна, смены оружия, исользования, захвата флага
5444 for i := T_RESPAWN to T_FLAGCAP do FTime[i] := utils.readLongWord(st);
5445 // Название модели
5446 str := utils.readStr(st);
5447 // Цвет модели
5448 FColor.R := utils.readByte(st);
5449 FColor.G := utils.readByte(st);
5450 FColor.B := utils.readByte(st);
5451 if (self = gPlayer1) then
5452 begin
5453 str := gPlayer1Settings.Model;
5454 FColor := gPlayer1Settings.Color;
5455 end
5456 else if (self = gPlayer2) then
5457 begin
5458 str := gPlayer2Settings.Model;
5459 FColor := gPlayer2Settings.Color;
5460 end;
5461 // Обновляем модель игрока
5462 SetModel(str);
5463 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
5464 FModel.Color := TEAMCOLOR[FTeam]
5465 else
5466 FModel.Color := FColor;
5467 end;
5470 procedure TPlayer.AllRulez(Health: Boolean);
5471 var
5472 a: Integer;
5473 begin
5474 if Health then
5475 begin
5476 FHealth := PLAYER_HP_LIMIT;
5477 FArmor := PLAYER_AP_LIMIT;
5478 Exit;
5479 end;
5481 for a := WP_FIRST to WP_LAST do FWeapon[a] := True;
5482 for a := A_BULLETS to A_HIGH do FAmmo[a] := 30000;
5483 FRulez := FRulez+[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5484 end;
5486 procedure TPlayer.RestoreHealthArmor();
5487 begin
5488 FHealth := PLAYER_HP_LIMIT;
5489 FArmor := PLAYER_AP_LIMIT;
5490 end;
5492 procedure TPlayer.FragCombo();
5493 var
5494 Param: Integer;
5495 begin
5496 if (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) or g_Game_IsClient then
5497 Exit;
5498 if gTime - FLastFrag < FRAG_COMBO_TIME then
5499 begin
5500 if FFragCombo < 5 then
5501 Inc(FFragCombo);
5502 Param := FUID or (FFragCombo shl 16);
5503 if (FComboEvnt >= Low(gDelayedEvents)) and
5504 (FComboEvnt <= High(gDelayedEvents)) and
5505 gDelayedEvents[FComboEvnt].Pending and
5506 (gDelayedEvents[FComboEvnt].DEType = DE_KILLCOMBO) and
5507 (gDelayedEvents[FComboEvnt].DENum and $FFFF = FUID) then
5508 begin
5509 gDelayedEvents[FComboEvnt].Time := gTime + 500;
5510 gDelayedEvents[FComboEvnt].DENum := Param;
5511 end
5512 else
5513 FComboEvnt := g_Game_DelayEvent(DE_KILLCOMBO, 500, Param);
5514 end
5515 else
5516 FFragCombo := 1;
5518 FLastFrag := gTime;
5519 end;
5521 procedure TPlayer.GiveItem(ItemType: Byte);
5522 begin
5523 case ItemType of
5524 ITEM_SUIT:
5525 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
5526 begin
5527 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
5528 end;
5530 ITEM_OXYGEN:
5531 if FAir < AIR_MAX then
5532 begin
5533 FAir := AIR_MAX;
5534 end;
5536 ITEM_MEDKIT_BLACK:
5537 begin
5538 if not (R_BERSERK in FRulez) then
5539 begin
5540 Include(FRulez, R_BERSERK);
5541 if FBFGFireCounter < 1 then
5542 begin
5543 FCurrWeap := WEAPON_KASTET;
5544 resetWeaponQueue();
5545 FModel.SetWeapon(WEAPON_KASTET);
5546 end;
5547 if gFlash <> 0 then
5548 Inc(FPain, 100);
5549 FBerserk := gTime+30000;
5550 end;
5551 if FHealth < PLAYER_HP_SOFT then
5552 begin
5553 FHealth := PLAYER_HP_SOFT;
5554 FBerserk := gTime+30000;
5555 end;
5556 end;
5558 ITEM_INVUL:
5559 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
5560 begin
5561 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
5562 FSpawnInvul := 0;
5563 end;
5565 ITEM_INVIS:
5566 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
5567 begin
5568 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
5569 end;
5571 ITEM_JETPACK:
5572 if FJetFuel < JET_MAX then
5573 begin
5574 FJetFuel := JET_MAX;
5575 end;
5577 ITEM_MEDKIT_SMALL: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
5578 ITEM_MEDKIT_LARGE: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
5580 ITEM_ARMOR_GREEN: if FArmor < PLAYER_AP_SOFT then FArmor := PLAYER_AP_SOFT;
5581 ITEM_ARMOR_BLUE: if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5583 ITEM_SPHERE_BLUE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
5584 ITEM_SPHERE_WHITE:
5585 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) then
5586 begin
5587 if FHealth < PLAYER_HP_LIMIT then FHealth := PLAYER_HP_LIMIT;
5588 if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5589 end;
5591 ITEM_WEAPON_SAW: FWeapon[WEAPON_SAW] := True;
5592 ITEM_WEAPON_SHOTGUN1: FWeapon[WEAPON_SHOTGUN1] := True;
5593 ITEM_WEAPON_SHOTGUN2: FWeapon[WEAPON_SHOTGUN2] := True;
5594 ITEM_WEAPON_CHAINGUN: FWeapon[WEAPON_CHAINGUN] := True;
5595 ITEM_WEAPON_ROCKETLAUNCHER: FWeapon[WEAPON_ROCKETLAUNCHER] := True;
5596 ITEM_WEAPON_PLASMA: FWeapon[WEAPON_PLASMA] := True;
5597 ITEM_WEAPON_BFG: FWeapon[WEAPON_BFG] := True;
5598 ITEM_WEAPON_SUPERPULEMET: FWeapon[WEAPON_SUPERPULEMET] := True;
5599 ITEM_WEAPON_FLAMETHROWER: FWeapon[WEAPON_FLAMETHROWER] := True;
5601 ITEM_AMMO_BULLETS: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5602 ITEM_AMMO_BULLETS_BOX: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
5603 ITEM_AMMO_SHELLS: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5604 ITEM_AMMO_SHELLS_BOX: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
5605 ITEM_AMMO_ROCKET: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5606 ITEM_AMMO_ROCKET_BOX: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
5607 ITEM_AMMO_CELL: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5608 ITEM_AMMO_CELL_BIG: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
5609 ITEM_AMMO_FUELCAN: if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
5611 ITEM_AMMO_BACKPACK:
5612 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
5613 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
5614 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
5615 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
5616 (FMaxAmmo[A_FUEL] < AmmoLimits[1, A_FUEL]) then
5617 begin
5618 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
5619 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
5620 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
5621 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
5622 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
5624 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5625 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5626 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5627 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5629 FRulez := FRulez + [R_ITEM_BACKPACK];
5630 end;
5632 ITEM_KEY_RED: if not (R_KEY_RED in FRulez) then Include(FRulez, R_KEY_RED);
5633 ITEM_KEY_GREEN: if not (R_KEY_GREEN in FRulez) then Include(FRulez, R_KEY_GREEN);
5634 ITEM_KEY_BLUE: if not (R_KEY_BLUE in FRulez) then Include(FRulez, R_KEY_BLUE);
5636 ITEM_BOTTLE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
5637 ITEM_HELMET: if FArmor < PLAYER_AP_LIMIT then IncMax(FArmor, 5, PLAYER_AP_LIMIT);
5639 else
5640 Exit;
5641 end;
5642 if g_Game_IsNet and g_Game_IsServer then
5643 MH_SEND_PlayerStats(FUID);
5644 end;
5646 procedure TPlayer.FlySmoke(Times: DWORD = 1);
5647 var i: DWORD;
5648 begin
5649 if (Random(5) = 1) and (Times = 1) then
5650 Exit;
5652 if BodyInLiquid(0, 0) then
5653 begin
5654 g_GFX_Bubbles(Obj.X+Obj.Rect.X+(Obj.Rect.Width div 2)+Random(3)-1,
5655 Obj.Y+Obj.Rect.Height+8, 1, 8, 4);
5656 if Random(2) = 0 then
5657 g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
5658 else
5659 g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
5660 Exit;
5661 end;
5663 for i := 1 to Times do
5664 begin
5665 r_GFX_OnceAnim(
5666 R_GFX_SMOKE_TRANS,
5667 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_SMOKE_WIDTH div 2),
5668 Obj.Y+Obj.Rect.Height-4+Random(8+Times*2)
5669 );
5670 end;
5671 end;
5673 procedure TPlayer.OnFireFlame(Times: DWORD = 1);
5674 var i: DWORD;
5675 begin
5676 if (Random(10) = 1) and (Times = 1) then
5677 Exit;
5679 for i := 1 to Times do
5680 begin
5681 r_GFX_OnceAnim(
5682 R_GFX_FLAME,
5683 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_FLAME_WIDTH div 2),
5684 Obj.Y+8+Random(8+Times*2)
5685 );
5686 end;
5687 end;
5689 procedure TPlayer.PauseSounds(Enable: Boolean);
5690 begin
5691 FSawSound.Pause(Enable);
5692 FSawSoundIdle.Pause(Enable);
5693 FSawSoundHit.Pause(Enable);
5694 FSawSoundSelect.Pause(Enable);
5695 FFlameSoundOn.Pause(Enable);
5696 FFlameSoundOff.Pause(Enable);
5697 FFlameSoundWork.Pause(Enable);
5698 FJetSoundFly.Pause(Enable);
5699 FJetSoundOn.Pause(Enable);
5700 FJetSoundOff.Pause(Enable);
5701 end;
5703 { T C o r p s e : }
5705 constructor TCorpse.Create(X, Y: Integer; ModelName: String; aMess: Boolean);
5706 begin
5707 g_Obj_Init(@FObj);
5708 FObj.X := X;
5709 FObj.Y := Y;
5710 FObj.Rect := PLAYER_CORPSERECT;
5711 FMess := aMess;
5712 FModel := g_PlayerModel_Get(ModelName);
5714 if FMess then
5715 begin
5716 FState := CORPSE_STATE_MESS;
5717 FModel.ChangeAnimation(A_DIE2);
5718 end
5719 else
5720 begin
5721 FState := CORPSE_STATE_NORMAL;
5722 FModel.ChangeAnimation(A_DIE1);
5723 end;
5724 end;
5726 destructor TCorpse.Destroy();
5727 begin
5728 FModel.Free;
5729 inherited;
5730 end;
5732 function TCorpse.ObjPtr (): PObj; inline; begin result := @FObj; end;
5734 procedure TCorpse.positionChanged (); inline; begin end;
5736 procedure TCorpse.moveBy (dx, dy: Integer); inline;
5737 begin
5738 if (dx <> 0) or (dy <> 0) then
5739 begin
5740 FObj.X += dx;
5741 FObj.Y += dy;
5742 positionChanged();
5743 end;
5744 end;
5747 procedure TCorpse.getMapBox (out x, y, w, h: Integer); inline;
5748 begin
5749 x := FObj.X+PLAYER_CORPSERECT.X;
5750 y := FObj.Y+PLAYER_CORPSERECT.Y;
5751 w := PLAYER_CORPSERECT.Width;
5752 h := PLAYER_CORPSERECT.Height;
5753 end;
5756 procedure TCorpse.Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
5757 var Blood: TModelBlood;
5758 begin
5759 if FState = CORPSE_STATE_REMOVEME then
5760 Exit;
5762 FDamage := FDamage + Value;
5764 if FDamage > 150 then
5765 begin
5766 if FModel <> nil then
5767 begin
5768 FState := CORPSE_STATE_REMOVEME;
5770 g_Player_CreateGibs(
5771 FObj.X + FObj.Rect.X + (FObj.Rect.Width div 2),
5772 FObj.Y + FObj.Rect.Y + (FObj.Rect.Height div 2),
5773 FModel.id,
5774 FModel.Color
5775 );
5777 // Звук мяса от трупа:
5778 FModel.PlaySound(MODELSOUND_DIE, 5, FObj.X, FObj.Y);
5780 // Зловещий смех:
5781 if (gBodyKillEvent <> -1) and gDelayedEvents[gBodyKillEvent].Pending then
5782 gDelayedEvents[gBodyKillEvent].Pending := False;
5783 gBodyKillEvent := g_Game_DelayEvent(DE_BODYKILL, 1050, SpawnerUID);
5785 FModel.Free;
5786 FModel := nil;
5787 end
5788 end
5789 else
5790 begin
5791 Blood := FModel.GetBlood();
5792 FObj.Vel.X := FObj.Vel.X + vx;
5793 FObj.Vel.Y := FObj.Vel.Y + vy;
5794 g_GFX_Blood(FObj.X+PLAYER_CORPSERECT.X+(PLAYER_CORPSERECT.Width div 2),
5795 FObj.Y+PLAYER_CORPSERECT.Y+(PLAYER_CORPSERECT.Height div 2),
5796 Value, vx, vy, 16, (PLAYER_CORPSERECT.Height*2) div 3,
5797 Blood.R, Blood.G, Blood.B, Blood.Kind);
5798 end;
5799 end;
5801 procedure TCorpse.Update();
5802 var
5803 st: Word;
5804 begin
5805 if FState = CORPSE_STATE_REMOVEME then
5806 Exit;
5808 FObj.oldX := FObj.X;
5809 FObj.oldY := FObj.Y;
5811 if gTime mod (GAME_TICK*2) <> 0 then
5812 begin
5813 g_Obj_Move(@FObj, True, True, True);
5814 positionChanged(); // this updates spatial accelerators
5815 Exit;
5816 end;
5818 // Сопротивление воздуха для трупа:
5819 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
5821 st := g_Obj_Move(@FObj, True, True, True);
5822 positionChanged(); // this updates spatial accelerators
5824 if WordBool(st and MOVE_FALLOUT) then
5825 begin
5826 FState := CORPSE_STATE_REMOVEME;
5827 Exit;
5828 end;
5830 if FModel <> nil then
5831 FModel.Update;
5832 end;
5835 procedure TCorpse.SaveState (st: TStream);
5836 var anim: Boolean;
5837 begin
5838 assert(st <> nil);
5840 // Сигнатура трупа
5841 utils.writeSign(st, 'CORP');
5842 utils.writeInt(st, Byte(0));
5843 // Состояние
5844 utils.writeInt(st, Byte(FState));
5845 // Накопленный урон
5846 utils.writeInt(st, Byte(FDamage));
5847 // Цвет
5848 utils.writeInt(st, Byte(FModel.Color.R));
5849 utils.writeInt(st, Byte(FModel.Color.G));
5850 utils.writeInt(st, Byte(FModel.Color.B));
5851 // Объект трупа
5852 Obj_SaveState(st, @FObj);
5853 utils.writeInt(st, Word(FPlayerUID));
5854 // animation
5855 anim := (FModel <> nil);
5856 utils.writeBool(st, anim);
5857 if anim then FModel.AnimState.SaveState(st);
5858 // animation for mask (same as animation, compat with older saves)
5859 anim := (FModel <> nil);
5860 utils.writeBool(st, anim);
5861 if anim then FModel.AnimState.SaveState(st);
5862 end;
5865 procedure TCorpse.LoadState (st: TStream);
5866 var anim: Boolean; r, g, b: Byte; stub: TAnimationState;
5867 begin
5868 assert(st <> nil);
5870 // Сигнатура трупа
5871 if not utils.checkSign(st, 'CORP') then raise XStreamError.Create('invalid corpse signature');
5872 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid corpse version');
5873 // Состояние
5874 FState := utils.readByte(st);
5875 // Накопленный урон
5876 FDamage := utils.readByte(st);
5877 // Цвет
5878 r := utils.readByte(st);
5879 g := utils.readByte(st);
5880 b := utils.readByte(st);
5881 FModel.SetColor(r, g, b);
5882 // Объект трупа
5883 Obj_LoadState(@FObj, st);
5884 FPlayerUID := utils.readWord(st);
5885 // animation
5886 stub := TAnimationState.Create(False, 0, 0);
5887 anim := utils.readBool(st);
5888 if anim then
5889 begin
5890 stub.LoadState(st);
5891 FModel.AnimState.CurrentFrame := Min(stub.CurrentFrame, FModel.AnimState.Length);
5892 end
5893 else
5894 begin
5895 FModel.Free;
5896 FModel := nil
5897 end;
5898 // animation for mask (same as animation, compat with older saves)
5899 anim := utils.readBool(st);
5900 if anim then stub.LoadState(st);
5901 stub.Free;
5902 end;
5904 { T B o t : }
5906 constructor TBot.Create();
5907 var
5908 a: Integer;
5909 begin
5910 inherited Create();
5912 FPhysics := True;
5913 FSpectator := False;
5914 FGhost := False;
5916 FIamBot := True;
5918 Inc(gNumBots);
5920 for a := WP_FIRST to WP_LAST do
5921 begin
5922 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
5923 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
5924 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
5925 end;
5926 end;
5928 destructor TBot.Destroy();
5929 begin
5930 Dec(gNumBots);
5931 inherited Destroy();
5932 end;
5934 procedure TBot.Respawn(Silent: Boolean; Force: Boolean = False);
5935 begin
5936 inherited Respawn(Silent, Force);
5938 FAIFlags := nil;
5939 FSelectedWeapon := FCurrWeap;
5940 resetWeaponQueue();
5941 FTargetUID := 0;
5942 end;
5944 procedure TBot.UpdateCombat();
5945 type
5946 TTarget = record
5947 UID: Word;
5948 X, Y: Integer;
5949 Rect: TRectWH;
5950 cX, cY: Integer;
5951 Dist: Word;
5952 Line: Boolean;
5953 Visible: Boolean;
5954 IsPlayer: Boolean;
5955 end;
5957 TTargetRecord = array of TTarget;
5959 function Compare(a, b: TTarget): Integer;
5960 begin
5961 if a.Line and not b.Line then // A на линии огня
5962 Result := -1
5963 else
5964 if not a.Line and b.Line then // B на линии огня
5965 Result := 1
5966 else // И A, и B на линии или не на линии огня
5967 if (a.Line and b.Line) or ((not a.Line) and (not b.Line)) then
5968 begin
5969 if a.Dist > b.Dist then // B ближе
5970 Result := 1
5971 else // A ближе или равноудаленно с B
5972 Result := -1;
5973 end
5974 else // Странно -> A
5975 Result := -1;
5976 end;
5978 var
5979 a, x1, y1, x2, y2: Integer;
5980 targets: TTargetRecord;
5981 ammo: Word;
5982 Target, BestTarget: TTarget;
5983 firew, fireh: Integer;
5984 angle: SmallInt;
5985 mon: TMonster;
5986 pla, tpla: TPlayer;
5987 vsPlayer, vsMonster, ok: Boolean;
5990 function monsUpdate (mon: TMonster): Boolean;
5991 begin
5992 result := false; // don't stop
5993 if mon.alive and (mon.MonsterType <> MONSTER_BARREL) then
5994 begin
5995 if not TargetOnScreen(mon.Obj.X+mon.Obj.Rect.X, mon.Obj.Y+mon.Obj.Rect.Y) then exit;
5997 x2 := mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2);
5998 y2 := mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2);
6000 // Если монстр на экране и не прикрыт стеной
6001 if g_TraceVector(x1, y1, x2, y2) then
6002 begin
6003 // Добавляем к списку возможных целей
6004 SetLength(targets, Length(targets)+1);
6005 with targets[High(targets)] do
6006 begin
6007 UID := mon.UID;
6008 X := mon.Obj.X;
6009 Y := mon.Obj.Y;
6010 cX := x2;
6011 cY := y2;
6012 Rect := mon.Obj.Rect;
6013 Dist := g_PatchLength(x1, y1, x2, y2);
6014 Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6015 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6016 Visible := True;
6017 IsPlayer := False;
6018 end;
6019 end;
6020 end;
6021 end;
6023 begin
6024 vsPlayer := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER);
6025 vsMonster := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER);
6027 // Если текущее оружие не то, что нужно, то меняем:
6028 if FCurrWeap <> FSelectedWeapon then
6029 NextWeapon();
6031 // Если нужно стрелять и нужное оружие, то нажать "Стрелять":
6032 if (GetAIFlag('NEEDFIRE') <> '') and (FCurrWeap = FSelectedWeapon) then
6033 begin
6034 RemoveAIFlag('NEEDFIRE');
6036 case FCurrWeap of
6037 WEAPON_PLASMA, WEAPON_SUPERPULEMET, WEAPON_CHAINGUN: PressKey(KEY_FIRE, 20);
6038 WEAPON_SAW, WEAPON_KASTET, WEAPON_FLAMETHROWER: PressKey(KEY_FIRE, 40);
6039 else PressKey(KEY_FIRE);
6040 end;
6041 end;
6043 // Координаты ствола:
6044 x1 := FObj.X + WEAPONPOINT[FDirection].X;
6045 y1 := FObj.Y + WEAPONPOINT[FDirection].Y;
6047 Target.UID := FTargetUID;
6049 ok := False;
6050 if Target.UID <> 0 then
6051 begin // Цель есть - настраиваем
6052 if (g_GetUIDType(Target.UID) = UID_PLAYER) and
6053 vsPlayer then
6054 begin // Игрок
6055 tpla := g_Player_Get(Target.UID);
6056 if tpla <> nil then
6057 with tpla do
6058 begin
6059 if (@FObj) <> nil then
6060 begin
6061 Target.X := FObj.X;
6062 Target.Y := FObj.Y;
6063 end;
6064 end;
6066 Target.cX := Target.X + PLAYER_RECT_CX;
6067 Target.cY := Target.Y + PLAYER_RECT_CY;
6068 Target.Rect := PLAYER_RECT;
6069 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6070 Target.Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6071 (y1-4 > Target.Y+PLAYER_RECT.Y);
6072 Target.IsPlayer := True;
6073 ok := True;
6074 end
6075 else
6076 if (g_GetUIDType(Target.UID) = UID_MONSTER) and
6077 vsMonster then
6078 begin // Монстр
6079 mon := g_Monsters_ByUID(Target.UID);
6080 if mon <> nil then
6081 begin
6082 Target.X := mon.Obj.X;
6083 Target.Y := mon.Obj.Y;
6085 Target.cX := Target.X + mon.Obj.Rect.X + (mon.Obj.Rect.Width div 2);
6086 Target.cY := Target.Y + mon.Obj.Rect.Y + (mon.Obj.Rect.Height div 2);
6087 Target.Rect := mon.Obj.Rect;
6088 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6089 Target.Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6090 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6091 Target.IsPlayer := False;
6092 ok := True;
6093 end;
6094 end;
6095 end;
6097 if not ok then
6098 begin // Цели нет - обнуляем
6099 Target.X := 0;
6100 Target.Y := 0;
6101 Target.cX := 0;
6102 Target.cY := 0;
6103 Target.Visible := False;
6104 Target.Line := False;
6105 Target.IsPlayer := False;
6106 end;
6108 targets := nil;
6110 // Если цель не видима или не на линии огня, то ищем все возможные цели:
6111 if (not Target.Line) or (not Target.Visible) then
6112 begin
6113 // Игроки:
6114 if vsPlayer then
6115 for a := 0 to High(gPlayers) do
6116 if (gPlayers[a] <> nil) and (gPlayers[a].alive) and
6117 (gPlayers[a].FUID <> FUID) and
6118 (not SameTeam(FUID, gPlayers[a].FUID)) and
6119 (not gPlayers[a].NoTarget) and
6120 (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
6121 begin
6122 if not TargetOnScreen(gPlayers[a].FObj.X + PLAYER_RECT.X,
6123 gPlayers[a].FObj.Y + PLAYER_RECT.Y) then
6124 Continue;
6126 x2 := gPlayers[a].FObj.X + PLAYER_RECT_CX;
6127 y2 := gPlayers[a].FObj.Y + PLAYER_RECT_CY;
6129 // Если игрок на экране и не прикрыт стеной:
6130 if g_TraceVector(x1, y1, x2, y2) then
6131 begin
6132 // Добавляем к списку возможных целей:
6133 SetLength(targets, Length(targets)+1);
6134 with targets[High(targets)] do
6135 begin
6136 UID := gPlayers[a].FUID;
6137 X := gPlayers[a].FObj.X;
6138 Y := gPlayers[a].FObj.Y;
6139 cX := x2;
6140 cY := y2;
6141 Rect := PLAYER_RECT;
6142 Dist := g_PatchLength(x1, y1, x2, y2);
6143 Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6144 (y1-4 > Target.Y+PLAYER_RECT.Y);
6145 Visible := True;
6146 IsPlayer := True;
6147 end;
6148 end;
6149 end;
6151 // Монстры:
6152 if vsMonster then g_Mons_ForEach(monsUpdate);
6153 end;
6155 // Если есть возможные цели:
6156 // (Выбираем лучшую, меняем оружие и бежим к ней/от нее)
6157 if targets <> nil then
6158 begin
6159 // Выбираем наилучшую цель:
6160 BestTarget := targets[0];
6161 if Length(targets) > 1 then
6162 for a := 1 to High(targets) do
6163 if Compare(BestTarget, targets[a]) = 1 then
6164 BestTarget := targets[a];
6166 // Если лучшая цель "виднее" текущей, то текущая := лучшая:
6167 if ((not Target.Visible) and BestTarget.Visible and (Target.UID <> BestTarget.UID)) or
6168 ((not Target.Line) and BestTarget.Line and BestTarget.Visible) then
6169 begin
6170 Target := BestTarget;
6172 if (Healthy() = 3) or ((Healthy() = 2)) then
6173 begin // Если здоровы - догоняем
6174 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6175 SetAIFlag('GORIGHT', '1');
6176 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6177 SetAIFlag('GOLEFT', '1');
6178 end
6179 else
6180 begin // Если побиты - убегаем
6181 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6182 SetAIFlag('GORIGHT', '1');
6183 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6184 SetAIFlag('GOLEFT', '1');
6185 end;
6187 // Выбираем оружие на основе расстояния и приоритетов:
6188 SelectWeapon(Abs(x1-Target.cX));
6189 end;
6190 end;
6192 // Если есть цель:
6193 // (Догоняем/убегаем, стреляем по направлению к цели)
6194 // (Если цель далеко, то хватит следить за ней)
6195 if Target.UID <> 0 then
6196 begin
6197 if not TargetOnScreen(Target.X + Target.Rect.X,
6198 Target.Y + Target.Rect.Y) then
6199 begin // Цель сбежала с "экрана"
6200 if (Healthy() = 3) or ((Healthy() = 2)) then
6201 begin // Если здоровы - догоняем
6202 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6203 SetAIFlag('GORIGHT', '1');
6204 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6205 SetAIFlag('GOLEFT', '1');
6206 end
6207 else
6208 begin // Если побиты - забываем о цели и убегаем
6209 Target.UID := 0;
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;
6215 end
6216 else
6217 begin // Цель пока на "экране"
6218 // Если цель не загорожена стеной, то отмечаем, когда ее видели:
6219 if g_TraceVector(x1, y1, Target.cX, Target.cY) then
6220 FLastVisible := gTime;
6221 // Если разница высот не велика, то догоняем:
6222 if (Abs(FObj.Y-Target.Y) <= 128) then
6223 begin
6224 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6225 SetAIFlag('GORIGHT', '1');
6226 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6227 SetAIFlag('GOLEFT', '1');
6228 end;
6229 end;
6231 // Выбираем угол вверх:
6232 if FDirection = TDirection.D_LEFT then
6233 angle := ANGLE_LEFTUP
6234 else
6235 angle := ANGLE_RIGHTUP;
6237 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6238 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6240 // Если при угле вверх можно попасть в приблизительное положение цели:
6241 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6242 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128), //96
6243 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6244 Target.Rect.Width, Target.Rect.Height) and
6245 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6246 begin // то нужно стрелять вверх
6247 SetAIFlag('NEEDFIRE', '1');
6248 SetAIFlag('NEEDSEEUP', '1');
6249 end;
6251 // Выбираем угол вниз:
6252 if FDirection = TDirection.D_LEFT then
6253 angle := ANGLE_LEFTDOWN
6254 else
6255 angle := ANGLE_RIGHTDOWN;
6257 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6258 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6260 // Если при угле вниз можно попасть в приблизительное положение цели:
6261 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6262 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6263 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6264 Target.Rect.Width, Target.Rect.Height) and
6265 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6266 begin // то нужно стрелять вниз
6267 SetAIFlag('NEEDFIRE', '1');
6268 SetAIFlag('NEEDSEEDOWN', '1');
6269 end;
6271 // Если цель видно и она на такой же высоте:
6272 if Target.Visible and
6273 (y1+4 < Target.Y+Target.Rect.Y+Target.Rect.Height) and
6274 (y1-4 > Target.Y+Target.Rect.Y) then
6275 begin
6276 // Если идем в сторону цели, то надо стрелять:
6277 if ((FDirection = TDirection.D_LEFT) and (Target.X < FObj.X)) or
6278 ((FDirection = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6279 begin // то нужно стрелять вперед
6280 SetAIFlag('NEEDFIRE', '1');
6281 SetAIFlag('NEEDSEEDOWN', '');
6282 SetAIFlag('NEEDSEEUP', '');
6283 end;
6284 // Если цель в пределах "экрана" и сложность позволяет прыжки сближения:
6285 if Abs(FObj.X-Target.X) < Trunc(gPlayerScreenSize.X*0.75) then
6286 if GetRnd(FDifficult.CloseJump) then
6287 begin // то если повезет - прыгаем (особенно, если близко)
6288 if Abs(FObj.X-Target.X) < 128 then
6289 a := 4
6290 else
6291 a := 30;
6292 if Random(a) = 0 then
6293 SetAIFlag('NEEDJUMP', '1');
6294 end;
6295 end;
6297 // Если цель все еще есть:
6298 if Target.UID <> 0 then
6299 if gTime-FLastVisible > 2000 then // Если видели давно
6300 Target.UID := 0 // то забыть цель
6301 else // Если видели недавно
6302 begin // но цель убили
6303 if Target.IsPlayer then
6304 begin // Цель - игрок
6305 pla := g_Player_Get(Target.UID);
6306 if (pla = nil) or (not pla.alive) or pla.NoTarget or
6307 (pla.FMegaRulez[MR_INVIS] >= gTime) then
6308 Target.UID := 0; // то забыть цель
6309 end
6310 else
6311 begin // Цель - монстр
6312 mon := g_Monsters_ByUID(Target.UID);
6313 if (mon = nil) or (not mon.alive) then
6314 Target.UID := 0; // то забыть цель
6315 end;
6316 end;
6317 end; // if Target.UID <> 0
6319 FTargetUID := Target.UID;
6321 // Если возможных целей нет:
6322 // (Атака чего-нибудь слева или справа)
6323 if targets = nil then
6324 if GetAIFlag('ATTACKLEFT') <> '' then
6325 begin // Если нужно атаковать налево
6326 RemoveAIFlag('ATTACKLEFT');
6328 SetAIFlag('NEEDJUMP', '1');
6330 if RunDirection() = TDirection.D_RIGHT then
6331 begin // Идем не в ту сторону
6332 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6333 begin // Если здоровы, то, возможно, стреляем бежим влево и стреляем
6334 SetAIFlag('NEEDFIRE', '1');
6335 SetAIFlag('GOLEFT', '1');
6336 end;
6337 end
6338 else
6339 begin // Идем в нужную сторону
6340 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6341 SetAIFlag('NEEDFIRE', '1');
6342 if Healthy() <= 1 then // Побиты - убегаем
6343 SetAIFlag('GORIGHT', '1');
6344 end;
6345 end
6346 else
6347 if GetAIFlag('ATTACKRIGHT') <> '' then
6348 begin // Если нужно атаковать направо
6349 RemoveAIFlag('ATTACKRIGHT');
6351 SetAIFlag('NEEDJUMP', '1');
6353 if RunDirection() = TDirection.D_LEFT then
6354 begin // Идем не в ту сторону
6355 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6356 begin // Если здоровы, то, возможно, бежим вправо и стреляем
6357 SetAIFlag('NEEDFIRE', '1');
6358 SetAIFlag('GORIGHT', '1');
6359 end;
6360 end
6361 else
6362 begin
6363 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6364 SetAIFlag('NEEDFIRE', '1');
6365 if Healthy() <= 1 then // Побиты - убегаем
6366 SetAIFlag('GOLEFT', '1');
6367 end;
6368 end;
6370 //HACK! (does it belongs there?)
6371 RealizeCurrentWeapon();
6373 // Если есть возможные цели:
6374 // (Стреляем по направлению к целям)
6375 if (targets <> nil) and (GetAIFlag('NEEDFIRE') <> '') then
6376 for a := 0 to High(targets) do
6377 begin
6378 // Если можем стрелять по диагонали:
6379 if GetRnd(FDifficult.DiagFire) then
6380 begin
6381 // Ищем цель сверху и стреляем, если есть:
6382 if FDirection = TDirection.D_LEFT then
6383 angle := ANGLE_LEFTUP
6384 else
6385 angle := ANGLE_RIGHTUP;
6387 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6388 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6390 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6391 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6392 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6393 targets[a].Rect.Width, targets[a].Rect.Height) and
6394 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6395 begin
6396 SetAIFlag('NEEDFIRE', '1');
6397 SetAIFlag('NEEDSEEUP', '1');
6398 end;
6400 // Ищем цель снизу и стреляем, если есть:
6401 if FDirection = TDirection.D_LEFT then
6402 angle := ANGLE_LEFTDOWN
6403 else
6404 angle := ANGLE_RIGHTDOWN;
6406 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6407 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6409 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6410 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6411 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6412 targets[a].Rect.Width, targets[a].Rect.Height) and
6413 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6414 begin
6415 SetAIFlag('NEEDFIRE', '1');
6416 SetAIFlag('NEEDSEEDOWN', '1');
6417 end;
6418 end;
6420 // Если цель "перед носом", то стреляем:
6421 if targets[a].Line and targets[a].Visible and
6422 (((FDirection = TDirection.D_LEFT) and (targets[a].X < FObj.X)) or
6423 ((FDirection = TDirection.D_RIGHT) and (targets[a].X > FObj.X))) then
6424 begin
6425 SetAIFlag('NEEDFIRE', '1');
6426 Break;
6427 end;
6428 end;
6430 // Если летит пуля, то, возможно, подпрыгиваем:
6431 if g_Weapon_Danger(FUID, FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y,
6432 PLAYER_RECT.Width, PLAYER_RECT.Height,
6433 40+GetInterval(FDifficult.Cover, 40)) then
6434 SetAIFlag('NEEDJUMP', '1');
6436 // Если кончились паторны, то нужно сменить оружие:
6437 ammo := GetAmmoByWeapon(FCurrWeap);
6438 if ((FCurrWeap = WEAPON_SHOTGUN2) and (ammo < 2)) or
6439 ((FCurrWeap = WEAPON_BFG) and (ammo < 40)) or
6440 (ammo = 0) then
6441 SetAIFlag('SELECTWEAPON', '1');
6443 // Если нужно сменить оружие, то выбираем нужное:
6444 if GetAIFlag('SELECTWEAPON') = '1' then
6445 begin
6446 SelectWeapon(-1);
6447 RemoveAIFlag('SELECTWEAPON');
6448 end;
6449 end;
6451 procedure TBot.Update();
6452 var
6453 EnableAI: Boolean;
6454 begin
6455 if not FAlive then
6456 begin // Respawn
6457 ReleaseKeys();
6458 PressKey(KEY_UP);
6459 end
6460 else
6461 begin
6462 EnableAI := True;
6464 // Проверяем, отключён ли AI ботов
6465 if (g_debug_BotAIOff = 1) and (Team = TEAM_RED) then
6466 EnableAI := False;
6467 if (g_debug_BotAIOff = 2) and (Team = TEAM_BLUE) then
6468 EnableAI := False;
6469 if g_debug_BotAIOff = 3 then
6470 EnableAI := False;
6472 if EnableAI then
6473 begin
6474 UpdateMove();
6475 UpdateCombat();
6476 end
6477 else
6478 begin
6479 RealizeCurrentWeapon();
6480 end;
6481 end;
6483 inherited Update();
6484 end;
6486 procedure TBot.ReleaseKey(Key: Byte);
6487 begin
6488 with FKeys[Key] do
6489 begin
6490 Pressed := False;
6491 Time := 0;
6492 end;
6493 end;
6495 function TBot.KeyPressed(Key: Word): Boolean;
6496 begin
6497 Result := FKeys[Key].Pressed;
6498 end;
6500 function TBot.GetAIFlag(aName: String20): String20;
6501 var
6502 a: Integer;
6503 begin
6504 Result := '';
6506 aName := LowerCase(aName);
6508 if FAIFlags <> nil then
6509 for a := 0 to High(FAIFlags) do
6510 if LowerCase(FAIFlags[a].Name) = aName then
6511 begin
6512 Result := FAIFlags[a].Value;
6513 Break;
6514 end;
6515 end;
6517 procedure TBot.RemoveAIFlag(aName: String20);
6518 var
6519 a, b: Integer;
6520 begin
6521 if FAIFlags = nil then Exit;
6523 aName := LowerCase(aName);
6525 for a := 0 to High(FAIFlags) do
6526 if LowerCase(FAIFlags[a].Name) = aName then
6527 begin
6528 if a <> High(FAIFlags) then
6529 for b := a to High(FAIFlags)-1 do
6530 FAIFlags[b] := FAIFlags[b+1];
6532 SetLength(FAIFlags, Length(FAIFlags)-1);
6533 Break;
6534 end;
6535 end;
6537 procedure TBot.SetAIFlag(aName, fValue: String20);
6538 var
6539 a: Integer;
6540 ok: Boolean;
6541 begin
6542 a := 0;
6543 ok := False;
6545 aName := LowerCase(aName);
6547 if FAIFlags <> nil then
6548 for a := 0 to High(FAIFlags) do
6549 if LowerCase(FAIFlags[a].Name) = aName then
6550 begin
6551 ok := True;
6552 Break;
6553 end;
6555 if ok then FAIFlags[a].Value := fValue
6556 else
6557 begin
6558 SetLength(FAIFlags, Length(FAIFlags)+1);
6559 with FAIFlags[High(FAIFlags)] do
6560 begin
6561 Name := aName;
6562 Value := fValue;
6563 end;
6564 end;
6565 end;
6567 procedure TBot.UpdateMove;
6569 procedure GoLeft(Time: Word = 1);
6570 begin
6571 ReleaseKey(KEY_LEFT);
6572 ReleaseKey(KEY_RIGHT);
6573 PressKey(KEY_LEFT, Time);
6574 SetDirection(TDirection.D_LEFT);
6575 end;
6577 procedure GoRight(Time: Word = 1);
6578 begin
6579 ReleaseKey(KEY_LEFT);
6580 ReleaseKey(KEY_RIGHT);
6581 PressKey(KEY_RIGHT, Time);
6582 SetDirection(TDirection.D_RIGHT);
6583 end;
6585 function Rnd(a: Word): Boolean;
6586 begin
6587 Result := Random(a) = 0;
6588 end;
6590 procedure Turn(Time: Word = 1200);
6591 begin
6592 if RunDirection() = TDirection.D_LEFT then GoRight(Time) else GoLeft(Time);
6593 end;
6595 procedure Stop();
6596 begin
6597 ReleaseKey(KEY_LEFT);
6598 ReleaseKey(KEY_RIGHT);
6599 end;
6601 function CanRunLeft(): Boolean;
6602 begin
6603 Result := not CollideLevel(-1, 0);
6604 end;
6606 function CanRunRight(): Boolean;
6607 begin
6608 Result := not CollideLevel(1, 0);
6609 end;
6611 function CanRun(): Boolean;
6612 begin
6613 if RunDirection() = TDirection.D_LEFT then Result := CanRunLeft() else Result := CanRunRight();
6614 end;
6616 procedure Jump(Time: Word = 30);
6617 begin
6618 PressKey(KEY_JUMP, Time);
6619 end;
6621 function NearHole(): Boolean;
6622 var
6623 x, sx: Integer;
6624 begin
6625 { TODO 5 : Лестницы }
6626 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6627 for x := 1 to PLAYER_RECT.Width do
6628 if (not StayOnStep(x*sx, 0)) and
6629 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6630 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6631 begin
6632 Result := True;
6633 Exit;
6634 end;
6636 Result := False;
6637 end;
6639 function BorderHole(): Boolean;
6640 var
6641 x, sx, xx: Integer;
6642 begin
6643 { TODO 5 : Лестницы }
6644 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6645 for x := 1 to PLAYER_RECT.Width do
6646 if (not StayOnStep(x*sx, 0)) and
6647 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6648 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6649 begin
6650 for xx := x to x+32 do
6651 if CollideLevel(xx*sx, PLAYER_RECT.Height) then
6652 begin
6653 Result := True;
6654 Exit;
6655 end;
6656 end;
6658 Result := False;
6659 end;
6661 function NearDeepHole(): Boolean;
6662 var
6663 x, sx, y: Integer;
6664 begin
6665 Result := False;
6667 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6668 y := 3;
6670 for x := 1 to PLAYER_RECT.Width do
6671 if (not StayOnStep(x*sx, 0)) and
6672 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6673 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6674 begin
6675 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6676 begin
6677 if CollideLevel(x*sx, PLAYER_RECT.Height*y) then Exit;
6678 y := y+1;
6679 end;
6681 Result := True;
6682 end else Result := False;
6683 end;
6685 function OverDeepHole(): Boolean;
6686 var
6687 y: Integer;
6688 begin
6689 Result := False;
6691 y := 1;
6692 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6693 begin
6694 if CollideLevel(0, PLAYER_RECT.Height*y) then Exit;
6695 y := y+1;
6696 end;
6698 Result := True;
6699 end;
6701 function OnGround(): Boolean;
6702 begin
6703 Result := StayOnStep(0, 0) or CollideLevel(0, 1);
6704 end;
6706 function OnLadder(): Boolean;
6707 begin
6708 Result := FullInStep(0, 0);
6709 end;
6711 function BelowLadder(): Boolean;
6712 begin
6713 Result := (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) and
6714 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6715 (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) and
6716 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6717 end;
6719 function BelowLiftUp(): Boolean;
6720 begin
6721 Result := ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) = -1) and
6722 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6723 ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) = -1) and
6724 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6725 end;
6727 function OnTopLift(): Boolean;
6728 begin
6729 Result := (FullInLift(0, 0) = -1) and (FullInLift(0, -32) = 0);
6730 end;
6732 function CanJumpOver(): Boolean;
6733 var
6734 sx, y: Integer;
6735 begin
6736 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6738 Result := False;
6740 if not CollideLevel(sx, 0) then Exit;
6742 for y := 1 to BOT_MAXJUMP do
6743 if CollideLevel(0, -y) then Exit else
6744 if not CollideLevel(sx, -y) then
6745 begin
6746 Result := True;
6747 Exit;
6748 end;
6749 end;
6751 function CanJumpUp(Dist: ShortInt): Boolean;
6752 var
6753 y, yy: Integer;
6754 c: Boolean;
6755 begin
6756 Result := False;
6758 if CollideLevel(Dist, 0) then Exit;
6760 c := False;
6761 for y := 0 to BOT_MAXJUMP do
6762 if CollideLevel(Dist, -y) then
6763 begin
6764 c := True;
6765 Break;
6766 end;
6768 if not c then Exit;
6770 c := False;
6771 for yy := y+1 to BOT_MAXJUMP do
6772 if not CollideLevel(Dist, -yy) then
6773 begin
6774 c := True;
6775 Break;
6776 end;
6778 if not c then Exit;
6780 c := False;
6781 for y := 0 to BOT_MAXJUMP do
6782 if CollideLevel(0, -y) then
6783 begin
6784 c := True;
6785 Break;
6786 end;
6788 if c then Exit;
6790 if y < yy then Exit;
6792 Result := True;
6793 end;
6795 function IsSafeTrigger(): Boolean;
6796 var
6797 a: Integer;
6798 begin
6799 Result := True;
6800 if gTriggers = nil then
6801 Exit;
6802 for a := 0 to High(gTriggers) do
6803 if Collide(gTriggers[a].X,
6804 gTriggers[a].Y,
6805 gTriggers[a].Width,
6806 gTriggers[a].Height) and
6807 (gTriggers[a].TriggerType in [TRIGGER_EXIT, TRIGGER_CLOSEDOOR,
6808 TRIGGER_CLOSETRAP, TRIGGER_TRAP,
6809 TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF,
6810 TRIGGER_ONOFF, TRIGGER_SPAWNMONSTER,
6811 TRIGGER_DAMAGE, TRIGGER_SHOT]) then
6812 Result := False;
6813 end;
6815 begin
6816 // Возможно, нажимаем кнопку:
6817 if Rnd(16) and IsSafeTrigger() then
6818 PressKey(KEY_OPEN);
6820 // Если под лифтом или ступеньками, то, возможно, прыгаем:
6821 if OnLadder() or ((BelowLadder() or BelowLiftUp()) and Rnd(8)) then
6822 begin
6823 ReleaseKey(KEY_LEFT);
6824 ReleaseKey(KEY_RIGHT);
6825 Jump();
6826 end;
6828 // Идем влево, если надо было:
6829 if GetAIFlag('GOLEFT') <> '' then
6830 begin
6831 RemoveAIFlag('GOLEFT');
6832 if CanRunLeft() then
6833 GoLeft(360);
6834 end;
6836 // Идем вправо, если надо было:
6837 if GetAIFlag('GORIGHT') <> '' then
6838 begin
6839 RemoveAIFlag('GORIGHT');
6840 if CanRunRight() then
6841 GoRight(360);
6842 end;
6844 // Если вылетели за карту, то пробуем вернуться:
6845 if FObj.X < -32 then
6846 GoRight(360)
6847 else
6848 if FObj.X+32 > gMapInfo.Width then
6849 GoLeft(360);
6851 // Прыгаем, если надо было:
6852 if GetAIFlag('NEEDJUMP') <> '' then
6853 begin
6854 Jump(0);
6855 RemoveAIFlag('NEEDJUMP');
6856 end;
6858 // Смотрим вверх, если надо было:
6859 if GetAIFlag('NEEDSEEUP') <> '' then
6860 begin
6861 ReleaseKey(KEY_UP);
6862 ReleaseKey(KEY_DOWN);
6863 PressKey(KEY_UP, 20);
6864 RemoveAIFlag('NEEDSEEUP');
6865 end;
6867 // Смотрим вниз, если надо было:
6868 if GetAIFlag('NEEDSEEDOWN') <> '' then
6869 begin
6870 ReleaseKey(KEY_UP);
6871 ReleaseKey(KEY_DOWN);
6872 PressKey(KEY_DOWN, 20);
6873 RemoveAIFlag('NEEDSEEDOWN');
6874 end;
6876 // Если нужно было в дыру и мы не на земле, то покорно летим:
6877 if GetAIFlag('GOINHOLE') <> '' then
6878 if not OnGround() then
6879 begin
6880 ReleaseKey(KEY_LEFT);
6881 ReleaseKey(KEY_RIGHT);
6882 RemoveAIFlag('GOINHOLE');
6883 SetAIFlag('FALLINHOLE', '1');
6884 end;
6886 // Если падали и достигли земли, то хватит падать:
6887 if GetAIFlag('FALLINHOLE') <> '' then
6888 if OnGround() then
6889 RemoveAIFlag('FALLINHOLE');
6891 // Если летели прямо и сейчас не на лестнице или на вершине лифта, то отходим в сторону:
6892 if not (KeyPressed(KEY_LEFT) or KeyPressed(KEY_RIGHT)) then
6893 if GetAIFlag('FALLINHOLE') = '' then
6894 if (not OnLadder()) or (FObj.Vel.Y >= 0) or (OnTopLift()) then
6895 if Rnd(2) then
6896 GoLeft(360)
6897 else
6898 GoRight(360);
6900 // Если на земле и можно подпрыгнуть, то, возможно, прыгаем:
6901 if OnGround() and
6902 CanJumpUp(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*32) and
6903 Rnd(8) then
6904 Jump();
6906 // Если на земле и возле дыры (глубина > 2 ростов игрока):
6907 if OnGround() and NearHole() then
6908 if NearDeepHole() then // Если это бездна
6909 case Random(6) of
6910 0..3: Turn(); // Бежим обратно
6911 4: Jump(); // Прыгаем
6912 5: begin // Прыгаем обратно
6913 Turn();
6914 Jump();
6915 end;
6916 end
6917 else // Это не бездна и мы еще не летим туда
6918 if GetAIFlag('GOINHOLE') = '' then
6919 case Random(6) of
6920 0: Turn(); // Не нужно туда
6921 1: Jump(); // Вдруг повезет - прыгаем
6922 else // Если яма с границей, то при случае можно туда прыгнуть
6923 if BorderHole() then
6924 SetAIFlag('GOINHOLE', '1');
6925 end;
6927 // Если на земле, но некуда идти:
6928 if (not CanRun()) and OnGround() then
6929 begin
6930 // Если мы на лестнице или можно перепрыгнуть, то прыгаем:
6931 if CanJumpOver() or OnLadder() then
6932 Jump()
6933 else // иначе попытаемся в другую сторону
6934 if Random(2) = 0 then
6935 begin
6936 if IsSafeTrigger() then
6937 PressKey(KEY_OPEN);
6938 end else
6939 Turn();
6940 end;
6942 // Осталось мало воздуха:
6943 if FAir < 36 * 2 then
6944 Jump(20);
6946 // Выбираемся из кислоты, если нет костюма, обожглись, или мало здоровья:
6947 if (FMegaRulez[MR_SUIT] < gTime) and ((FLastHit = HIT_ACID) or (Healthy() <= 1)) then
6948 if BodyInAcid(0, 0) then
6949 Jump();
6950 end;
6952 function TBot.FullInStep(XInc, YInc: Integer): Boolean;
6953 begin
6954 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
6955 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_STEP, False);
6956 end;
6958 {function TBot.NeedItem(Item: Byte): Byte;
6959 begin
6960 Result := 4;
6961 end;}
6963 procedure TBot.SelectWeapon(Dist: Integer);
6964 var
6965 a: Integer;
6967 function HaveAmmo(weapon: Byte): Boolean;
6968 begin
6969 case weapon of
6970 WEAPON_PISTOL: Result := FAmmo[A_BULLETS] >= 1;
6971 WEAPON_SHOTGUN1: Result := FAmmo[A_SHELLS] >= 1;
6972 WEAPON_SHOTGUN2: Result := FAmmo[A_SHELLS] >= 2;
6973 WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS] >= 10;
6974 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS] >= 1;
6975 WEAPON_PLASMA: Result := FAmmo[A_CELLS] >= 10;
6976 WEAPON_BFG: Result := FAmmo[A_CELLS] >= 40;
6977 WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS] >= 1;
6978 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL] >= 1;
6979 else Result := True;
6980 end;
6981 end;
6983 begin
6984 if Dist = -1 then Dist := BOT_LONGDIST;
6986 if Dist > BOT_LONGDIST then
6987 begin // Дальний бой
6988 for a := 0 to 9 do
6989 if FWeapon[FDifficult.WeaponPrior[a]] and HaveAmmo(FDifficult.WeaponPrior[a]) then
6990 begin
6991 FSelectedWeapon := FDifficult.WeaponPrior[a];
6992 Break;
6993 end;
6994 end
6995 else //if Dist > BOT_UNSAFEDIST then
6996 begin // Ближний бой
6997 for a := 0 to 9 do
6998 if FWeapon[FDifficult.CloseWeaponPrior[a]] and HaveAmmo(FDifficult.CloseWeaponPrior[a]) then
6999 begin
7000 FSelectedWeapon := FDifficult.CloseWeaponPrior[a];
7001 Break;
7002 end;
7003 end;
7004 { else
7005 begin
7006 for a := 0 to 9 do
7007 if FWeapon[FDifficult.SafeWeaponPrior[a]] and HaveAmmo(FDifficult.SafeWeaponPrior[a]) then
7008 begin
7009 FSelectedWeapon := FDifficult.SafeWeaponPrior[a];
7010 Break;
7011 end;
7012 end;}
7013 end;
7015 function TBot.PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean;
7016 begin
7017 Result := inherited PickItem(ItemType, force, remove);
7019 if Result then SetAIFlag('SELECTWEAPON', '1');
7020 end;
7022 function TBot.Heal(value: Word; Soft: Boolean): Boolean;
7023 begin
7024 Result := inherited Heal(value, Soft);
7025 end;
7027 function TBot.Healthy(): Byte;
7028 begin
7029 if FMegaRulez[MR_INVUL] >= gTime then Result := 3
7030 else if (FHealth > 80) or ((FHealth > 50) and (FArmor > 20)) then Result := 3
7031 else if (FHealth > 50) then Result := 2
7032 else if (FHealth > 20) then Result := 1
7033 else Result := 0;
7034 end;
7036 function TBot.TargetOnScreen(TX, TY: Integer): Boolean;
7037 begin
7038 Result := (Abs(FObj.X-TX) <= Trunc(gPlayerScreenSize.X*0.6)) and
7039 (Abs(FObj.Y-TY) <= Trunc(gPlayerScreenSize.Y*0.6));
7040 end;
7042 procedure TBot.OnDamage(Angle: SmallInt);
7043 var
7044 pla: TPlayer;
7045 mon: TMonster;
7046 ok: Boolean;
7047 begin
7048 inherited;
7050 if (Angle = 0) or (Angle = 180) then
7051 begin
7052 ok := False;
7053 if (g_GetUIDType(FLastSpawnerUID) = UID_PLAYER) and
7054 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER) then
7055 begin // Игрок
7056 pla := g_Player_Get(FLastSpawnerUID);
7057 ok := not TargetOnScreen(pla.FObj.X + PLAYER_RECT.X,
7058 pla.FObj.Y + PLAYER_RECT.Y);
7059 end
7060 else
7061 if (g_GetUIDType(FLastSpawnerUID) = UID_MONSTER) and
7062 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER) then
7063 begin // Монстр
7064 mon := g_Monsters_ByUID(FLastSpawnerUID);
7065 ok := not TargetOnScreen(mon.Obj.X + mon.Obj.Rect.X,
7066 mon.Obj.Y + mon.Obj.Rect.Y);
7067 end;
7069 if ok then
7070 if Angle = 0 then
7071 SetAIFlag('ATTACKLEFT', '1')
7072 else
7073 SetAIFlag('ATTACKRIGHT', '1');
7074 end;
7075 end;
7077 function TBot.RunDirection(): TDirection;
7078 begin
7079 if Abs(Vel.X) >= 1 then
7080 begin
7081 if Vel.X > 0 then Result := TDirection.D_RIGHT else Result := TDirection.D_LEFT;
7082 end else
7083 Result := FDirection;
7084 end;
7086 function TBot.GetRnd(a: Byte): Boolean;
7087 begin
7088 if a = 0 then Result := False
7089 else if a = 255 then Result := True
7090 else Result := Random(256) > 255-a;
7091 end;
7093 function TBot.GetInterval(a: Byte; radius: SmallInt): SmallInt;
7094 begin
7095 Result := Round((255-a)/255*radius*(Random(2)-1));
7096 end;
7099 procedure TDifficult.save (st: TStream);
7100 begin
7101 utils.writeInt(st, Byte(DiagFire));
7102 utils.writeInt(st, Byte(InvisFire));
7103 utils.writeInt(st, Byte(DiagPrecision));
7104 utils.writeInt(st, Byte(FlyPrecision));
7105 utils.writeInt(st, Byte(Cover));
7106 utils.writeInt(st, Byte(CloseJump));
7107 st.WriteBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7108 st.WriteBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7109 end;
7111 procedure TDifficult.load (st: TStream);
7112 begin
7113 DiagFire := utils.readByte(st);
7114 InvisFire := utils.readByte(st);
7115 DiagPrecision := utils.readByte(st);
7116 FlyPrecision := utils.readByte(st);
7117 Cover := utils.readByte(st);
7118 CloseJump := utils.readByte(st);
7119 st.ReadBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7120 st.ReadBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7121 end;
7124 procedure TBot.SaveState (st: TStream);
7125 var
7126 i: Integer;
7127 dw: Integer;
7128 begin
7129 inherited SaveState(st);
7130 utils.writeSign(st, 'BOT0');
7131 // Выбранное оружие
7132 utils.writeInt(st, Byte(FSelectedWeapon));
7133 // UID цели
7134 utils.writeInt(st, Word(FTargetUID));
7135 // Время потери цели
7136 utils.writeInt(st, LongWord(FLastVisible));
7137 // Количество флагов ИИ
7138 dw := Length(FAIFlags);
7139 utils.writeInt(st, LongInt(dw));
7140 // Флаги ИИ
7141 for i := 0 to dw-1 do
7142 begin
7143 utils.writeStr(st, FAIFlags[i].Name, 20);
7144 utils.writeStr(st, FAIFlags[i].Value, 20);
7145 end;
7146 // Настройки сложности
7147 FDifficult.save(st);
7148 end;
7151 procedure TBot.LoadState (st: TStream);
7152 var
7153 i: Integer;
7154 dw: Integer;
7155 begin
7156 inherited LoadState(st);
7157 if not utils.checkSign(st, 'BOT0') then raise XStreamError.Create('invalid bot signature');
7158 // Выбранное оружие
7159 FSelectedWeapon := utils.readByte(st);
7160 // UID цели
7161 FTargetUID := utils.readWord(st);
7162 // Время потери цели
7163 FLastVisible := utils.readLongWord(st);
7164 // Количество флагов ИИ
7165 dw := utils.readLongInt(st);
7166 if (dw < 0) or (dw > 16384) then raise XStreamError.Create('invalid number of bot AI flags');
7167 SetLength(FAIFlags, dw);
7168 // Флаги ИИ
7169 for i := 0 to dw-1 do
7170 begin
7171 FAIFlags[i].Name := utils.readStr(st, 20);
7172 FAIFlags[i].Value := utils.readStr(st, 20);
7173 end;
7174 // Настройки сложности
7175 FDifficult.load(st);
7176 end;
7179 begin
7180 conRegVar('cheat_berserk_autoswitch', @gBerserkAutoswitch, 'autoswitch to fist when berserk pack taken', '', true, true);
7181 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');
7182 conRegVar('player_indicator_style', @gPlayerIndicatorStyle, 'Visual appearance of indicator', 'Visual appearance of indicator');
7183 end.