DEADSOFTWARE

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