DEADSOFTWARE

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