DEADSOFTWARE

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