DEADSOFTWARE

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