DEADSOFTWARE

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