DEADSOFTWARE

render: use only r_render to access render
[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 {$IFNDEF HEADLESS}
655 r_render,
656 {$ENDIF}
657 e_log, g_map, g_items, g_console, g_gfx, Math,
658 g_options, g_triggers, g_menu, g_game, g_grid, e_res,
659 wadreader, g_monsters, CONFIG, g_language,
660 g_net, g_netmsg,
661 utils, xstreams;
663 const PLR_SAVE_VERSION = 0;
665 type
666 TBotProfile = record
667 name: ShortString;
668 model: ShortString;
669 team: Byte;
670 color: TRGB;
671 diag_fire: Byte;
672 invis_fire: Byte;
673 diag_precision: Byte;
674 fly_precision: Byte;
675 cover: Byte;
676 close_jump: Byte;
677 w_prior1: Array [WP_FIRST..WP_LAST] of Byte;
678 w_prior2: Array [WP_FIRST..WP_LAST] of Byte;
679 w_prior3: Array [WP_FIRST..WP_LAST] of Byte;
680 end;
682 const
683 TIME_RESPAWN1 = 1500;
684 TIME_RESPAWN2 = 2000;
685 TIME_RESPAWN3 = 3000;
686 PLAYER_SUIT_TIME = 30000;
687 PLAYER_INVUL_TIME = 30000;
688 PLAYER_INVIS_TIME = 35000;
689 FRAG_COMBO_TIME = 3000;
690 VEL_SW = 4;
691 VEL_FLY = 6;
692 PLAYER_HEADRECT: TRectWH = (X:24; Y:12; Width:20; Height:12);
693 BOT_MAXJUMP = 84;
694 BOT_LONGDIST = 300;
695 BOT_UNSAFEDIST = 128;
696 DIFFICULT_EASY: TDifficult = (DiagFire: 32; InvisFire: 32; DiagPrecision: 32;
697 FlyPrecision: 32; Cover: 32; CloseJump: 32;
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_MEDIUM: TDifficult = (DiagFire: 127; InvisFire: 127; DiagPrecision: 127;
700 FlyPrecision: 127; Cover: 127; CloseJump: 127;
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 DIFFICULT_HARD: TDifficult = (DiagFire: 255; InvisFire: 255; DiagPrecision: 255;
703 FlyPrecision: 255; Cover: 255; CloseJump: 255;
704 WeaponPrior:(0,0,0,0,0,0,0,0,0,0,0); CloseWeaponPrior:(0,0,0,0,0,0,0,0,0,0,0));
705 WEAPON_PRIOR1: Array [WP_FIRST..WP_LAST] of Byte =
706 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
707 WEAPON_SHOTGUN2, WEAPON_SHOTGUN1,
708 WEAPON_CHAINGUN, WEAPON_PLASMA, WEAPON_ROCKETLAUNCHER,
709 WEAPON_BFG, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
710 WEAPON_PRIOR2: Array [WP_FIRST..WP_LAST] of Byte =
711 (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
712 WEAPON_BFG, WEAPON_ROCKETLAUNCHER,
713 WEAPON_SHOTGUN2, WEAPON_PLASMA, WEAPON_SHOTGUN1,
714 WEAPON_CHAINGUN, WEAPON_PISTOL, WEAPON_SAW, WEAPON_KASTET);
715 //WEAPON_PRIOR3: Array [WP_FIRST..WP_LAST] of Byte =
716 // (WEAPON_FLAMETHROWER, WEAPON_SUPERPULEMET,
717 // WEAPON_BFG, WEAPON_PLASMA, WEAPON_SHOTGUN2,
718 // WEAPON_CHAINGUN, WEAPON_SHOTGUN1, WEAPON_SAW,
719 // WEAPON_ROCKETLAUNCHER, WEAPON_PISTOL, WEAPON_KASTET);
720 WEAPON_RELOAD: Array [WP_FIRST..WP_LAST] of Byte =
721 (5, 2, 6, 18, 36, 2, 12, 2, 14, 2, 2);
723 PLAYER_SIGNATURE = $52594C50; // 'PLYR'
724 CORPSE_SIGNATURE = $50524F43; // 'CORP'
726 BOTNAMES_FILENAME = 'botnames.txt';
727 BOTLIST_FILENAME = 'botlist.txt';
729 var
730 MaxGibs: Word = 150;
731 MaxCorpses: Word = 20;
732 MaxShells: Word = 300;
733 ForceModel: Word = 0;
734 ForcedModelName: String = STD_PLAYER_MODEL;
735 CurrentGib: Integer = 0;
736 CurrentShell: Integer = 0;
737 BotNames: Array of String;
738 BotList: Array of TBotProfile;
739 SavedStates: Array of TPlayerSavedState;
742 function Lerp(X, Y, Factor: Integer): Integer;
743 begin
744 Result := X + ((Y - X) div Factor);
745 end;
747 function SameTeam(UID1, UID2: Word): Boolean;
748 begin
749 Result := False;
751 if (UID1 > UID_MAX_PLAYER) or (UID1 <= UID_MAX_GAME) or
752 (UID2 > UID_MAX_PLAYER) or (UID2 <= UID_MAX_GAME) then Exit;
754 if (g_Player_Get(UID1) = nil) or (g_Player_Get(UID2) = nil) then Exit;
756 if ((g_Player_Get(UID1).Team = TEAM_NONE) or
757 (g_Player_Get(UID2).Team = TEAM_NONE)) then Exit;
759 Result := g_Player_Get(UID1).FTeam = g_Player_Get(UID2).FTeam;
760 end;
762 procedure g_Gibs_SetMax(Count: Word);
763 begin
764 MaxGibs := Count;
765 SetLength(gGibs, Count);
767 if CurrentGib >= Count then
768 CurrentGib := 0;
769 end;
771 function g_Gibs_GetMax(): Word;
772 begin
773 Result := MaxGibs;
774 end;
776 procedure g_Shells_SetMax(Count: Word);
777 begin
778 MaxShells := Count;
779 SetLength(gShells, Count);
781 if CurrentShell >= Count then
782 CurrentShell := 0;
783 end;
785 function g_Shells_GetMax(): Word;
786 begin
787 Result := MaxShells;
788 end;
791 procedure g_Corpses_SetMax(Count: Word);
792 begin
793 MaxCorpses := Count;
794 SetLength(gCorpses, Count);
795 end;
797 function g_Corpses_GetMax(): Word;
798 begin
799 Result := MaxCorpses;
800 end;
802 procedure g_Force_Model_Set(Mode: Word);
803 begin
804 ForceModel := Mode;
805 end;
807 function g_Force_Model_Get(): Word;
808 begin
809 Result := ForceModel;
810 end;
812 procedure g_Forced_Model_SetName(Model: String);
813 begin
814 ForcedModelName := Model;
815 end;
817 function g_Forced_Model_GetName(): String;
818 begin
819 Result := ForcedModelName;
820 end;
822 function g_Player_Create(ModelName: String; Color: TRGB; Team: Byte; Bot: Boolean): Word;
823 var
824 a: Integer;
825 ok: Boolean;
826 begin
827 Result := 0;
829 ok := False;
830 a := 0;
832 // Есть ли место в gPlayers:
833 if gPlayers <> nil then
834 for a := 0 to High(gPlayers) do
835 if gPlayers[a] = nil then
836 begin
837 ok := True;
838 Break;
839 end;
841 // Нет места - расширяем gPlayers:
842 if not ok then
843 begin
844 SetLength(gPlayers, Length(gPlayers)+1);
845 a := High(gPlayers);
846 end;
848 // Создаем объект игрока:
849 if Bot then
850 gPlayers[a] := TBot.Create()
851 else
852 gPlayers[a] := TPlayer.Create();
855 gPlayers[a].FActualModelName := ModelName;
856 gPlayers[a].SetModel(ModelName);
857 if Bot and (g_Force_Model_Get() <> 0) then
858 gPlayers[a].SetModel(g_Forced_Model_GetName());
860 // Нет модели - создание не возможно:
861 if gPlayers[a].FModel = nil then
862 begin
863 gPlayers[a].Free();
864 gPlayers[a] := nil;
865 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], [ModelName]));
866 Exit;
867 end;
869 if not (Team in [TEAM_RED, TEAM_BLUE]) then
870 if Random(2) = 0 then
871 Team := TEAM_RED
872 else
873 Team := TEAM_BLUE;
874 gPlayers[a].FPreferredTeam := Team;
876 case gGameSettings.GameMode of
877 GM_DM: gPlayers[a].FTeam := TEAM_NONE;
878 GM_TDM,
879 GM_CTF: gPlayers[a].FTeam := gPlayers[a].FPreferredTeam;
880 GM_SINGLE,
881 GM_COOP: gPlayers[a].FTeam := TEAM_COOP;
882 end;
884 // Если командная игра - красим модель в цвет команды:
885 gPlayers[a].FColor := Color;
886 if gPlayers[a].FTeam in [TEAM_RED, TEAM_BLUE] then
887 gPlayers[a].FModel.Color := TEAMCOLOR[gPlayers[a].FTeam]
888 else
889 gPlayers[a].FModel.Color := Color;
891 gPlayers[a].FUID := g_CreateUID(UID_PLAYER);
892 gPlayers[a].FAlive := False;
894 Result := gPlayers[a].FUID;
895 end;
897 function g_Player_CreateFromState (st: TStream): Word;
898 var a: Integer; ok, Bot: Boolean; pos: Int64;
899 begin
900 assert(st <> nil);
902 // check signature and entity type
903 pos := st.Position;
904 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
905 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
906 Bot := utils.readBool(st);
907 st.Position := pos;
909 // find free player slot
910 ok := false;
911 for a := 0 to High(gPlayers) do
912 if gPlayers[a] = nil then
913 begin
914 ok := true;
915 break;
916 end;
918 // allocate player slot
919 if not ok then
920 begin
921 SetLength(gPlayers, Length(gPlayers)+1);
922 a := High(gPlayers);
923 end;
925 // create entity and load state
926 if Bot then
927 begin
928 gPlayers[a] := TBot.Create();
929 if (g_Force_Model_Get() <> 0) then
930 gPlayers[a].SetModel(g_Forced_Model_GetName());
931 end
932 else
933 gPlayers[a] := TPlayer.Create();
934 gPlayers[a].FPhysics := True; // ???
935 gPlayers[a].LoadState(st);
937 result := gPlayers[a].FUID;
938 end;
941 procedure g_Player_ResetTeams();
942 var
943 a: Integer;
944 begin
945 if g_Game_IsClient then
946 Exit;
947 if gPlayers = nil then
948 Exit;
949 for a := Low(gPlayers) to High(gPlayers) do
950 if gPlayers[a] <> nil then
951 case gGameSettings.GameMode of
952 GM_DM:
953 gPlayers[a].ChangeTeam(TEAM_NONE);
954 GM_TDM, GM_CTF:
955 if not (gPlayers[a].Team in [TEAM_RED, TEAM_BLUE]) then
956 if gPlayers[a].FPreferredTeam in [TEAM_RED, TEAM_BLUE] then
957 gPlayers[a].ChangeTeam(gPlayers[a].FPreferredTeam)
958 else
959 if a mod 2 = 0 then
960 gPlayers[a].ChangeTeam(TEAM_RED)
961 else
962 gPlayers[a].ChangeTeam(TEAM_BLUE);
963 GM_SINGLE,
964 GM_COOP:
965 gPlayers[a].ChangeTeam(TEAM_COOP);
966 end;
967 end;
969 procedure g_Bot_Add(Team, Difficult: Byte; Handicap: Integer = 100);
970 var
971 m: SSArray;
972 _name, _model: String;
973 a, tr, tb: Integer;
974 begin
975 if not g_Game_IsServer then Exit;
977 if (g_Bot_GetCount() >= gMaxBots) then Exit;
979 // Список названий моделей:
980 m := g_PlayerModel_GetNames();
981 if m = nil then
982 Exit;
984 // Команда:
985 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
986 Team := TEAM_COOP // COOP
987 else
988 if gGameSettings.GameMode = GM_DM then
989 Team := TEAM_NONE // DM
990 else
991 if Team = TEAM_NONE then // CTF / TDM
992 begin
993 // Автобаланс команд:
994 tr := 0;
995 tb := 0;
997 for a := 0 to High(gPlayers) do
998 if gPlayers[a] <> nil then
999 begin
1000 if gPlayers[a].Team = TEAM_RED then
1001 Inc(tr)
1002 else
1003 if gPlayers[a].Team = TEAM_BLUE then
1004 Inc(tb);
1005 end;
1007 if tr > tb then
1008 Team := TEAM_BLUE
1009 else
1010 if tb > tr then
1011 Team := TEAM_RED
1012 else // tr = tb
1013 if Random(2) = 0 then
1014 Team := TEAM_RED
1015 else
1016 Team := TEAM_BLUE;
1017 end;
1019 // Выбираем боту имя:
1020 _name := '';
1021 if BotNames <> nil then
1022 for a := 0 to High(BotNames) do
1023 if g_Player_ValidName(BotNames[a]) then
1024 begin
1025 _name := BotNames[a];
1026 Break;
1027 end;
1029 // Выбираем случайную модель:
1030 _model := m[Random(Length(m))];
1032 // Создаем бота:
1033 with g_Player_Get(g_Player_Create(_model,
1034 _RGB(Min(Random(9)*32, 255),
1035 Min(Random(9)*32, 255),
1036 Min(Random(9)*32, 255)),
1037 Team, True)) as TBot do
1038 begin
1039 // Если имени нет, делаем его из UID бота
1040 if _name = '' then
1041 Name := Format('DFBOT%.5d', [UID])
1042 else
1043 Name := _name;
1045 case Difficult of
1046 1: FDifficult := DIFFICULT_EASY;
1047 2: FDifficult := DIFFICULT_MEDIUM;
1048 else FDifficult := DIFFICULT_HARD;
1049 end;
1051 for a := WP_FIRST to WP_LAST do
1052 begin
1053 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
1054 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
1055 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
1056 end;
1058 FHandicap := Handicap;
1060 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1062 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1063 if g_Game_IsServer and (gGameSettings.MaxLives > 0) then
1064 Spectate();
1065 end;
1066 end;
1068 procedure g_Bot_AddList(Team: Byte; lName: ShortString; num: Integer = -1; Handicap: Integer = 100);
1069 var
1070 m: SSArray;
1071 _name, _model: String;
1072 a: Integer;
1073 begin
1074 if not g_Game_IsServer then Exit;
1076 if (g_Bot_GetCount() >= gMaxBots) then Exit;
1078 // Список названий моделей:
1079 m := g_PlayerModel_GetNames();
1080 if m = nil then
1081 Exit;
1083 // Команда:
1084 if (gGameSettings.GameType = GT_SINGLE) or (gGameSettings.GameMode = GM_COOP) then
1085 Team := TEAM_COOP // COOP
1086 else
1087 if gGameSettings.GameMode = GM_DM then
1088 Team := TEAM_NONE // DM
1089 else
1090 if Team = TEAM_NONE then
1091 Team := BotList[num].team; // CTF / TDM
1093 // Выбираем настройки бота из списка по номеру или имени:
1094 lName := AnsiLowerCase(lName);
1095 if (num < 0) or (num > Length(BotList)-1) then
1096 num := -1;
1097 if (num = -1) and (lName <> '') and (BotList <> nil) then
1098 for a := 0 to High(BotList) do
1099 if AnsiLowerCase(BotList[a].name) = lName then
1100 begin
1101 num := a;
1102 Break;
1103 end;
1104 if num = -1 then
1105 Exit;
1107 // Имя бота:
1108 _name := BotList[num].name;
1109 // Занято - выбираем случайное:
1110 if not g_Player_ValidName(_name) then
1111 repeat
1112 _name := Format('DFBOT%.2d', [Random(100)]);
1113 until g_Player_ValidName(_name);
1115 // Модель:
1116 _model := BotList[num].model;
1117 // Нет такой - выбираем случайную:
1118 if not InSArray(_model, m) then
1119 _model := m[Random(Length(m))];
1121 // Создаем бота:
1122 with g_Player_Get(g_Player_Create(_model, BotList[num].color, Team, True)) as TBot do
1123 begin
1124 Name := _name;
1126 FDifficult.DiagFire := BotList[num].diag_fire;
1127 FDifficult.InvisFire := BotList[num].invis_fire;
1128 FDifficult.DiagPrecision := BotList[num].diag_precision;
1129 FDifficult.FlyPrecision := BotList[num].fly_precision;
1130 FDifficult.Cover := BotList[num].cover;
1131 FDifficult.CloseJump := BotList[num].close_jump;
1133 FHandicap := Handicap;
1135 for a := WP_FIRST to WP_LAST do
1136 begin
1137 FDifficult.WeaponPrior[a] := BotList[num].w_prior1[a];
1138 FDifficult.CloseWeaponPrior[a] := BotList[num].w_prior2[a];
1139 //FDifficult.SafeWeaponPrior[a] := BotList[num].w_prior3[a];
1140 end;
1142 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [Name]), True);
1144 if g_Game_IsNet then MH_SEND_PlayerCreate(UID);
1145 end;
1146 end;
1148 procedure g_Bot_RemoveAll();
1149 var
1150 a: Integer;
1151 begin
1152 if not g_Game_IsServer then Exit;
1153 if gPlayers = nil then Exit;
1155 for a := 0 to High(gPlayers) do
1156 if gPlayers[a] <> nil then
1157 if gPlayers[a] is TBot then
1158 begin
1159 gPlayers[a].Lives := 0;
1160 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
1161 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
1162 g_Player_Remove(gPlayers[a].FUID);
1163 end;
1165 g_Bot_MixNames();
1166 end;
1168 procedure g_Bot_MixNames();
1169 var
1170 s: String;
1171 a, b: Integer;
1172 begin
1173 if BotNames <> nil then
1174 for a := 0 to High(BotNames) do
1175 begin
1176 b := Random(Length(BotNames));
1177 s := BotNames[a];
1178 Botnames[a] := BotNames[b];
1179 BotNames[b] := s;
1180 end;
1181 end;
1183 procedure g_Player_Remove(UID: Word);
1184 var
1185 i: Integer;
1186 begin
1187 if gPlayers = nil then Exit;
1189 if g_Game_IsServer and g_Game_IsNet then
1190 MH_SEND_PlayerDelete(UID);
1192 for i := 0 to High(gPlayers) do
1193 if gPlayers[i] <> nil then
1194 if gPlayers[i].FUID = UID then
1195 begin
1196 if gPlayers[i] is TPlayer then
1197 TPlayer(gPlayers[i]).Free()
1198 else
1199 TBot(gPlayers[i]).Free();
1200 gPlayers[i] := nil;
1201 Exit;
1202 end;
1203 end;
1205 procedure g_Player_Init();
1206 var
1207 F: TextFile;
1208 s: String;
1209 a, b: Integer;
1210 config: TConfig;
1211 sa: SSArray;
1212 path: AnsiString;
1213 begin
1214 BotNames := nil;
1216 path := BOTNAMES_FILENAME;
1217 if e_FindResource(DataDirs, path) = false then
1218 Exit;
1220 // Читаем возможные имена ботов из файла:
1221 AssignFile(F, path);
1222 Reset(F);
1224 while not EOF(F) do
1225 begin
1226 ReadLn(F, s);
1228 s := Trim(s);
1229 if s = '' then
1230 Continue;
1232 SetLength(BotNames, Length(BotNames)+1);
1233 BotNames[High(BotNames)] := s;
1234 end;
1236 CloseFile(F);
1238 // Перемешиваем их:
1239 g_Bot_MixNames();
1241 // Читаем файл с параметрами ботов:
1242 config := TConfig.CreateFile(path);
1243 BotList := nil;
1244 a := 0;
1246 while config.SectionExists(IntToStr(a)) do
1247 begin
1248 SetLength(BotList, Length(BotList)+1);
1250 with BotList[High(BotList)] do
1251 begin
1252 // Имя бота:
1253 name := config.ReadStr(IntToStr(a), 'name', '');
1254 // Модель:
1255 model := config.ReadStr(IntToStr(a), 'model', '');
1256 // Команда:
1257 if config.ReadStr(IntToStr(a), 'team', 'red') = 'red' then
1258 team := TEAM_RED
1259 else
1260 team := TEAM_BLUE;
1261 // Цвет модели:
1262 sa := parse(config.ReadStr(IntToStr(a), 'color', ''));
1263 color.R := StrToIntDef(sa[0], 0);
1264 color.G := StrToIntDef(sa[1], 0);
1265 color.B := StrToIntDef(sa[2], 0);
1266 // Вероятность стрельбы под углом:
1267 diag_fire := config.ReadInt(IntToStr(a), 'diag_fire', 0);
1268 // Вероятность ответного огня по невидимому сопернику:
1269 invis_fire := config.ReadInt(IntToStr(a), 'invis_fire', 0);
1270 // Точность стрельбы под углом:
1271 diag_precision := config.ReadInt(IntToStr(a), 'diag_precision', 0);
1272 // Точность стрельбы в полете:
1273 fly_precision := config.ReadInt(IntToStr(a), 'fly_precision', 0);
1274 // Точность уклонения от снарядов:
1275 cover := config.ReadInt(IntToStr(a), 'cover', 0);
1276 // Вероятность прыжка при приближении соперника:
1277 close_jump := config.ReadInt(IntToStr(a), 'close_jump', 0);
1278 // Приоритеты оружия для дальнего боя:
1279 sa := parse(config.ReadStr(IntToStr(a), 'w_prior1', ''));
1280 if Length(sa) = 10 then
1281 for b := 0 to 9 do
1282 w_prior1[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1283 // Приоритеты оружия для ближнего боя:
1284 sa := parse(config.ReadStr(IntToStr(a), 'w_prior2', ''));
1285 if Length(sa) = 10 then
1286 for b := 0 to 9 do
1287 w_prior2[b] := EnsureRange(StrToInt(sa[b]), 0, 9);
1289 {sa := parse(config.ReadStr(IntToStr(a), 'w_prior3', ''));
1290 if Length(sa) = 10 then
1291 for b := 0 to 9 do
1292 w_prior3[b] := EnsureRange(StrToInt(sa[b]), 0, 9);}
1293 end;
1295 a := a + 1;
1296 end;
1298 config.Free();
1299 SetLength(SavedStates, 0);
1300 end;
1302 procedure g_Player_Free();
1303 var
1304 i: Integer;
1305 begin
1306 if gPlayers <> nil then
1307 begin
1308 for i := 0 to High(gPlayers) do
1309 if gPlayers[i] <> nil then
1310 begin
1311 if gPlayers[i] is TPlayer then
1312 TPlayer(gPlayers[i]).Free()
1313 else
1314 TBot(gPlayers[i]).Free();
1315 gPlayers[i] := nil;
1316 end;
1318 gPlayers := nil;
1319 end;
1321 gPlayer1 := nil;
1322 gPlayer2 := nil;
1323 SetLength(SavedStates, 0);
1324 end;
1326 procedure g_Player_PreUpdate();
1327 var
1328 i: Integer;
1329 begin
1330 if gPlayers = nil then Exit;
1331 for i := 0 to High(gPlayers) do
1332 if gPlayers[i] <> nil then
1333 gPlayers[i].PreUpdate();
1334 end;
1336 procedure g_Player_UpdateAll();
1337 var
1338 i: Integer;
1339 begin
1340 if gPlayers = nil then Exit;
1342 //e_WriteLog('***g_Player_UpdateAll: ENTER', MSG_WARNING);
1343 for i := 0 to High(gPlayers) do
1344 begin
1345 if gPlayers[i] <> nil then
1346 begin
1347 if gPlayers[i] is TPlayer then
1348 begin
1349 gPlayers[i].Update();
1350 gPlayers[i].RealizeCurrentWeapon(); // WARNING! DO NOT MOVE THIS INTO `Update()`!
1351 end
1352 else
1353 begin
1354 // bot updates weapons in `UpdateCombat()`
1355 TBot(gPlayers[i]).Update();
1356 end;
1357 end;
1358 end;
1359 //e_WriteLog('***g_Player_UpdateAll: EXIT', MSG_WARNING);
1360 end;
1362 function g_Player_Get(UID: Word): TPlayer;
1363 var
1364 a: Integer;
1365 begin
1366 Result := nil;
1368 if gPlayers = nil then
1369 Exit;
1371 for a := 0 to High(gPlayers) do
1372 if gPlayers[a] <> nil then
1373 if gPlayers[a].FUID = UID then
1374 begin
1375 Result := gPlayers[a];
1376 Exit;
1377 end;
1378 end;
1380 function g_Player_GetCount(): Byte;
1381 var
1382 a: Integer;
1383 begin
1384 Result := 0;
1386 if gPlayers = nil then
1387 Exit;
1389 for a := 0 to High(gPlayers) do
1390 if gPlayers[a] <> nil then
1391 Result := Result + 1;
1392 end;
1394 function g_Bot_GetCount(): Integer;
1395 var
1396 a: Integer;
1397 begin
1398 Result := 0;
1400 if gPlayers = nil then
1401 Exit;
1403 for a := 0 to High(gPlayers) do
1404 if (gPlayers[a] <> nil) and (gPlayers[a] is TBot) then
1405 Result := Result + 1;
1406 end;
1408 function g_Player_GetStats(): TPlayerStatArray;
1409 var
1410 a: Integer;
1411 begin
1412 Result := nil;
1414 if gPlayers = nil then Exit;
1416 for a := 0 to High(gPlayers) do
1417 if gPlayers[a] <> nil then
1418 begin
1419 SetLength(Result, Length(Result)+1);
1420 with Result[High(Result)] do
1421 begin
1422 Num := a;
1423 Ping := gPlayers[a].FPing;
1424 Loss := gPlayers[a].FLoss;
1425 Name := gPlayers[a].FName;
1426 Team := gPlayers[a].FTeam;
1427 Frags := gPlayers[a].FFrags;
1428 Deaths := gPlayers[a].FDeath;
1429 Kills := gPlayers[a].FKills;
1430 Color := gPlayers[a].FModel.Color;
1431 Lives := gPlayers[a].FLives;
1432 Spectator := gPlayers[a].FSpectator;
1433 UID := gPlayers[a].FUID;
1434 end;
1435 end;
1436 end;
1438 procedure g_Player_ResetReady();
1439 var
1440 a: Integer;
1441 begin
1442 if not g_Game_IsServer then Exit;
1443 if gPlayers = nil then Exit;
1445 for a := 0 to High(gPlayers) do
1446 if gPlayers[a] <> nil then
1447 begin
1448 gPlayers[a].FReady := False;
1449 if g_Game_IsNet then
1450 MH_SEND_GameEvent(NET_EV_INTER_READY, gPlayers[a].UID, 'N');
1451 end;
1452 end;
1454 procedure g_Player_RememberAll;
1455 var
1456 i: Integer;
1457 begin
1458 for i := Low(gPlayers) to High(gPlayers) do
1459 if (gPlayers[i] <> nil) and gPlayers[i].alive then
1460 gPlayers[i].RememberState;
1461 end;
1463 procedure g_Player_ResetAll(Force, Silent: Boolean);
1464 var
1465 i: Integer;
1466 begin
1467 gTeamStat[TEAM_RED].Score := 0;
1468 gTeamStat[TEAM_BLUE].Score := 0;
1470 if gPlayers <> nil then
1471 for i := 0 to High(gPlayers) do
1472 if gPlayers[i] <> nil then
1473 begin
1474 gPlayers[i].Reset(Force);
1476 if gPlayers[i] is TPlayer then
1477 begin
1478 if (not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame then
1479 gPlayers[i].Respawn(Silent)
1480 else
1481 gPlayers[i].Spectate();
1482 end
1483 else
1484 TBot(gPlayers[i]).Respawn(Silent);
1485 end;
1486 end;
1488 function g_Player_CreateCorpse(Player: TPlayer): Integer;
1489 var
1490 i: Integer;
1491 find_id: DWORD;
1492 ok: Boolean;
1493 begin
1494 Result := -1;
1496 if Player.alive then
1497 Exit;
1499 // Разрываем связь с прежним трупом:
1500 i := Player.FCorpse;
1501 if (i >= 0) and (i < Length(gCorpses)) then
1502 begin
1503 if (gCorpses[i] <> nil) and (gCorpses[i].FPlayerUID = Player.FUID) then
1504 gCorpses[i].FPlayerUID := 0;
1505 end;
1507 if Player.FObj.Y >= gMapInfo.Height+128 then
1508 Exit;
1510 with Player do
1511 begin
1512 if (FHealth >= -50) or (gGibsCount = 0) then
1513 begin
1514 if (gCorpses = nil) or (Length(gCorpses) = 0) then
1515 Exit;
1517 ok := False;
1518 for find_id := 0 to High(gCorpses) do
1519 if gCorpses[find_id] = nil then
1520 begin
1521 ok := True;
1522 Break;
1523 end;
1525 if not ok then
1526 find_id := Random(Length(gCorpses));
1528 gCorpses[find_id] := TCorpse.Create(FObj.X, FObj.Y, FModel.GetName(), FHealth < -20);
1529 gCorpses[find_id].FModel.Color := FModel.Color;
1530 gCorpses[find_id].FObj.Vel := FObj.Vel;
1531 gCorpses[find_id].FObj.Accel := FObj.Accel;
1532 gCorpses[find_id].FPlayerUID := FUID;
1534 Result := find_id;
1535 end
1536 else
1537 g_Player_CreateGibs(FObj.X + PLAYER_RECT_CX, FObj.Y + PLAYER_RECT_CY, FModel.id, FModel.Color);
1538 end;
1539 end;
1541 procedure g_Player_CreateShell(fX, fY, dX, dY: Integer; T: Byte);
1542 begin
1543 if (gShells = nil) or (Length(gShells) = 0) then
1544 Exit;
1546 with gShells[CurrentShell] do
1547 begin
1548 g_Obj_Init(@Obj);
1549 Obj.Rect.X := 0;
1550 Obj.Rect.Y := 0;
1551 if T = SHELL_BULLET then
1552 begin
1553 Obj.Rect.Width := 4;
1554 Obj.Rect.Height := 2;
1555 end
1556 else
1557 begin
1558 Obj.Rect.Width := 7;
1559 Obj.Rect.Height := 3;
1560 end;
1561 SType := T;
1562 alive := True;
1563 Obj.X := fX;
1564 Obj.Y := fY;
1565 g_Obj_Push(@Obj, dX + Random(4)-Random(4), dY-Random(4));
1566 positionChanged(); // this updates spatial accelerators
1567 RAngle := Random(360);
1568 Timeout := gTime + SHELL_TIMEOUT;
1570 if CurrentShell >= High(gShells) then
1571 CurrentShell := 0
1572 else
1573 Inc(CurrentShell);
1574 end;
1575 end;
1577 procedure g_Player_CreateGibs (fX, fY, mid: Integer; fColor: TRGB);
1578 var
1579 a: Integer;
1580 GibsArray: TGibsArray;
1581 Blood: TModelBlood;
1582 begin
1583 if mid = -1 then
1584 Exit;
1585 if (gGibs = nil) or (Length(gGibs) = 0) then
1586 Exit;
1587 if not g_PlayerModel_GetGibs(mid, GibsArray) then
1588 Exit;
1589 Blood := PlayerModelsArray[mid].Blood;
1591 for a := 0 to High(GibsArray) do
1592 with gGibs[CurrentGib] do
1593 begin
1594 ModelID := mid;
1595 GibID := GibsArray[a];
1596 Color := fColor;
1597 alive := True;
1598 g_Obj_Init(@Obj);
1599 {$IFNDEF HEADLESS}
1600 Obj.Rect := r_Render_GetGibRect(ModelID, GibID);
1601 {$ELSE}
1602 Obj.Rect.X := 16;
1603 Obj.Rect.Y := 16;
1604 Obj.Rect.Width := 16;
1605 Obj.Rect.Height := 16;
1606 {$ENDIF}
1607 Obj.X := fX - Obj.Rect.X - (Obj.Rect.Width div 2);
1608 Obj.Y := fY - Obj.Rect.Y - (Obj.Rect.Height div 2);
1609 g_Obj_PushA(@Obj, 25 + Random(10), Random(361));
1610 positionChanged(); // this updates spatial accelerators
1611 RAngle := Random(360);
1613 if gBloodCount > 0 then
1614 g_GFX_Blood(fX, fY, 16*gBloodCount+Random(5*gBloodCount), -16+Random(33), -16+Random(33),
1615 Random(48), Random(48), Blood.R, Blood.G, Blood.B, Blood.Kind);
1617 if CurrentGib >= High(gGibs) then
1618 CurrentGib := 0
1619 else
1620 Inc(CurrentGib);
1621 end;
1622 end;
1624 procedure g_Player_UpdatePhysicalObjects();
1625 var
1626 i: Integer;
1627 vel: TPoint2i;
1628 mr: Word;
1630 procedure ShellSound_Bounce(X, Y: Integer; T: Byte);
1631 var
1632 k: Integer;
1633 begin
1634 k := 1 + Random(2);
1635 if T = SHELL_BULLET then
1636 g_Sound_PlayExAt('SOUND_PLAYER_CASING' + IntToStr(k), X, Y)
1637 else
1638 g_Sound_PlayExAt('SOUND_PLAYER_SHELL' + IntToStr(k), X, Y);
1639 end;
1641 begin
1642 // Куски мяса:
1643 if gGibs <> nil then
1644 for i := 0 to High(gGibs) do
1645 if gGibs[i].alive then
1646 with gGibs[i] do
1647 begin
1648 Obj.oldX := Obj.X;
1649 Obj.oldY := Obj.Y;
1651 vel := Obj.Vel;
1652 mr := g_Obj_Move(@Obj, True, False, True);
1653 positionChanged(); // this updates spatial accelerators
1655 if WordBool(mr and MOVE_FALLOUT) then
1656 begin
1657 alive := False;
1658 Continue;
1659 end;
1661 // Отлетает от удара о стену/потолок/пол:
1662 if WordBool(mr and MOVE_HITWALL) then
1663 Obj.Vel.X := -(vel.X div 2);
1664 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1665 Obj.Vel.Y := -(vel.Y div 2);
1667 if (Obj.Vel.X >= 0) then
1668 begin // Clockwise
1669 RAngle := RAngle + Abs(Obj.Vel.X)*6 + Abs(Obj.Vel.Y);
1670 if RAngle >= 360 then
1671 RAngle := RAngle mod 360;
1672 end else begin // Counter-clockwise
1673 RAngle := RAngle - Abs(Obj.Vel.X)*6 - Abs(Obj.Vel.Y);
1674 if RAngle < 0 then
1675 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1676 end;
1678 // Сопротивление воздуха для куска трупа:
1679 if gTime mod (GAME_TICK*3) = 0 then
1680 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
1681 end;
1683 // Трупы:
1684 if gCorpses <> nil then
1685 for i := 0 to High(gCorpses) do
1686 if gCorpses[i] <> nil then
1687 if gCorpses[i].State = CORPSE_STATE_REMOVEME then
1688 begin
1689 gCorpses[i].Free();
1690 gCorpses[i] := nil;
1691 end
1692 else
1693 gCorpses[i].Update();
1695 // Гильзы:
1696 if gShells <> nil then
1697 for i := 0 to High(gShells) do
1698 if gShells[i].alive then
1699 with gShells[i] do
1700 begin
1701 Obj.oldX := Obj.X;
1702 Obj.oldY := Obj.Y;
1704 vel := Obj.Vel;
1705 mr := g_Obj_Move(@Obj, True, False, True);
1706 positionChanged(); // this updates spatial accelerators
1708 if WordBool(mr and MOVE_FALLOUT) or (gShells[i].Timeout < gTime) then
1709 begin
1710 alive := False;
1711 Continue;
1712 end;
1714 // Отлетает от удара о стену/потолок/пол:
1715 if WordBool(mr and MOVE_HITWALL) then
1716 begin
1717 Obj.Vel.X := -(vel.X div 2);
1718 if not WordBool(mr and MOVE_INWATER) then
1719 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1720 end;
1721 if WordBool(mr and (MOVE_HITCEIL or MOVE_HITLAND)) then
1722 begin
1723 Obj.Vel.Y := -(vel.Y div 2);
1724 if Obj.Vel.X <> 0 then Obj.Vel.X := Obj.Vel.X div 2;
1725 if (Obj.Vel.X = 0) and (Obj.Vel.Y = 0) then
1726 begin
1727 if RAngle mod 90 <> 0 then
1728 RAngle := (RAngle div 90) * 90;
1729 end
1730 else if not WordBool(mr and MOVE_INWATER) then
1731 ShellSound_Bounce(Obj.X, Obj.Y, SType);
1732 end;
1734 if (Obj.Vel.X >= 0) then
1735 begin // Clockwise
1736 RAngle := RAngle + Abs(Obj.Vel.X)*8 + Abs(Obj.Vel.Y);
1737 if RAngle >= 360 then
1738 RAngle := RAngle mod 360;
1739 end else begin // Counter-clockwise
1740 RAngle := RAngle - Abs(Obj.Vel.X)*8 - Abs(Obj.Vel.Y);
1741 if RAngle < 0 then
1742 RAngle := (360 - (Abs(RAngle) mod 360)) mod 360;
1743 end;
1744 end;
1745 end;
1748 procedure TGib.getMapBox (out x, y, w, h: Integer); inline;
1749 begin
1750 x := Obj.X+Obj.Rect.X;
1751 y := Obj.Y+Obj.Rect.Y;
1752 w := Obj.Rect.Width;
1753 h := Obj.Rect.Height;
1754 end;
1756 procedure TGib.moveBy (dx, dy: Integer); inline;
1757 begin
1758 if (dx <> 0) or (dy <> 0) then
1759 begin
1760 Obj.X += dx;
1761 Obj.Y += dy;
1762 positionChanged();
1763 end;
1764 end;
1767 procedure TShell.getMapBox (out x, y, w, h: Integer); inline;
1768 begin
1769 x := Obj.X;
1770 y := Obj.Y;
1771 w := Obj.Rect.Width;
1772 h := Obj.Rect.Height;
1773 end;
1775 procedure TShell.moveBy (dx, dy: Integer); inline;
1776 begin
1777 if (dx <> 0) or (dy <> 0) then
1778 begin
1779 Obj.X += dx;
1780 Obj.Y += dy;
1781 positionChanged();
1782 end;
1783 end;
1786 procedure TGib.positionChanged (); inline; begin end;
1787 procedure TShell.positionChanged (); inline; begin end;
1790 procedure g_Player_RemoveAllCorpses();
1791 var
1792 i: Integer;
1793 begin
1794 gGibs := nil;
1795 gShells := nil;
1796 SetLength(gGibs, MaxGibs);
1797 SetLength(gShells, MaxGibs);
1798 CurrentGib := 0;
1799 CurrentShell := 0;
1801 if gCorpses <> nil then
1802 for i := 0 to High(gCorpses) do
1803 gCorpses[i].Free();
1805 gCorpses := nil;
1806 SetLength(gCorpses, MaxCorpses);
1807 end;
1809 procedure g_Player_Corpses_SaveState (st: TStream);
1810 var
1811 count, i: Integer;
1812 begin
1813 // Считаем количество существующих трупов
1814 count := 0;
1815 for i := 0 to High(gCorpses) do if (gCorpses[i] <> nil) then Inc(count);
1817 // Количество трупов
1818 utils.writeInt(st, LongInt(count));
1820 if (count = 0) then exit;
1822 // Сохраняем трупы
1823 for i := 0 to High(gCorpses) do
1824 begin
1825 if gCorpses[i] <> nil then
1826 begin
1827 // Название модели
1828 utils.writeStr(st, gCorpses[i].FModel.GetName());
1829 // Тип смерти
1830 utils.writeBool(st, gCorpses[i].Mess);
1831 // Сохраняем данные трупа:
1832 gCorpses[i].SaveState(st);
1833 end;
1834 end;
1835 end;
1838 procedure g_Player_Corpses_LoadState (st: TStream);
1839 var
1840 count, i: Integer;
1841 str: String;
1842 b: Boolean;
1843 begin
1844 assert(st <> nil);
1846 g_Player_RemoveAllCorpses();
1848 // Количество трупов:
1849 count := utils.readLongInt(st);
1850 if (count < 0) or (count > Length(gCorpses)) then raise XStreamError.Create('invalid number of corpses');
1852 if (count = 0) then exit;
1854 // Загружаем трупы
1855 for i := 0 to count-1 do
1856 begin
1857 // Название модели:
1858 str := utils.readStr(st);
1859 // Тип смерти
1860 b := utils.readBool(st);
1861 // Создаем труп
1862 gCorpses[i] := TCorpse.Create(0, 0, str, b);
1863 // Загружаем данные трупа
1864 gCorpses[i].LoadState(st);
1865 end;
1866 end;
1869 { T P l a y e r : }
1871 function TPlayer.isValidViewPort (): Boolean; inline; begin result := (viewPortW > 0) and (viewPortH > 0); end;
1873 procedure TPlayer.BFGHit();
1874 begin
1875 g_Weapon_BFGHit(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1876 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2));
1877 if g_Game_IsServer and g_Game_IsNet then
1878 MH_SEND_Effect(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
1879 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
1880 0, NET_GFX_BFGHIT);
1881 end;
1883 procedure TPlayer.ChangeModel(ModelName: string);
1884 var
1885 locModel: TPlayerModel;
1886 begin
1887 locModel := g_PlayerModel_Get(ModelName);
1888 if locModel = nil then Exit;
1890 FModel.Free();
1891 FModel := locModel;
1892 end;
1894 procedure TPlayer.SetModel(ModelName: string);
1895 var
1896 m: TPlayerModel;
1897 begin
1898 m := g_PlayerModel_Get(ModelName);
1899 if m = nil then
1900 begin
1901 g_SimpleError(Format(_lc[I_GAME_ERROR_MODEL_FALLBACK], [ModelName]));
1902 m := g_PlayerModel_Get('doomer');
1903 if m = nil then
1904 begin
1905 g_FatalError(Format(_lc[I_GAME_ERROR_MODEL], ['doomer']));
1906 Exit;
1907 end;
1908 end;
1910 if FModel <> nil then
1911 FModel.Free();
1913 FModel := m;
1915 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1916 FModel.Color := FColor
1917 else
1918 FModel.Color := TEAMCOLOR[FTeam];
1919 FModel.SetWeapon(FCurrWeap);
1920 FModel.SetFlag(FFlag);
1921 SetDirection(FDirection);
1922 end;
1924 procedure TPlayer.SetColor(Color: TRGB);
1925 begin
1926 FColor := Color;
1927 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
1928 if FModel <> nil then FModel.Color := Color;
1929 end;
1933 function TPlayer.GetColor(): TRGB;
1934 begin
1935 result := FModel.Color;
1936 end;
1938 procedure TPlayer.SetWeaponPrefs(Prefs: Array of Byte);
1939 var
1940 i: Integer;
1941 begin
1942 for i := WP_FIRST to WP_LAST + 1 do
1943 begin
1944 if (Prefs[i] > WP_LAST + 1) then
1945 FWeapPreferences[i] := 0
1946 else
1947 FWeapPreferences[i] := Prefs[i];
1948 end;
1949 end;
1951 procedure TPlayer.SetWeaponPref(Weapon, Pref: Byte);
1952 begin
1953 if (Weapon > WP_LAST + 1) then
1954 exit
1955 else if (Pref <= WP_LAST + 1) and (Weapon <= WP_LAST + 1) then
1956 FWeapPreferences[Weapon] := Pref
1957 else if (Weapon <= WP_LAST + 1) and (Pref > WP_LAST + 1) then
1958 FWeapPreferences[Weapon] := 0;
1959 end;
1961 function TPlayer.GetWeaponPref(Weapon: Byte) : Byte;
1962 begin
1963 if (Weapon > WP_LAST + 1) then
1964 result := 0
1965 else if (FWeapPreferences[Weapon] > WP_LAST + 1) then
1966 result := 0
1967 else
1968 result := FWeapPreferences[Weapon];
1969 end;
1971 function TPlayer.GetMorePrefered() : Byte;
1972 var
1973 testedWeap, i: Byte;
1974 begin
1975 testedWeap := FCurrWeap;
1976 for i := WP_FIRST to WP_LAST do
1977 if FWeapon[i] and maySwitch(i) and (FWeapPreferences[i] > FWeapPreferences[testedWeap]) then
1978 testedWeap := i;
1979 if (R_BERSERK in FRulez) and (FWeapPreferences[WP_LAST + 1] > FWeapPreferences[testedWeap]) then
1980 testedWeap := WEAPON_KASTET;
1981 result := testedWeap;
1982 end;
1984 function TPlayer.maySwitch(Weapon: Byte) : Boolean;
1985 begin
1986 result := true;
1987 if (Weapon = WEAPON_KASTET) and (FSkipFist <> 0) then
1988 begin
1989 if (FSkipFist = 1) and (not (R_BERSERK in FRulez)) then
1990 result := false;
1991 end
1992 else if (FSwitchToEmpty = 0) and (not hasAmmoForShooting(Weapon)) then
1993 result := false;
1994 end;
1996 procedure TPlayer.SwitchTeam;
1997 begin
1998 if g_Game_IsClient then
1999 Exit;
2000 if not (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then Exit;
2002 if gGameOn and FAlive then
2003 Kill(K_SIMPLEKILL, FUID, HIT_SELF);
2005 if FTeam = TEAM_RED then
2006 begin
2007 ChangeTeam(TEAM_BLUE);
2008 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_BLUE], [FName]), True);
2009 if g_Game_IsNet then
2010 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_BLUE, FName);
2011 end
2012 else
2013 begin
2014 ChangeTeam(TEAM_RED);
2015 g_Console_Add(Format(_lc[I_PLAYER_CHTEAM_RED], [FName]), True);
2016 if g_Game_IsNet then
2017 MH_SEND_GameEvent(NET_EV_CHANGE_TEAM, TEAM_RED, FName);
2018 end;
2019 FPreferredTeam := FTeam;
2020 end;
2022 procedure TPlayer.ChangeTeam(Team: Byte);
2023 var
2024 OldTeam: Byte;
2025 begin
2026 OldTeam := FTeam;
2027 FTeam := Team;
2028 case Team of
2029 TEAM_RED, TEAM_BLUE:
2030 FModel.Color := TEAMCOLOR[Team];
2031 else
2032 FModel.Color := FColor;
2033 end;
2034 if (FTeam <> OldTeam) and g_Game_IsNet and g_Game_IsServer then
2035 MH_SEND_PlayerStats(FUID);
2036 end;
2039 procedure TPlayer.CollideItem();
2040 var
2041 i: Integer;
2042 r: Boolean;
2043 begin
2044 if gItems = nil then Exit;
2045 if not FAlive then Exit;
2047 for i := 0 to High(gItems) do
2048 with gItems[i] do
2049 begin
2050 if (ItemType <> ITEM_NONE) and alive then
2051 if g_Obj_Collide(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
2052 PLAYER_RECT.Height, @Obj) then
2053 begin
2054 if not PickItem(ItemType, gItems[i].Respawnable, r) then Continue;
2056 if ItemType in [ITEM_SPHERE_BLUE, ITEM_SPHERE_WHITE, ITEM_INVUL] then
2057 g_Sound_PlayExAt('SOUND_ITEM_GETRULEZ', FObj.X, FObj.Y)
2058 else if ItemType in [ITEM_MEDKIT_SMALL, ITEM_MEDKIT_LARGE, ITEM_MEDKIT_BLACK] then
2059 g_Sound_PlayExAt('SOUND_ITEM_GETMED', FObj.X, FObj.Y)
2060 else g_Sound_PlayExAt('SOUND_ITEM_GETITEM', FObj.X, FObj.Y);
2062 // Надо убрать с карты, если это не ключ, которым нужно поделится с другим игроком:
2063 if r and not ((ItemType in [ITEM_KEY_RED, ITEM_KEY_GREEN, ITEM_KEY_BLUE]) and
2064 (gGameSettings.GameType = GT_SINGLE) and
2065 (g_Player_GetCount() > 1)) then
2066 if not Respawnable then g_Items_Remove(i) else g_Items_Pick(i);
2067 end;
2068 end;
2069 end;
2072 function TPlayer.CollideLevel(XInc, YInc: Integer): Boolean;
2073 begin
2074 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
2075 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_WALL,
2076 False);
2077 end;
2079 constructor TPlayer.Create();
2080 begin
2081 viewPortX := 0;
2082 viewPortY := 0;
2083 viewPortW := 0;
2084 viewPortH := 0;
2085 mEDamageType := HIT_SOME;
2087 FIamBot := False;
2088 FDummy := False;
2089 FSpawned := False;
2091 FSawSound := TPlayableSound.Create();
2092 FSawSoundIdle := TPlayableSound.Create();
2093 FSawSoundHit := TPlayableSound.Create();
2094 FSawSoundSelect := TPlayableSound.Create();
2095 FFlameSoundOn := TPlayableSound.Create();
2096 FFlameSoundOff := TPlayableSound.Create();
2097 FFlameSoundWork := TPlayableSound.Create();
2098 FJetSoundFly := TPlayableSound.Create();
2099 FJetSoundOn := TPlayableSound.Create();
2100 FJetSoundOff := TPlayableSound.Create();
2102 FSawSound.SetByName('SOUND_WEAPON_FIRESAW');
2103 FSawSoundIdle.SetByName('SOUND_WEAPON_IDLESAW');
2104 FSawSoundHit.SetByName('SOUND_WEAPON_HITSAW');
2105 FSawSoundSelect.SetByName('SOUND_WEAPON_SELECTSAW');
2106 FFlameSoundOn.SetByName('SOUND_WEAPON_FLAMEON');
2107 FFlameSoundOff.SetByName('SOUND_WEAPON_FLAMEOFF');
2108 FFlameSoundWork.SetByName('SOUND_WEAPON_FLAMEWORK');
2109 FJetSoundFly.SetByName('SOUND_PLAYER_JETFLY');
2110 FJetSoundOn.SetByName('SOUND_PLAYER_JETON');
2111 FJetSoundOff.SetByName('SOUND_PLAYER_JETOFF');
2113 FSpectatePlayer := -1;
2114 FClientID := -1;
2115 FPing := 0;
2116 FLoss := 0;
2117 FSavedStateNum := -1;
2118 FShellTimer := -1;
2119 FFireTime := 0;
2120 FFirePainTime := 0;
2121 FFireAttacker := 0;
2122 FHandicap := 100;
2123 FCorpse := -1;
2125 FActualModelName := 'doomer';
2127 g_Obj_Init(@FObj);
2128 FObj.Rect := PLAYER_RECT;
2130 FBFGFireCounter := -1;
2131 FJustTeleported := False;
2132 FNetTime := 0;
2134 FWaitForFirstSpawn := false;
2135 FPunchAnim := TAnimationState.Create(False, 1, 4);
2136 FPunchAnim.Disable;
2138 resetWeaponQueue();
2139 end;
2141 procedure TPlayer.positionChanged (); inline;
2142 begin
2143 end;
2145 procedure TPlayer.doDamage (v: Integer);
2146 begin
2147 if (v <= 0) then exit;
2148 if (v > 32767) then v := 32767;
2149 Damage(v, 0, 0, 0, mEDamageType);
2150 end;
2152 procedure TPlayer.Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte);
2153 var
2154 c: Word;
2155 begin
2156 if (not g_Game_IsClient) and (not FAlive) then
2157 Exit;
2159 FLastHit := t;
2161 // Неуязвимость не спасает от ловушек:
2162 if ((t = HIT_TRAP) or (t = HIT_SELF)) and (not FGodMode) then
2163 begin
2164 if not g_Game_IsClient then
2165 begin
2166 FArmor := 0;
2167 if t = HIT_TRAP then
2168 begin
2169 // Ловушка убивает сразу:
2170 FHealth := -100;
2171 Kill(K_EXTRAHARDKILL, SpawnerUID, t);
2172 end;
2173 if t = HIT_SELF then
2174 begin
2175 // Самоубийство:
2176 FHealth := 0;
2177 Kill(K_SIMPLEKILL, SpawnerUID, t);
2178 end;
2179 end;
2180 // Обнулить действия примочек, чтобы фон пропал
2181 FMegaRulez[MR_SUIT] := 0;
2182 FMegaRulez[MR_INVUL] := 0;
2183 FMegaRulez[MR_INVIS] := 0;
2184 FSpawnInvul := 0;
2185 FBerserk := 0;
2186 end;
2188 // Но от остального спасает:
2189 if FMegaRulez[MR_INVUL] >= gTime then
2190 Exit;
2192 // Чит-код "ГОРЕЦ":
2193 if FGodMode then
2194 Exit;
2196 // Если есть урон своим, или ранил сам себя, или тебя ранил противник:
2197 if LongBool(gGameSettings.Options and GAME_OPTION_TEAMDAMAGE) or
2198 (SpawnerUID = FUID) or
2199 (not SameTeam(FUID, SpawnerUID)) then
2200 begin
2201 FLastSpawnerUID := SpawnerUID;
2203 // Кровь (пузырьки, если в воде):
2204 if gBloodCount > 0 then
2205 begin
2206 c := Min(value, 200)*gBloodCount + Random(Min(value, 200) div 2);
2207 if value div 4 <= c then
2208 c := c - (value div 4)
2209 else
2210 c := 0;
2212 if (t = HIT_SOME) and (vx = 0) and (vy = 0) then
2213 MakeBloodSimple(c)
2214 else
2215 case t of
2216 HIT_TRAP, HIT_ACID, HIT_FLAME, HIT_SELF: MakeBloodSimple(c);
2217 HIT_BFG, HIT_ROCKET, HIT_SOME: MakeBloodVector(c, vx, vy);
2218 end;
2220 if t = HIT_WATER then
2221 begin
2222 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
2223 FObj.Y+PLAYER_RECT.Y-4, value div 2, 8, 4);
2224 if Random(2) = 0
2225 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
2226 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
2227 end;
2228 end;
2230 // Буфер урона:
2231 if FAlive then
2232 Inc(FDamageBuffer, value);
2234 // Вспышка боли:
2235 if gFlash <> 0 then
2236 FPain := FPain + value;
2237 end;
2239 if g_Game_IsServer and g_Game_IsNet then
2240 begin
2241 MH_SEND_PlayerDamage(FUID, t, SpawnerUID, value, vx, vy);
2242 MH_SEND_PlayerStats(FUID);
2243 MH_SEND_PlayerPos(False, FUID);
2244 end;
2245 end;
2247 function TPlayer.Heal(value: Word; Soft: Boolean): Boolean;
2248 begin
2249 Result := False;
2250 if g_Game_IsClient then
2251 Exit;
2252 if not FAlive then
2253 Exit;
2255 if Soft and (FHealth < PLAYER_HP_SOFT) then
2256 begin
2257 IncMax(FHealth, value, PLAYER_HP_SOFT);
2258 Result := True;
2259 end;
2260 if (not Soft) and (FHealth < PLAYER_HP_LIMIT) then
2261 begin
2262 IncMax(FHealth, value, PLAYER_HP_LIMIT);
2263 Result := True;
2264 end;
2266 if Result and g_Game_IsServer and g_Game_IsNet then
2267 MH_SEND_PlayerStats(FUID);
2268 end;
2270 destructor TPlayer.Destroy();
2271 begin
2272 if (gPlayer1 <> nil) and (gPlayer1.FUID = FUID) then
2273 gPlayer1 := nil;
2274 if (gPlayer2 <> nil) and (gPlayer2.FUID = FUID) then
2275 gPlayer2 := nil;
2277 FSawSound.Free();
2278 FSawSoundIdle.Free();
2279 FSawSoundHit.Free();
2280 FSawSoundSelect.Free();
2281 FFlameSoundOn.Free();
2282 FFlameSoundOff.Free();
2283 FFlameSoundWork.Free();
2284 FJetSoundFly.Free();
2285 FJetSoundOn.Free();
2286 FJetSoundOff.Free();
2287 FModel.Free();
2288 FPunchAnim.Free();
2290 inherited;
2291 end;
2293 procedure TPlayer.DoPunch();
2294 begin
2295 FPunchAnim.Reset;
2296 FPunchAnim.Enable;
2297 end;
2299 procedure TPlayer.Fire();
2300 var
2301 f, DidFire: Boolean;
2302 wx, wy, xd, yd: Integer;
2303 locobj: TObj;
2304 begin
2305 if g_Game_IsClient then Exit;
2306 // FBFGFireCounter - время перед выстрелом (для BFG)
2307 // FReloading - время после выстрела (для всего)
2309 if FSpectator then
2310 begin
2311 Respawn(False);
2312 Exit;
2313 end;
2315 if FReloading[FCurrWeap] <> 0 then Exit;
2317 DidFire := False;
2319 f := False;
2320 wx := FObj.X+WEAPONPOINT[FDirection].X;
2321 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
2322 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
2323 yd := wy+firediry();
2325 case FCurrWeap of
2326 WEAPON_KASTET:
2327 begin
2328 DoPunch();
2329 if R_BERSERK in FRulez then
2330 begin
2331 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
2332 locobj.X := FObj.X+FObj.Rect.X;
2333 locobj.Y := FObj.Y+FObj.Rect.Y;
2334 locobj.rect.X := 0;
2335 locobj.rect.Y := 0;
2336 locobj.rect.Width := 39;
2337 locobj.rect.Height := 52;
2338 locobj.Vel.X := (xd-wx) div 2;
2339 locobj.Vel.Y := (yd-wy) div 2;
2340 locobj.Accel.X := xd-wx;
2341 locobj.Accel.y := yd-wy;
2343 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
2344 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
2345 else
2346 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
2348 if (gFlash = 1) and (FPain < 50) then FPain := min(FPain + 25, 50);
2349 end
2350 else
2351 begin
2352 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
2353 end;
2355 DidFire := True;
2356 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2357 end;
2359 WEAPON_SAW:
2360 begin
2361 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
2362 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
2363 begin
2364 FSawSoundSelect.Stop();
2365 FSawSound.Stop();
2366 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
2367 end
2368 else if not FSawSoundHit.IsPlaying() then
2369 begin
2370 FSawSoundSelect.Stop();
2371 FSawSound.PlayAt(FObj.X, FObj.Y);
2372 end;
2374 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2375 DidFire := True;
2376 f := True;
2377 end;
2379 WEAPON_PISTOL:
2380 if FAmmo[A_BULLETS] > 0 then
2381 begin
2382 g_Weapon_pistol(wx, wy, xd, yd, FUID);
2383 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2384 Dec(FAmmo[A_BULLETS]);
2385 FFireAngle := FAngle;
2386 f := True;
2387 DidFire := True;
2388 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2389 GameVelX, GameVelY-2, SHELL_BULLET);
2390 end;
2392 WEAPON_SHOTGUN1:
2393 if FAmmo[A_SHELLS] > 0 then
2394 begin
2395 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2396 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', wx, wy);
2397 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2398 Dec(FAmmo[A_SHELLS]);
2399 FFireAngle := FAngle;
2400 f := True;
2401 DidFire := True;
2402 FShellTimer := 10;
2403 FShellType := SHELL_SHELL;
2404 end;
2406 WEAPON_SHOTGUN2:
2407 if FAmmo[A_SHELLS] >= 2 then
2408 begin
2409 g_Weapon_dshotgun(wx, wy, xd, yd, FUID);
2410 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2411 Dec(FAmmo[A_SHELLS], 2);
2412 FFireAngle := FAngle;
2413 f := True;
2414 DidFire := True;
2415 FShellTimer := 13;
2416 FShellType := SHELL_DBLSHELL;
2417 end;
2419 WEAPON_CHAINGUN:
2420 if FAmmo[A_BULLETS] > 0 then
2421 begin
2422 g_Weapon_mgun(wx, wy, xd, yd, FUID);
2423 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', wx, wy);
2424 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2425 Dec(FAmmo[A_BULLETS]);
2426 FFireAngle := FAngle;
2427 f := True;
2428 DidFire := True;
2429 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2430 GameVelX, GameVelY-2, SHELL_BULLET);
2431 end;
2433 WEAPON_ROCKETLAUNCHER:
2434 if FAmmo[A_ROCKETS] > 0 then
2435 begin
2436 g_Weapon_rocket(wx, wy, xd, yd, FUID);
2437 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2438 Dec(FAmmo[A_ROCKETS]);
2439 FFireAngle := FAngle;
2440 f := True;
2441 DidFire := True;
2442 end;
2444 WEAPON_PLASMA:
2445 if FAmmo[A_CELLS] > 0 then
2446 begin
2447 g_Weapon_plasma(wx, wy, xd, yd, FUID);
2448 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2449 Dec(FAmmo[A_CELLS]);
2450 FFireAngle := FAngle;
2451 f := True;
2452 DidFire := True;
2453 end;
2455 WEAPON_BFG:
2456 if (FAmmo[A_CELLS] >= 40) and (FBFGFireCounter = -1) then
2457 begin
2458 FBFGFireCounter := 17;
2459 if not FNoReload then
2460 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', FObj.X, FObj.Y);
2461 Dec(FAmmo[A_CELLS], 40);
2462 DidFire := True;
2463 end;
2465 WEAPON_SUPERPULEMET:
2466 if FAmmo[A_SHELLS] > 0 then
2467 begin
2468 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2469 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', wx, wy);
2470 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2471 Dec(FAmmo[A_SHELLS]);
2472 FFireAngle := FAngle;
2473 f := True;
2474 DidFire := True;
2475 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2476 GameVelX, GameVelY-2, SHELL_SHELL);
2477 end;
2479 WEAPON_FLAMETHROWER:
2480 if FAmmo[A_FUEL] > 0 then
2481 begin
2482 g_Weapon_flame(wx, wy, xd, yd, FUID);
2483 FlamerOn;
2484 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2485 Dec(FAmmo[A_FUEL]);
2486 FFireAngle := FAngle;
2487 f := True;
2488 DidFire := True;
2489 end
2490 else
2491 begin
2492 FlamerOff;
2493 if g_Game_IsNet and g_Game_IsServer then MH_SEND_PlayerStats(FUID);
2494 end;
2495 end;
2497 if g_Game_IsNet then
2498 begin
2499 if DidFire then
2500 begin
2501 if FCurrWeap <> WEAPON_BFG then
2502 MH_SEND_PlayerFire(FUID, FCurrWeap, wx, wy, xd, yd, LastShotID)
2503 else
2504 if not FNoReload then
2505 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_WEAPON_STARTFIREBFG');
2506 end;
2508 MH_SEND_PlayerStats(FUID);
2509 end;
2511 if not f then Exit;
2513 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
2514 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
2515 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
2516 end;
2518 function TPlayer.GetAmmoByWeapon(Weapon: Byte): Word;
2519 begin
2520 case Weapon of
2521 WEAPON_PISTOL, WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS];
2522 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS];
2523 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS];
2524 WEAPON_PLASMA, WEAPON_BFG: Result := FAmmo[A_CELLS];
2525 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL];
2526 else Result := 0;
2527 end;
2528 end;
2530 function TPlayer.HeadInLiquid(XInc, YInc: Integer): Boolean;
2531 begin
2532 Result := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X+XInc, FObj.Y+PLAYER_HEADRECT.Y+YInc,
2533 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
2534 PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, True);
2535 end;
2537 procedure TPlayer.FlamerOn;
2538 begin
2539 FFlameSoundOff.Stop();
2540 FFlameSoundOff.SetPosition(0);
2541 if FFlaming then
2542 begin
2543 if (not FFlameSoundOn.IsPlaying()) and (not FFlameSoundWork.IsPlaying()) then
2544 FFlameSoundWork.PlayAt(FObj.X, FObj.Y);
2545 end
2546 else
2547 begin
2548 FFlameSoundOn.PlayAt(FObj.X, FObj.Y);
2549 FFlaming := True;
2550 end;
2551 end;
2553 procedure TPlayer.FlamerOff;
2554 begin
2555 if FFlaming then
2556 begin
2557 FFlameSoundOn.Stop();
2558 FFlameSoundOn.SetPosition(0);
2559 FFlameSoundWork.Stop();
2560 FFlameSoundWork.SetPosition(0);
2561 FFlameSoundOff.PlayAt(FObj.X, FObj.Y);
2562 FFlaming := False;
2563 end;
2564 end;
2566 procedure TPlayer.JetpackOn;
2567 begin
2568 FJetSoundFly.Stop;
2569 FJetSoundOff.Stop;
2570 FJetSoundOn.SetPosition(0);
2571 FJetSoundOn.PlayAt(FObj.X, FObj.Y);
2572 FlySmoke(8);
2573 end;
2575 procedure TPlayer.JetpackOff;
2576 begin
2577 FJetSoundFly.Stop;
2578 FJetSoundOn.Stop;
2579 FJetSoundOff.SetPosition(0);
2580 FJetSoundOff.PlayAt(FObj.X, FObj.Y);
2581 end;
2583 procedure TPlayer.CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
2584 begin
2585 if Timeout <= 0 then
2586 exit;
2587 if (FMegaRulez[MR_SUIT] > gTime) or (FMegaRulez[MR_INVUL] > gTime) then
2588 exit; // Не загораемся когда есть защита
2589 if g_Obj_CollidePanel(@FObj, 0, 0, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2) then
2590 exit; // Не подгораем в воде на всякий случай
2591 if FFireTime <= 0 then
2592 g_Sound_PlayExAt('SOUND_IGNITE', FObj.X, FObj.Y);
2593 FFireTime := Timeout;
2594 FFireAttacker := Attacker;
2595 if g_Game_IsNet and g_Game_IsServer then
2596 MH_SEND_PlayerStats(FUID);
2597 end;
2599 procedure TPlayer.Jump();
2600 begin
2601 if gFly or FJetpack then
2602 begin
2603 // Полет (чит-код или джетпак):
2604 if FObj.Vel.Y > -VEL_FLY then
2605 FObj.Vel.Y := FObj.Vel.Y - 3;
2606 if FJetpack then
2607 begin
2608 if FJetFuel > 0 then
2609 Dec(FJetFuel);
2610 if (FJetFuel < 1) and g_Game_IsServer then
2611 begin
2612 FJetpack := False;
2613 JetpackOff;
2614 if g_Game_IsNet then
2615 MH_SEND_PlayerStats(FUID);
2616 end;
2617 end;
2618 Exit;
2619 end;
2621 // Не включать джетпак в режиме прохождения сквозь стены
2622 if FGhost then
2623 FCanJetpack := False;
2625 // Прыгаем или всплываем:
2626 if (CollideLevel(0, 1) or
2627 g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y+36, PLAYER_RECT.Width,
2628 PLAYER_RECT.Height-33, PANEL_STEP, False)
2629 ) and (FObj.Accel.Y = 0) then // Не прыгать, если есть вертикальное ускорение
2630 begin
2631 FObj.Vel.Y := -VEL_JUMP;
2632 FCanJetpack := False;
2633 end
2634 else
2635 begin
2636 if BodyInLiquid(0, 0) then
2637 FObj.Vel.Y := -VEL_SW
2638 else if (FJetFuel > 0) and FCanJetpack and
2639 g_Game_IsServer and (not g_Obj_CollideLiquid(@FObj, 0, 0)) then
2640 begin
2641 FJetpack := True;
2642 JetpackOn;
2643 if g_Game_IsNet then
2644 MH_SEND_PlayerStats(FUID);
2645 end;
2646 end;
2647 end;
2649 procedure TPlayer.Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
2650 var
2651 a, i, k, ab, ar: Byte;
2652 s: String;
2653 mon: TMonster;
2654 plr: TPlayer;
2655 srv, netsrv: Boolean;
2656 DoFrags: Boolean;
2657 OldLR: Byte;
2658 KP: TPlayer;
2659 it: PItem;
2661 procedure PushItem(t: Byte);
2662 var
2663 id: DWORD;
2664 begin
2665 id := g_Items_Create(FObj.X, FObj.Y, t, True, False);
2666 it := g_Items_ByIdx(id);
2667 if KillType = K_EXTRAHARDKILL then // -7..+7; -8..0
2668 begin
2669 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-7+Random(15),
2670 (FObj.Vel.Y div 2)-Random(9));
2671 it.positionChanged(); // this updates spatial accelerators
2672 end
2673 else
2674 begin
2675 if KillType = K_HARDKILL then // -5..+5; -5..0
2676 begin
2677 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-5+Random(11),
2678 (FObj.Vel.Y div 2)-Random(6));
2679 end
2680 else // -3..+3; -3..0
2681 begin
2682 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-3+Random(7),
2683 (FObj.Vel.Y div 2)-Random(4));
2684 end;
2685 it.positionChanged(); // this updates spatial accelerators
2686 end;
2688 if g_Game_IsNet and g_Game_IsServer then
2689 MH_SEND_ItemSpawn(True, id);
2690 end;
2692 begin
2693 DoFrags := (gGameSettings.MaxLives = 0) or (gGameSettings.GameMode = GM_COOP);
2694 Srv := g_Game_IsServer;
2695 Netsrv := g_Game_IsServer and g_Game_IsNet;
2696 if Srv then FDeath := FDeath + 1;
2697 if FAlive then
2698 begin
2699 if FGhost then
2700 FGhost := False;
2701 if not FPhysics then
2702 FPhysics := True;
2703 FAlive := False;
2704 end;
2705 FShellTimer := -1;
2707 if (gGameSettings.MaxLives > 0) and Srv and (gLMSRespawn = LMS_RESPAWN_NONE) then
2708 begin
2709 if FLives > 0 then FLives := FLives - 1;
2710 if FLives = 0 then FNoRespawn := True;
2711 end;
2713 // Номер типа смерти:
2714 a := 1;
2715 case KillType of
2716 K_SIMPLEKILL: a := 1;
2717 K_HARDKILL: a := 2;
2718 K_EXTRAHARDKILL: a := 3;
2719 K_FALLKILL: a := 4;
2720 end;
2722 // Звук смерти:
2723 if not FModel.PlaySound(MODELSOUND_DIE, a, FObj.X, FObj.Y) then
2724 for i := 1 to 3 do
2725 if FModel.PlaySound(MODELSOUND_DIE, i, FObj.X, FObj.Y) then
2726 Break;
2728 // Время респауна:
2729 if Srv then
2730 case KillType of
2731 K_SIMPLEKILL:
2732 FTime[T_RESPAWN] := gTime + TIME_RESPAWN1;
2733 K_HARDKILL:
2734 FTime[T_RESPAWN] := gTime + TIME_RESPAWN2;
2735 K_EXTRAHARDKILL, K_FALLKILL:
2736 FTime[T_RESPAWN] := gTime + TIME_RESPAWN3;
2737 end;
2739 // Переключаем состояние:
2740 case KillType of
2741 K_SIMPLEKILL:
2742 SetAction(A_DIE1);
2743 K_HARDKILL, K_EXTRAHARDKILL:
2744 SetAction(A_DIE2);
2745 end;
2747 // Реакция монстров на смерть игрока:
2748 if (KillType <> K_FALLKILL) and (Srv) then
2749 g_Monsters_killedp();
2751 if SpawnerUID = FUID then
2752 begin // Самоубился
2753 if Srv then
2754 begin
2755 if gGameSettings.GameMode = GM_TDM then
2756 Dec(gTeamStat[FTeam].Score);
2757 if DoFrags or (gGameSettings.GameMode = GM_TDM) then
2758 begin
2759 Dec(FFrags);
2760 FLastFrag := 0;
2761 end;
2762 end;
2763 g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2764 end
2765 else
2766 if g_GetUIDType(SpawnerUID) = UID_PLAYER then
2767 begin // Убит другим игроком
2768 KP := g_Player_Get(SpawnerUID);
2769 if (KP <> nil) and Srv then
2770 begin
2771 if (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2772 if SameTeam(FUID, SpawnerUID) then
2773 begin
2774 Dec(KP.FFrags);
2775 KP.FLastFrag := 0;
2776 end else
2777 begin
2778 Inc(KP.FFrags);
2779 KP.FragCombo();
2780 end;
2782 if (gGameSettings.GameMode = GM_TDM) and DoFrags then
2783 Inc(gTeamStat[KP.Team].Score,
2784 IfThen(SameTeam(FUID, SpawnerUID), -1, 1));
2786 if netsrv then MH_SEND_PlayerStats(SpawnerUID);
2787 end;
2789 plr := g_Player_Get(SpawnerUID);
2790 if plr = nil then
2791 s := '?'
2792 else
2793 s := plr.FName;
2795 case KillType of
2796 K_HARDKILL:
2797 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2798 [FName, s]),
2799 gShowKillMsg);
2800 K_EXTRAHARDKILL:
2801 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2802 [FName, s]),
2803 gShowKillMsg);
2804 else
2805 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2806 [FName, s]),
2807 gShowKillMsg);
2808 end;
2809 end
2810 else if g_GetUIDType(SpawnerUID) = UID_MONSTER then
2811 begin // Убит монстром
2812 mon := g_Monsters_ByUID(SpawnerUID);
2813 if mon = nil then
2814 s := '?'
2815 else
2816 s := g_Mons_GetKilledByTypeId(mon.MonsterType);
2818 case KillType of
2819 K_HARDKILL:
2820 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2821 [FName, s]),
2822 gShowKillMsg);
2823 K_EXTRAHARDKILL:
2824 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2825 [FName, s]),
2826 gShowKillMsg);
2827 else
2828 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2829 [FName, s]),
2830 gShowKillMsg);
2831 end;
2832 end
2833 else // Особые типы смерти
2834 case t of
2835 HIT_DISCON: ;
2836 HIT_SELF: g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2837 HIT_FALL: g_Console_Add(Format(_lc[I_PLAYER_KILL_FALL], [FName]), True);
2838 HIT_WATER: g_Console_Add(Format(_lc[I_PLAYER_KILL_WATER], [FName]), True);
2839 HIT_ACID: g_Console_Add(Format(_lc[I_PLAYER_KILL_ACID], [FName]), True);
2840 HIT_TRAP: g_Console_Add(Format(_lc[I_PLAYER_KILL_TRAP], [FName]), True);
2841 else g_Console_Add(Format(_lc[I_PLAYER_DIED], [FName]), True);
2842 end;
2844 if Srv then
2845 begin
2846 // Выброс оружия:
2847 for a := WP_FIRST to WP_LAST do
2848 if FWeapon[a] then
2849 begin
2850 case a of
2851 WEAPON_SAW: i := ITEM_WEAPON_SAW;
2852 WEAPON_SHOTGUN1: i := ITEM_WEAPON_SHOTGUN1;
2853 WEAPON_SHOTGUN2: i := ITEM_WEAPON_SHOTGUN2;
2854 WEAPON_CHAINGUN: i := ITEM_WEAPON_CHAINGUN;
2855 WEAPON_ROCKETLAUNCHER: i := ITEM_WEAPON_ROCKETLAUNCHER;
2856 WEAPON_PLASMA: i := ITEM_WEAPON_PLASMA;
2857 WEAPON_BFG: i := ITEM_WEAPON_BFG;
2858 WEAPON_SUPERPULEMET: i := ITEM_WEAPON_SUPERPULEMET;
2859 WEAPON_FLAMETHROWER: i := ITEM_WEAPON_FLAMETHROWER;
2860 else i := 0;
2861 end;
2863 if i <> 0 then
2864 PushItem(i);
2865 end;
2867 // Выброс рюкзака:
2868 if R_ITEM_BACKPACK in FRulez then
2869 PushItem(ITEM_AMMO_BACKPACK);
2871 // Выброс ракетного ранца:
2872 if FJetFuel > 0 then
2873 PushItem(ITEM_JETPACK);
2875 // Выброс ключей:
2876 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) or
2877 (not LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS)) then
2878 begin
2879 if R_KEY_RED in FRulez then
2880 PushItem(ITEM_KEY_RED);
2882 if R_KEY_GREEN in FRulez then
2883 PushItem(ITEM_KEY_GREEN);
2885 if R_KEY_BLUE in FRulez then
2886 PushItem(ITEM_KEY_BLUE);
2887 end;
2889 // Выброс флага:
2890 DropFlag(KillType = K_FALLKILL);
2891 end;
2893 FCorpse := g_Player_CreateCorpse(Self);
2895 if Srv and (gGameSettings.MaxLives > 0) and FNoRespawn and
2896 (gLMSRespawn = LMS_RESPAWN_NONE) then
2897 begin
2898 a := 0;
2899 k := 0;
2900 ar := 0;
2901 ab := 0;
2902 for i := Low(gPlayers) to High(gPlayers) do
2903 begin
2904 if gPlayers[i] = nil then continue;
2905 if (not gPlayers[i].FNoRespawn) and (not gPlayers[i].FSpectator) then
2906 begin
2907 Inc(a);
2908 if gPlayers[i].FTeam = TEAM_RED then Inc(ar)
2909 else if gPlayers[i].FTeam = TEAM_BLUE then Inc(ab);
2910 k := i;
2911 end;
2912 end;
2914 OldLR := gLMSRespawn;
2915 if (gGameSettings.GameMode = GM_COOP) then
2916 begin
2917 if (a = 0) then
2918 begin
2919 // everyone is dead, restart the map
2920 g_Game_Message(_lc[I_MESSAGE_LMS_LOSE], 144);
2921 if Netsrv then
2922 MH_SEND_GameEvent(NET_EV_LMS_LOSE);
2923 gLMSRespawn := LMS_RESPAWN_FINAL;
2924 gLMSRespawnTime := gTime + 5000;
2925 end
2926 else if (a = 1) then
2927 begin
2928 if (gPlayers[k] <> nil) and not (gPlayers[k] is TBot) then
2929 if (gPlayers[k] = gPlayer1) or
2930 (gPlayers[k] = gPlayer2) then
2931 g_Console_Add('*** ' + _lc[I_MESSAGE_LMS_SURVIVOR] + ' ***', True)
2932 else if Netsrv and (gPlayers[k].FClientID >= 0) then
2933 MH_SEND_GameEvent(NET_EV_LMS_SURVIVOR, 0, 'N', gPlayers[k].FClientID);
2934 end;
2935 end
2936 else if (gGameSettings.GameMode = GM_TDM) then
2937 begin
2938 if (ab = 0) and (ar <> 0) then
2939 begin
2940 // blu team ded
2941 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 144);
2942 if Netsrv then
2943 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_RED);
2944 Inc(gTeamStat[TEAM_RED].Score);
2945 gLMSRespawn := LMS_RESPAWN_FINAL;
2946 gLMSRespawnTime := gTime + 5000;
2947 end
2948 else if (ar = 0) and (ab <> 0) then
2949 begin
2950 // red team ded
2951 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 144);
2952 if Netsrv then
2953 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_BLUE);
2954 Inc(gTeamStat[TEAM_BLUE].Score);
2955 gLMSRespawn := LMS_RESPAWN_FINAL;
2956 gLMSRespawnTime := gTime + 5000;
2957 end
2958 else if (ar = 0) and (ab = 0) then
2959 begin
2960 // everyone ded
2961 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2962 if Netsrv then
2963 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2964 gLMSRespawn := LMS_RESPAWN_FINAL;
2965 gLMSRespawnTime := gTime + 5000;
2966 end;
2967 end
2968 else if (gGameSettings.GameMode = GM_DM) then
2969 begin
2970 if (a = 1) then
2971 begin
2972 if gPlayers[k] <> nil then
2973 with gPlayers[k] do
2974 begin
2975 // survivor is the winner
2976 g_Game_Message(Format(_lc[I_MESSAGE_LMS_WIN], [AnsiUpperCase(FName)]), 144);
2977 if Netsrv then
2978 MH_SEND_GameEvent(NET_EV_LMS_WIN, 0, FName);
2979 Inc(FFrags);
2980 end;
2981 gLMSRespawn := LMS_RESPAWN_FINAL;
2982 gLMSRespawnTime := gTime + 5000;
2983 end
2984 else if (a = 0) then
2985 begin
2986 // everyone is dead, restart the map
2987 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2988 if Netsrv then
2989 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2990 gLMSRespawn := LMS_RESPAWN_FINAL;
2991 gLMSRespawnTime := gTime + 5000;
2992 end;
2993 end;
2994 if srv and (OldLR = LMS_RESPAWN_NONE) and (gLMSRespawn > LMS_RESPAWN_NONE) then
2995 begin
2996 if NetMode = NET_SERVER then
2997 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime)
2998 else
2999 g_Console_Add(Format(_lc[I_MSG_WARMUP_START], [(gLMSRespawnTime - gTime) div 1000]), True);
3000 end;
3001 end;
3003 if Netsrv then
3004 begin
3005 MH_SEND_PlayerStats(FUID);
3006 MH_SEND_PlayerDeath(FUID, KillType, t, SpawnerUID);
3007 if gGameSettings.GameMode = GM_TDM then MH_SEND_GameStats;
3008 end;
3010 if srv and FNoRespawn then Spectate(True);
3011 FWantsInGame := True;
3012 end;
3014 function TPlayer.BodyInLiquid(XInc, YInc: Integer): Boolean;
3015 begin
3016 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3017 PLAYER_RECT.Height-20, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, False);
3018 end;
3020 function TPlayer.BodyInAcid(XInc, YInc: Integer): Boolean;
3021 begin
3022 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3023 PLAYER_RECT.Height-20, PANEL_ACID1 or PANEL_ACID2, False);
3024 end;
3026 procedure TPlayer.MakeBloodSimple(Count: Word);
3027 var Blood: TModelBlood;
3028 begin
3029 Blood := SELF.FModel.GetBlood();
3030 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)+8,
3031 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3032 Count div 2, 3, -1, 16, (PLAYER_RECT.Height*2 div 3),
3033 Blood.R, Blood.G, Blood.B, Blood.Kind);
3034 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-8,
3035 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3036 Count div 2, -3, -1, 16, (PLAYER_RECT.Height*2) div 3,
3037 Blood.R, Blood.G, Blood.B, Blood.Kind);
3038 end;
3040 procedure TPlayer.MakeBloodVector(Count: Word; VelX, VelY: Integer);
3041 var Blood: TModelBlood;
3042 begin
3043 Blood := SELF.FModel.GetBlood();
3044 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
3045 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3046 Count, VelX, VelY, 16, (PLAYER_RECT.Height*2) div 3,
3047 Blood.R, Blood.G, Blood.B, Blood.Kind);
3048 end;
3050 procedure TPlayer.ProcessWeaponAction(Action: Byte);
3051 begin
3052 if g_Game_IsClient then Exit;
3053 case Action of
3054 WP_PREV: PrevWeapon();
3055 WP_NEXT: NextWeapon();
3056 end;
3057 end;
3059 procedure TPlayer.QueueWeaponSwitch(Weapon: Byte);
3060 begin
3061 if g_Game_IsClient then Exit;
3062 if Weapon > High(FWeapon) then Exit;
3063 FNextWeap := FNextWeap or (1 shl Weapon);
3064 end;
3066 procedure TPlayer.resetWeaponQueue ();
3067 begin
3068 FNextWeap := 0;
3069 FNextWeapDelay := 0;
3070 end;
3072 function TPlayer.hasAmmoForWeapon (weapon: Byte): Boolean;
3073 begin
3074 result := false;
3075 case weapon of
3076 WEAPON_KASTET, WEAPON_SAW: result := true;
3077 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3078 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3079 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3080 WEAPON_PLASMA, WEAPON_BFG: result := (FAmmo[A_CELLS] > 0);
3081 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3082 else result := (weapon < length(FWeapon));
3083 end;
3084 end;
3086 function TPlayer.hasAmmoForShooting (weapon: Byte): Boolean;
3087 begin
3088 result := false;
3089 case weapon of
3090 WEAPON_KASTET, WEAPON_SAW: result := true;
3091 WEAPON_SHOTGUN1, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3092 WEAPON_SHOTGUN2: result := (FAmmo[A_SHELLS] > 1);
3093 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3094 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3095 WEAPON_PLASMA: result := (FAmmo[A_CELLS] > 0);
3096 WEAPON_BFG: result := (FAmmo[A_CELLS] >= 40);
3097 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3098 else result := (weapon < length(FWeapon));
3099 end;
3100 end;
3102 function TPlayer.shouldSwitch (weapon: Byte; hadWeapon: Boolean): Boolean;
3103 begin
3104 result := false;
3105 if (weapon > WP_LAST + 1) then
3106 begin
3107 result := false;
3108 exit;
3109 end;
3110 if (FWeapSwitchMode = 1) and not hadWeapon then
3111 result := true
3112 else if (FWeapSwitchMode = 2) then
3113 result := (FWeapPreferences[weapon] > FWeapPreferences[FCurrWeap]);
3114 end;
3116 // return 255 for "no switch"
3117 function TPlayer.getNextWeaponIndex (): Byte;
3118 var
3119 i: Word;
3120 wantThisWeapon: array[0..64] of Boolean;
3121 wwc: Integer = 0; //HACK!
3122 dir, cwi: Integer;
3123 begin
3124 result := 255; // default result: "no switch"
3125 //e_LogWriteFln('FSWITCHTOEMPTY: %s', [FSwitchToEmpty], TMsgType.Notify);
3126 // had weapon cycling on previous frame? remove that flag
3127 if (FNextWeap and $2000) <> 0 then
3128 begin
3129 FNextWeap := FNextWeap and $1FFF;
3130 FNextWeapDelay := 0;
3131 end;
3132 // cycling has priority
3133 if (FNextWeap and $C000) <> 0 then
3134 begin
3135 if (FNextWeap and $8000) <> 0 then
3136 dir := 1
3137 else
3138 dir := -1;
3139 FNextWeap := FNextWeap or $2000; // we need this
3140 if FNextWeapDelay > 0 then
3141 exit; // cooldown time
3142 cwi := FCurrWeap;
3143 for i := 0 to High(FWeapon) do
3144 begin
3145 cwi := (cwi+length(FWeapon)+dir) mod length(FWeapon);
3146 if FWeapon[cwi] and maySwitch(cwi) then
3147 begin
3148 //e_LogWriteFln(' SWITCH: cur=%d; new=%d %s %s', [FCurrWeap, cwi, FSwitchToEmpty, hasAmmoForWeapon(cwi)], TMsgType.Notify);
3149 result := Byte(cwi);
3150 FNextWeapDelay := WEAPON_DELAY;
3151 exit;
3152 end;
3153 end;
3154 resetWeaponQueue();
3155 exit;
3156 end;
3157 // no cycling
3158 for i := 0 to High(wantThisWeapon) do
3159 wantThisWeapon[i] := false;
3160 for i := 0 to High(FWeapon) do
3161 if (FNextWeap and (1 shl i)) <> 0 then
3162 begin
3163 wantThisWeapon[i] := true;
3164 Inc(wwc);
3165 end;
3167 // exclude currently selected weapon from the set
3168 wantThisWeapon[FCurrWeap] := false;
3169 // slow down alterations a little
3170 if wwc > 1 then
3171 begin
3172 //e_WriteLog(Format(' FNextWeap=%x; delay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3173 // more than one weapon requested, assume "alteration" and check alteration delay
3174 if FNextWeapDelay > 0 then
3175 begin
3176 FNextWeap := 0;
3177 exit;
3178 end; // yeah
3179 end;
3180 // do not reset weapon queue, it will be done in `RealizeCurrentWeapon()`
3181 // but clear all counters if no weapon should be switched
3182 if wwc < 1 then
3183 begin
3184 resetWeaponQueue();
3185 exit;
3186 end;
3187 //e_WriteLog(Format('wwc=%d', [wwc]), MSG_WARNING);
3188 // try weapons in descending order
3189 for i := High(FWeapon) downto 0 do
3190 begin
3191 if wantThisWeapon[i] and FWeapon[i] and ((wwc = 1) or hasAmmoForWeapon(i)) then
3192 begin
3193 // i found her!
3194 result := Byte(i);
3195 resetWeaponQueue();
3196 FNextWeapDelay := WEAPON_DELAY * 2; // anyway, 'cause why not
3197 //e_LogWriteFln('FOUND %s %s %s', [result, FSwitchToEmpty, hasAmmoForWeapon(i)], TMsgType.Notify);
3198 exit;
3199 end;
3200 end;
3201 // no suitable weapon found, so reset the queue, to avoid accidental "queuing" of weapon w/o ammo
3202 resetWeaponQueue();
3203 end;
3205 procedure TPlayer.RealizeCurrentWeapon();
3206 function switchAllowed (): Boolean;
3207 var
3208 i: Byte;
3209 begin
3210 result := false;
3211 if FBFGFireCounter <> -1 then
3212 exit;
3213 if FTime[T_SWITCH] > gTime then
3214 exit;
3215 for i := WP_FIRST to WP_LAST do
3216 if FReloading[i] > 0 then
3217 exit;
3218 result := true;
3219 end;
3221 var
3222 nw: Byte;
3223 begin
3224 //e_WriteLog(Format('***RealizeCurrentWeapon: FNextWeap=%x; FNextWeapDelay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3225 //FNextWeap := FNextWeap and $1FFF;
3226 if FNextWeapDelay > 0 then Dec(FNextWeapDelay); // "alteration delay"
3228 if not switchAllowed then
3229 begin
3230 //HACK for weapon cycling
3231 if (FNextWeap and $E000) <> 0 then FNextWeap := 0;
3232 exit;
3233 end;
3235 nw := getNextWeaponIndex();
3236 //
3237 if nw = 255 then exit; // don't reset anything here
3238 if nw > High(FWeapon) then
3239 begin
3240 // don't forget to reset queue here!
3241 //e_WriteLog(' RealizeCurrentWeapon: WUTAFUUUU', MSG_WARNING);
3242 resetWeaponQueue();
3243 exit;
3244 end;
3246 if FWeapon[nw] then
3247 begin
3248 FCurrWeap := nw;
3249 FTime[T_SWITCH] := gTime+156;
3250 if FCurrWeap = WEAPON_SAW then FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3251 FModel.SetWeapon(FCurrWeap);
3252 if g_Game_IsNet then MH_SEND_PlayerStats(FUID);
3253 end;
3254 end;
3256 procedure TPlayer.NextWeapon();
3257 begin
3258 if g_Game_IsClient then Exit;
3259 FNextWeap := $8000;
3260 end;
3262 procedure TPlayer.PrevWeapon();
3263 begin
3264 if g_Game_IsClient then Exit;
3265 FNextWeap := $4000;
3266 end;
3268 procedure TPlayer.SetWeapon(W: Byte);
3269 begin
3270 if FCurrWeap <> W then
3271 if W = WEAPON_SAW then
3272 FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3274 FCurrWeap := W;
3275 FModel.SetWeapon(CurrWeap);
3276 resetWeaponQueue();
3277 end;
3279 function TPlayer.PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean;
3280 var
3281 a: Boolean;
3282 switchWeapon: Byte = 255;
3283 hadWeapon: Boolean = False;
3284 begin
3285 Result := False;
3286 if g_Game_IsClient then Exit;
3288 // a = true - место спавна предмета:
3289 a := LongBool(gGameSettings.Options and GAME_OPTION_WEAPONSTAY) and arespawn;
3290 remove := not a;
3291 case ItemType of
3292 ITEM_MEDKIT_SMALL:
3293 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3294 begin
3295 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
3296 Result := True;
3297 remove := True;
3298 FFireTime := 0;
3299 if gFlash = 2 then Inc(FPickup, 5);
3300 end;
3302 ITEM_MEDKIT_LARGE:
3303 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3304 begin
3305 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
3306 Result := True;
3307 remove := True;
3308 FFireTime := 0;
3309 if gFlash = 2 then Inc(FPickup, 5);
3310 end;
3312 ITEM_ARMOR_GREEN:
3313 if FArmor < PLAYER_AP_SOFT then
3314 begin
3315 FArmor := PLAYER_AP_SOFT;
3316 Result := True;
3317 remove := True;
3318 if gFlash = 2 then Inc(FPickup, 5);
3319 end;
3321 ITEM_ARMOR_BLUE:
3322 if FArmor < PLAYER_AP_LIMIT then
3323 begin
3324 FArmor := PLAYER_AP_LIMIT;
3325 Result := True;
3326 remove := True;
3327 if gFlash = 2 then Inc(FPickup, 5);
3328 end;
3330 ITEM_SPHERE_BLUE:
3331 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3332 begin
3333 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
3334 Result := True;
3335 remove := True;
3336 FFireTime := 0;
3337 if gFlash = 2 then Inc(FPickup, 5);
3338 end;
3340 ITEM_SPHERE_WHITE:
3341 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) or (FFireTime > 0) then
3342 begin
3343 if FHealth < PLAYER_HP_LIMIT then
3344 FHealth := PLAYER_HP_LIMIT;
3345 if FArmor < PLAYER_AP_LIMIT then
3346 FArmor := PLAYER_AP_LIMIT;
3347 Result := True;
3348 remove := True;
3349 FFireTime := 0;
3350 if gFlash = 2 then Inc(FPickup, 5);
3351 end;
3353 ITEM_WEAPON_SAW:
3354 if (not FWeapon[WEAPON_SAW]) or ((not arespawn) and (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) then
3355 begin
3356 hadWeapon := FWeapon[WEAPON_SAW];
3357 switchWeapon := WEAPON_SAW;
3358 FWeapon[WEAPON_SAW] := True;
3359 Result := True;
3360 if gFlash = 2 then Inc(FPickup, 5);
3361 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3362 end;
3364 ITEM_WEAPON_SHOTGUN1:
3365 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN1] then
3366 begin
3367 // Нужно, чтобы не взять все пули сразу:
3368 if a and FWeapon[WEAPON_SHOTGUN1] then Exit;
3369 hadWeapon := FWeapon[WEAPON_SHOTGUN1];
3370 switchWeapon := WEAPON_SHOTGUN1;
3371 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3372 FWeapon[WEAPON_SHOTGUN1] := True;
3373 Result := True;
3374 if gFlash = 2 then Inc(FPickup, 5);
3375 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3376 end;
3378 ITEM_WEAPON_SHOTGUN2:
3379 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN2] then
3380 begin
3381 if a and FWeapon[WEAPON_SHOTGUN2] then Exit;
3382 hadWeapon := FWeapon[WEAPON_SHOTGUN2];
3383 switchWeapon := WEAPON_SHOTGUN2;
3384 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3385 FWeapon[WEAPON_SHOTGUN2] := True;
3386 Result := True;
3387 if gFlash = 2 then Inc(FPickup, 5);
3388 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3389 end;
3391 ITEM_WEAPON_CHAINGUN:
3392 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or not FWeapon[WEAPON_CHAINGUN] then
3393 begin
3394 if a and FWeapon[WEAPON_CHAINGUN] then Exit;
3395 hadWeapon := FWeapon[WEAPON_CHAINGUN];
3396 switchWeapon := WEAPON_CHAINGUN;
3397 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3398 FWeapon[WEAPON_CHAINGUN] := True;
3399 Result := True;
3400 if gFlash = 2 then Inc(FPickup, 5);
3401 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3402 end;
3404 ITEM_WEAPON_ROCKETLAUNCHER:
3405 if (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or not FWeapon[WEAPON_ROCKETLAUNCHER] then
3406 begin
3407 if a and FWeapon[WEAPON_ROCKETLAUNCHER] then Exit;
3408 switchWeapon := WEAPON_ROCKETLAUNCHER;
3409 hadWeapon := FWeapon[WEAPON_ROCKETLAUNCHER];
3410 IncMax(FAmmo[A_ROCKETS], 2, FMaxAmmo[A_ROCKETS]);
3411 FWeapon[WEAPON_ROCKETLAUNCHER] := True;
3412 Result := True;
3413 if gFlash = 2 then Inc(FPickup, 5);
3414 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3415 end;
3417 ITEM_WEAPON_PLASMA:
3418 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_PLASMA] then
3419 begin
3420 if a and FWeapon[WEAPON_PLASMA] then Exit;
3421 switchWeapon := WEAPON_PLASMA;
3422 hadWeapon := FWeapon[WEAPON_PLASMA];
3423 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3424 FWeapon[WEAPON_PLASMA] := True;
3425 Result := True;
3426 if gFlash = 2 then Inc(FPickup, 5);
3427 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3428 end;
3430 ITEM_WEAPON_BFG:
3431 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_BFG] then
3432 begin
3433 if a and FWeapon[WEAPON_BFG] then Exit;
3434 switchWeapon := WEAPON_BFG;
3435 hadWeapon := FWeapon[WEAPON_BFG];
3436 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3437 FWeapon[WEAPON_BFG] := True;
3438 Result := True;
3439 if gFlash = 2 then Inc(FPickup, 5);
3440 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3441 end;
3443 ITEM_WEAPON_SUPERPULEMET:
3444 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SUPERPULEMET] then
3445 begin
3446 if a and FWeapon[WEAPON_SUPERPULEMET] then Exit;
3447 switchWeapon := WEAPON_SUPERPULEMET;
3448 hadWeapon := FWeapon[WEAPON_SUPERPULEMET];
3449 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3450 FWeapon[WEAPON_SUPERPULEMET] := True;
3451 Result := True;
3452 if gFlash = 2 then Inc(FPickup, 5);
3453 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3454 end;
3456 ITEM_WEAPON_FLAMETHROWER:
3457 if (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) or not FWeapon[WEAPON_FLAMETHROWER] then
3458 begin
3459 if a and FWeapon[WEAPON_FLAMETHROWER] then Exit;
3460 switchWeapon := WEAPON_FLAMETHROWER;
3461 hadWeapon := FWeapon[WEAPON_FLAMETHROWER];
3462 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3463 FWeapon[WEAPON_FLAMETHROWER] := True;
3464 Result := True;
3465 if gFlash = 2 then Inc(FPickup, 5);
3466 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3467 end;
3469 ITEM_AMMO_BULLETS:
3470 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3471 begin
3472 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3473 Result := True;
3474 remove := True;
3475 if gFlash = 2 then Inc(FPickup, 5);
3476 end;
3478 ITEM_AMMO_BULLETS_BOX:
3479 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3480 begin
3481 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3482 Result := True;
3483 remove := True;
3484 if gFlash = 2 then Inc(FPickup, 5);
3485 end;
3487 ITEM_AMMO_SHELLS:
3488 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3489 begin
3490 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3491 Result := True;
3492 remove := True;
3493 if gFlash = 2 then Inc(FPickup, 5);
3494 end;
3496 ITEM_AMMO_SHELLS_BOX:
3497 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3498 begin
3499 IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
3500 Result := True;
3501 remove := True;
3502 if gFlash = 2 then Inc(FPickup, 5);
3503 end;
3505 ITEM_AMMO_ROCKET:
3506 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3507 begin
3508 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3509 Result := True;
3510 remove := True;
3511 if gFlash = 2 then Inc(FPickup, 5);
3512 end;
3514 ITEM_AMMO_ROCKET_BOX:
3515 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3516 begin
3517 IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
3518 Result := True;
3519 remove := True;
3520 if gFlash = 2 then Inc(FPickup, 5);
3521 end;
3523 ITEM_AMMO_CELL:
3524 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3525 begin
3526 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3527 Result := True;
3528 remove := True;
3529 if gFlash = 2 then Inc(FPickup, 5);
3530 end;
3532 ITEM_AMMO_CELL_BIG:
3533 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3534 begin
3535 IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
3536 Result := True;
3537 remove := True;
3538 if gFlash = 2 then Inc(FPickup, 5);
3539 end;
3541 ITEM_AMMO_FUELCAN:
3542 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3543 begin
3544 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3545 Result := True;
3546 remove := True;
3547 if gFlash = 2 then Inc(FPickup, 5);
3548 end;
3550 ITEM_AMMO_BACKPACK:
3551 if not(R_ITEM_BACKPACK in FRulez) or
3552 (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
3553 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
3554 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
3555 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
3556 (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) then
3557 begin
3558 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
3559 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
3560 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
3561 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
3562 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
3564 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3565 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3566 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3567 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3568 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3569 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3570 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3571 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3572 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3573 IncMax(FAmmo[A_FUEL], 50, FMaxAmmo[A_FUEL]);
3575 FRulez := FRulez + [R_ITEM_BACKPACK];
3576 Result := True;
3577 remove := True;
3578 if gFlash = 2 then Inc(FPickup, 5);
3579 end;
3581 ITEM_KEY_RED:
3582 if not(R_KEY_RED in FRulez) then
3583 begin
3584 Include(FRulez, R_KEY_RED);
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_GREEN:
3592 if not(R_KEY_GREEN in FRulez) then
3593 begin
3594 Include(FRulez, R_KEY_GREEN);
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_KEY_BLUE:
3602 if not(R_KEY_BLUE in FRulez) then
3603 begin
3604 Include(FRulez, R_KEY_BLUE);
3605 Result := True;
3606 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3607 if gFlash = 2 then Inc(FPickup, 5);
3608 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3609 end;
3611 ITEM_SUIT:
3612 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
3613 begin
3614 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
3615 Result := True;
3616 remove := True;
3617 FFireTime := 0;
3618 if gFlash = 2 then Inc(FPickup, 5);
3619 end;
3621 ITEM_OXYGEN:
3622 if FAir < AIR_MAX then
3623 begin
3624 FAir := AIR_MAX;
3625 Result := True;
3626 remove := True;
3627 if gFlash = 2 then Inc(FPickup, 5);
3628 end;
3630 ITEM_MEDKIT_BLACK:
3631 begin
3632 if not (R_BERSERK in FRulez) then
3633 begin
3634 Include(FRulez, R_BERSERK);
3635 if (FBFGFireCounter = -1) then
3636 begin
3637 FCurrWeap := WEAPON_KASTET;
3638 resetWeaponQueue();
3639 FModel.SetWeapon(WEAPON_KASTET);
3640 end;
3641 if gFlash <> 0 then
3642 begin
3643 Inc(FPain, 100);
3644 if gFlash = 2 then Inc(FPickup, 5);
3645 end;
3646 FBerserk := gTime+30000;
3647 Result := True;
3648 remove := True;
3649 FFireTime := 0;
3650 end;
3651 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3652 begin
3653 if FHealth < PLAYER_HP_SOFT then FHealth := PLAYER_HP_SOFT;
3654 FBerserk := gTime+30000;
3655 Result := True;
3656 remove := True;
3657 FFireTime := 0;
3658 end;
3659 end;
3661 ITEM_INVUL:
3662 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
3663 begin
3664 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
3665 FSpawnInvul := 0;
3666 Result := True;
3667 remove := True;
3668 if gFlash = 2 then Inc(FPickup, 5);
3669 end;
3671 ITEM_BOTTLE:
3672 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3673 begin
3674 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
3675 Result := True;
3676 remove := True;
3677 FFireTime := 0;
3678 if gFlash = 2 then Inc(FPickup, 5);
3679 end;
3681 ITEM_HELMET:
3682 if FArmor < PLAYER_AP_LIMIT then
3683 begin
3684 IncMax(FArmor, 5, PLAYER_AP_LIMIT);
3685 Result := True;
3686 remove := True;
3687 if gFlash = 2 then Inc(FPickup, 5);
3688 end;
3690 ITEM_JETPACK:
3691 if FJetFuel < JET_MAX then
3692 begin
3693 FJetFuel := JET_MAX;
3694 Result := True;
3695 remove := True;
3696 if gFlash = 2 then Inc(FPickup, 5);
3697 end;
3699 ITEM_INVIS:
3700 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
3701 begin
3702 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
3703 Result := True;
3704 remove := True;
3705 if gFlash = 2 then Inc(FPickup, 5);
3706 end;
3707 end;
3709 if (shouldSwitch(switchWeapon, hadWeapon)) then
3710 QueueWeaponSwitch(switchWeapon);
3711 end;
3713 procedure TPlayer.Touch();
3714 begin
3715 if not FAlive then
3716 Exit;
3717 //FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
3718 if FIamBot then
3719 begin
3720 // Бросить флаг товарищу:
3721 if gGameSettings.GameMode = GM_CTF then
3722 DropFlag();
3723 end;
3724 end;
3726 procedure TPlayer.Push(vx, vy: Integer);
3727 begin
3728 if (not FPhysics) and FGhost then
3729 Exit;
3730 FObj.Accel.X := FObj.Accel.X + vx;
3731 FObj.Accel.Y := FObj.Accel.Y + vy;
3732 if g_Game_IsNet and g_Game_IsServer then
3733 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3734 end;
3736 procedure TPlayer.Reset(Force: Boolean);
3737 begin
3738 if Force then
3739 FAlive := False;
3741 FSpawned := False;
3742 FTime[T_RESPAWN] := 0;
3743 FTime[T_FLAGCAP] := 0;
3744 FGodMode := False;
3745 FNoTarget := False;
3746 FNoReload := False;
3747 FFrags := 0;
3748 FLastFrag := 0;
3749 FComboEvnt := -1;
3750 FKills := 0;
3751 FMonsterKills := 0;
3752 FDeath := 0;
3753 FSecrets := 0;
3754 FSpawnInvul := 0;
3755 FCorpse := -1;
3756 FReady := False;
3757 if FNoRespawn then
3758 begin
3759 FSpectator := False;
3760 FGhost := False;
3761 FPhysics := True;
3762 FSpectatePlayer := -1;
3763 FNoRespawn := False;
3764 end;
3765 FLives := gGameSettings.MaxLives;
3767 SetFlag(FLAG_NONE);
3768 end;
3770 procedure TPlayer.SoftReset();
3771 begin
3772 ReleaseKeys();
3774 FDamageBuffer := 0;
3775 FSlopeOld := 0;
3776 FIncCamOld := 0;
3777 FIncCam := 0;
3778 FBFGFireCounter := -1;
3779 FShellTimer := -1;
3780 FPain := 0;
3781 FLastHit := 0;
3782 FLastFrag := 0;
3783 FComboEvnt := -1;
3785 SetFlag(FLAG_NONE);
3786 SetAction(A_STAND, True);
3787 end;
3789 function TPlayer.GetRespawnPoint(): Byte;
3790 var
3791 c: Byte;
3792 begin
3793 Result := 255;
3794 // На будущее: FSpawn - игрок уже играл и перерождается
3796 // Одиночная игра/кооператив
3797 if gGameSettings.GameMode in [GM_COOP, GM_SINGLE] then
3798 begin
3799 if Self = gPlayer1 then
3800 begin
3801 // player 1 should try to spawn on the player 1 point
3802 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3803 Exit(RESPAWNPOINT_PLAYER1)
3804 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3805 Exit(RESPAWNPOINT_PLAYER2);
3806 end
3807 else if Self = gPlayer2 then
3808 begin
3809 // player 2 should try to spawn on the player 2 point
3810 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3811 Exit(RESPAWNPOINT_PLAYER2)
3812 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3813 Exit(RESPAWNPOINT_PLAYER1);
3814 end
3815 else
3816 begin
3817 // other players randomly pick either the first or the second point
3818 c := IfThen((Random(2) = 0), RESPAWNPOINT_PLAYER1, RESPAWNPOINT_PLAYER2);
3819 if g_Map_GetPointCount(c) > 0 then
3820 Exit(c);
3821 // try the other one
3822 c := IfThen((c = RESPAWNPOINT_PLAYER1), RESPAWNPOINT_PLAYER2, RESPAWNPOINT_PLAYER1);
3823 if g_Map_GetPointCount(c) > 0 then
3824 Exit(c);
3825 end;
3826 end;
3828 // Мясоповал
3829 if gGameSettings.GameMode = GM_DM then
3830 begin
3831 // try DM points first
3832 if g_Map_GetPointCount(RESPAWNPOINT_DM) > 0 then
3833 Exit(RESPAWNPOINT_DM);
3834 end;
3836 // Командные
3837 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3838 begin
3839 // try team points first
3840 c := RESPAWNPOINT_DM;
3841 if FTeam = TEAM_RED then
3842 c := RESPAWNPOINT_RED
3843 else if FTeam = TEAM_BLUE then
3844 c := RESPAWNPOINT_BLUE;
3845 if g_Map_GetPointCount(c) > 0 then
3846 Exit(c);
3847 end;
3849 // still haven't found a spawnpoint, try random shit
3850 Result := g_Map_GetRandomPointType();
3851 end;
3853 procedure TPlayer.Respawn(Silent: Boolean; Force: Boolean = False);
3854 var
3855 RespawnPoint: TRespawnPoint;
3856 a, b, c: Byte;
3857 begin
3858 FSlopeOld := 0;
3859 FIncCamOld := 0;
3860 FIncCam := 0;
3861 FBFGFireCounter := -1;
3862 FShellTimer := -1;
3863 FPain := 0;
3864 FLastHit := 0;
3865 FSpawnInvul := 0;
3866 FCorpse := -1;
3868 if not g_Game_IsServer then
3869 Exit;
3870 if FDummy then
3871 Exit;
3872 FWantsInGame := True;
3873 FJustTeleported := True;
3874 if Force then
3875 begin
3876 FTime[T_RESPAWN] := 0;
3877 FAlive := False;
3878 end;
3879 FNetTime := 0;
3880 // if server changes MaxLives we gotta be ready
3881 if gGameSettings.MaxLives = 0 then FNoRespawn := False;
3883 // Еще нельзя возродиться:
3884 if FTime[T_RESPAWN] > gTime then
3885 Exit;
3887 // Просрал все жизни:
3888 if FNoRespawn then
3889 begin
3890 if not FSpectator then Spectate(True);
3891 FWantsInGame := True;
3892 Exit;
3893 end;
3895 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.GameMode <> GM_COOP) then
3896 begin // "Своя игра"
3897 // Берсерк не сохраняется между уровнями:
3898 FRulez := FRulez-[R_BERSERK];
3899 end
3900 else // "Одиночная игра"/"Кооп"
3901 begin
3902 // Берсерк и ключи не сохраняются между уровнями:
3903 FRulez := FRulez-[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE, R_BERSERK];
3904 end;
3906 // Получаем точку спауна игрока:
3907 c := GetRespawnPoint();
3909 ReleaseKeys();
3910 SetFlag(FLAG_NONE);
3912 // Воскрешение без оружия:
3913 if not FAlive then
3914 begin
3915 FHealth := Round(PLAYER_HP_SOFT * (FHandicap / 100));
3916 FArmor := 0;
3917 FAlive := True;
3918 FAir := AIR_DEF;
3919 FJetFuel := 0;
3921 for a := WP_FIRST to WP_LAST do
3922 begin
3923 FWeapon[a] := False;
3924 FReloading[a] := 0;
3925 end;
3927 FWeapon[WEAPON_PISTOL] := True;
3928 FWeapon[WEAPON_KASTET] := True;
3929 FCurrWeap := WEAPON_PISTOL;
3930 resetWeaponQueue();
3932 FModel.SetWeapon(FCurrWeap);
3934 for b := A_BULLETS to A_HIGH do
3935 FAmmo[b] := 0;
3937 FAmmo[A_BULLETS] := 50;
3939 FMaxAmmo[A_BULLETS] := AmmoLimits[0, A_BULLETS];
3940 FMaxAmmo[A_SHELLS] := AmmoLimits[0, A_SHELLS];
3941 FMaxAmmo[A_ROCKETS] := AmmoLimits[0, A_SHELLS];
3942 FMaxAmmo[A_CELLS] := AmmoLimits[0, A_CELLS];
3943 FMaxAmmo[A_FUEL] := AmmoLimits[0, A_FUEL];
3945 if (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) and
3946 LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS) then
3947 FRulez := [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE]
3948 else
3949 FRulez := [];
3950 end;
3952 // Получаем координаты точки возрождения:
3953 if not g_Map_GetPoint(c, RespawnPoint) then
3954 begin
3955 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3956 Exit;
3957 end;
3959 // Установка координат и сброс всех параметров:
3960 FObj.X := RespawnPoint.X-PLAYER_RECT.X;
3961 FObj.Y := RespawnPoint.Y-PLAYER_RECT.Y;
3962 FObj.oldX := FObj.X; // don't interpolate after respawn
3963 FObj.oldY := FObj.Y;
3964 FObj.Vel.X := 0;
3965 FObj.Vel.Y := 0;
3966 FObj.Accel.X := 0;
3967 FObj.Accel.Y := 0;
3969 FDirection := RespawnPoint.Direction;
3970 if FDirection = TDirection.D_LEFT then
3971 FAngle := 180
3972 else
3973 FAngle := 0;
3975 SetAction(A_STAND, True);
3976 FModel.Direction := FDirection;
3978 for a := Low(FTime) to High(FTime) do
3979 FTime[a] := 0;
3981 for a := Low(FMegaRulez) to High(FMegaRulez) do
3982 FMegaRulez[a] := 0;
3984 // Respawn invulnerability
3985 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.SpawnInvul > 0) then
3986 begin
3987 FMegaRulez[MR_INVUL] := gTime + gGameSettings.SpawnInvul * 1000;
3988 FSpawnInvul := FMegaRulez[MR_INVUL];
3989 end;
3991 FDamageBuffer := 0;
3992 FJetpack := False;
3993 FCanJetpack := False;
3994 FFlaming := False;
3995 FFireTime := 0;
3996 FFirePainTime := 0;
3997 FFireAttacker := 0;
3999 // Анимация возрождения:
4000 if (not gLoadGameMode) and (not Silent) then
4001 g_GFX_QueueEffect(
4002 R_GFX_TELEPORT_FAST,
4003 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4004 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4005 );
4007 FSpectator := False;
4008 FGhost := False;
4009 FPhysics := True;
4010 FSpectatePlayer := -1;
4011 FSpawned := True;
4013 if (gPlayer1 = nil) and (gSpectLatchPID1 = FUID) then
4014 gPlayer1 := self;
4015 if (gPlayer2 = nil) and (gSpectLatchPID2 = FUID) then
4016 gPlayer2 := self;
4018 if g_Game_IsNet then
4019 begin
4020 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
4021 MH_SEND_PlayerStats(FUID, NET_EVERYONE);
4022 if not Silent then
4023 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4024 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32,
4025 0, NET_GFX_TELE);
4026 end;
4027 end;
4029 procedure TPlayer.Spectate(NoMove: Boolean = False);
4030 begin
4031 if FAlive then
4032 Kill(K_EXTRAHARDKILL, FUID, HIT_SOME)
4033 else if (not NoMove) then
4034 begin
4035 GameX := gMapInfo.Width div 2;
4036 GameY := gMapInfo.Height div 2;
4037 end;
4038 FXTo := GameX;
4039 FYTo := GameY;
4041 FAlive := False;
4042 FSpectator := True;
4043 FGhost := True;
4044 FPhysics := False;
4045 FWantsInGame := False;
4046 FSpawned := False;
4047 FCorpse := -1;
4049 if FNoRespawn then
4050 begin
4051 if Self = gPlayer1 then
4052 begin
4053 gSpectLatchPID1 := FUID;
4054 gPlayer1 := nil;
4055 end
4056 else if Self = gPlayer2 then
4057 begin
4058 gSpectLatchPID2 := FUID;
4059 gPlayer2 := nil;
4060 end;
4061 end;
4063 if g_Game_IsNet then
4064 MH_SEND_PlayerStats(FUID);
4065 end;
4067 procedure TPlayer.SwitchNoClip;
4068 begin
4069 if not FAlive then
4070 Exit;
4071 FGhost := not FGhost;
4072 FPhysics := not FGhost;
4073 if FGhost then
4074 begin
4075 FXTo := FObj.X;
4076 FYTo := FObj.Y;
4077 end else
4078 begin
4079 FObj.Accel.X := 0;
4080 FObj.Accel.Y := 0;
4081 end;
4082 end;
4084 procedure TPlayer.Run(Direction: TDirection);
4085 var
4086 a, b: Integer;
4087 begin
4088 if MAX_RUNVEL > 8 then
4089 FlySmoke();
4091 // Бежим:
4092 if Direction = TDirection.D_LEFT then
4093 begin
4094 if FObj.Vel.X > -MAX_RUNVEL then
4095 FObj.Vel.X := FObj.Vel.X - (MAX_RUNVEL shr 3);
4096 end
4097 else
4098 if FObj.Vel.X < MAX_RUNVEL then
4099 FObj.Vel.X := FObj.Vel.X + (MAX_RUNVEL shr 3);
4101 // Возможно, пинаем куски:
4102 if (FObj.Vel.X <> 0) and (gGibs <> nil) then
4103 begin
4104 b := Abs(FObj.Vel.X);
4105 if b > 1 then b := b * (Random(8 div b) + 1);
4106 for a := 0 to High(gGibs) do
4107 begin
4108 if gGibs[a].alive and
4109 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
4110 FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
4111 begin
4112 // Пинаем куски
4113 if FObj.Vel.X < 0 then
4114 begin
4115 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)+120) // налево
4116 end
4117 else
4118 begin
4119 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)); // направо
4120 end;
4121 gGibs[a].positionChanged(); // this updates spatial accelerators
4122 end;
4123 end;
4124 end;
4126 SetAction(A_WALK);
4127 end;
4129 procedure TPlayer.SeeDown();
4130 begin
4131 SetAction(A_SEEDOWN);
4133 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTDOWN else FAngle := ANGLE_RIGHTDOWN;
4135 if FIncCam > -120 then DecMin(FIncCam, 5, -120);
4136 end;
4138 procedure TPlayer.SeeUp();
4139 begin
4140 SetAction(A_SEEUP);
4142 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTUP else FAngle := ANGLE_RIGHTUP;
4144 if FIncCam < 120 then IncMax(FIncCam, 5, 120);
4145 end;
4147 procedure TPlayer.SetAction(Action: Byte; Force: Boolean = False);
4148 var
4149 Prior: Byte;
4150 begin
4151 case Action of
4152 A_WALK: Prior := 3;
4153 A_DIE1: Prior := 5;
4154 A_DIE2: Prior := 5;
4155 A_ATTACK: Prior := 2;
4156 A_SEEUP: Prior := 1;
4157 A_SEEDOWN: Prior := 1;
4158 A_ATTACKUP: Prior := 2;
4159 A_ATTACKDOWN: Prior := 2;
4160 A_PAIN: Prior := 4;
4161 else Prior := 0;
4162 end;
4164 if (Prior > FActionPrior) or Force then
4165 if not ((Prior = 2) and (FCurrWeap = WEAPON_SAW)) then
4166 begin
4167 FActionPrior := Prior;
4168 FActionAnim := Action;
4169 FActionForce := Force;
4170 FActionChanged := True;
4171 end;
4173 if Action in [A_ATTACK, A_ATTACKUP, A_ATTACKDOWN] then FModel.SetFire(True);
4174 end;
4176 function TPlayer.StayOnStep(XInc, YInc: Integer): Boolean;
4177 begin
4178 Result := not g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height-1,
4179 PLAYER_RECT.Width, 1, PANEL_STEP, False)
4180 and g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height,
4181 PLAYER_RECT.Width, 1, PANEL_STEP, False);
4182 end;
4184 function TPlayer.TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
4185 begin
4186 Result := False;
4188 if g_CollideLevel(X, Y, PLAYER_RECT.Width, PLAYER_RECT.Height) then
4189 begin
4190 g_Sound_PlayExAt('SOUND_GAME_NOTELEPORT', FObj.X, FObj.Y);
4191 if g_Game_IsServer and g_Game_IsNet then
4192 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_GAME_NOTELEPORT');
4193 Exit;
4194 end;
4196 FJustTeleported := True;
4198 if not silent then
4199 begin
4200 g_Sound_PlayExAt('SOUND_GAME_TELEPORT', FObj.X, FObj.Y);
4201 g_GFX_QueueEffect(
4202 R_GFX_TELEPORT_FAST,
4203 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4204 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4205 );
4206 if g_Game_IsServer and g_Game_IsNet then
4207 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4208 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 1,
4209 NET_GFX_TELE);
4210 end;
4212 FObj.X := X-PLAYER_RECT.X;
4213 FObj.Y := Y-PLAYER_RECT.Y;
4214 FObj.oldX := FObj.X; // don't interpolate after respawn
4215 FObj.oldY := FObj.Y;
4216 if FAlive and FGhost then
4217 begin
4218 FXTo := FObj.X;
4219 FYTo := FObj.Y;
4220 end;
4222 if not g_Game_IsNet then
4223 begin
4224 if dir = 1 then
4225 begin
4226 SetDirection(TDirection.D_LEFT);
4227 FAngle := 180;
4228 end
4229 else
4230 if dir = 2 then
4231 begin
4232 SetDirection(TDirection.D_RIGHT);
4233 FAngle := 0;
4234 end
4235 else
4236 if dir = 3 then
4237 begin // обратное
4238 if FDirection = TDirection.D_RIGHT then
4239 begin
4240 SetDirection(TDirection.D_LEFT);
4241 FAngle := 180;
4242 end
4243 else
4244 begin
4245 SetDirection(TDirection.D_RIGHT);
4246 FAngle := 0;
4247 end;
4248 end;
4249 end;
4251 if not silent then
4252 begin
4253 g_GFX_QueueEffect(
4254 R_GFX_TELEPORT_FAST,
4255 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4256 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4257 );
4258 if g_Game_IsServer and g_Game_IsNet then
4259 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4260 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 0,
4261 NET_GFX_TELE);
4262 end;
4264 Result := True;
4265 end;
4267 function nonz(a: Single): Single;
4268 begin
4269 if a <> 0 then
4270 Result := a
4271 else
4272 Result := 1;
4273 end;
4275 function TPlayer.refreshCorpse(): Boolean;
4276 var
4277 i: Integer;
4278 begin
4279 Result := False;
4280 FCorpse := -1;
4281 if FAlive or FSpectator then
4282 Exit;
4283 if (gCorpses = nil) or (Length(gCorpses) = 0) then
4284 Exit;
4285 for i := 0 to High(gCorpses) do
4286 if gCorpses[i] <> nil then
4287 if gCorpses[i].FPlayerUID = FUID then
4288 begin
4289 Result := True;
4290 FCorpse := i;
4291 break;
4292 end;
4293 end;
4295 function TPlayer.getCameraObj(): TObj;
4296 begin
4297 if (not FAlive) and (not FSpectator) and
4298 (FCorpse >= 0) and (FCorpse < Length(gCorpses)) and
4299 (gCorpses[FCorpse] <> nil) and (gCorpses[FCorpse].FPlayerUID = FUID) then
4300 begin
4301 gCorpses[FCorpse].FObj.slopeUpLeft := FObj.slopeUpLeft;
4302 Result := gCorpses[FCorpse].FObj;
4303 end
4304 else
4305 begin
4306 Result := FObj;
4307 end;
4308 end;
4310 procedure TPlayer.PreUpdate();
4311 begin
4312 FSlopeOld := FObj.slopeUpLeft;
4313 FIncCamOld := FIncCam;
4314 FObj.oldX := FObj.X;
4315 FObj.oldY := FObj.Y;
4316 end;
4318 procedure TPlayer.Update();
4319 var
4320 b: Byte;
4321 i, ii, wx, wy, xd, yd, k: Integer;
4322 blockmon, headwater, dospawn: Boolean;
4323 NetServer: Boolean;
4324 AnyServer: Boolean;
4325 SetSpect: Boolean;
4326 begin
4327 NetServer := g_Game_IsNet and g_Game_IsServer;
4328 AnyServer := g_Game_IsServer;
4330 if g_Game_IsClient and (NetInterpLevel > 0) then
4331 DoLerp(NetInterpLevel + 1)
4332 else
4333 if FGhost then
4334 DoLerp(4);
4336 if NetServer then
4337 if (FClientID >= 0) and (NetClients[FClientID].Peer <> nil) then
4338 begin
4339 FPing := NetClients[FClientID].Peer^.lastRoundTripTime;
4340 if NetClients[FClientID].Peer^.packetsSent > 0 then
4341 FLoss := Round(100*NetClients[FClientID].Peer^.packetsLost/NetClients[FClientID].Peer^.packetsSent)
4342 else
4343 FLoss := 0;
4344 end else
4345 begin
4346 FPing := 0;
4347 FLoss := 0;
4348 end;
4350 if FAlive then
4351 FPunchAnim.Update;
4352 if FPunchAnim.played then
4353 FPunchAnim.Disable;
4355 if FAlive and (gFly or FJetpack) then
4356 FlySmoke();
4358 if FDirection = TDirection.D_LEFT then
4359 FAngle := 180
4360 else
4361 FAngle := 0;
4363 if FAlive and (not FGhost) then
4364 begin
4365 if FKeys[KEY_UP].Pressed then
4366 SeeUp();
4367 if FKeys[KEY_DOWN].Pressed then
4368 SeeDown();
4369 end;
4371 if (not (FKeys[KEY_UP].Pressed or FKeys[KEY_DOWN].Pressed)) and
4372 (FIncCam <> 0) then
4373 begin
4374 i := g_basic.Sign(FIncCam);
4375 FIncCam := Abs(FIncCam);
4376 DecMin(FIncCam, 5, 0);
4377 FIncCam := FIncCam*i;
4378 end;
4380 if gTime mod (GAME_TICK*2) <> 0 then
4381 begin
4382 if (FObj.Vel.X = 0) and FAlive then
4383 begin
4384 if FKeys[KEY_LEFT].Pressed then
4385 Run(TDirection.D_LEFT);
4386 if FKeys[KEY_RIGHT].Pressed then
4387 Run(TDirection.D_RIGHT);
4388 end;
4390 if FPhysics then
4391 begin
4392 g_Obj_Move(@FObj, True, True, True);
4393 positionChanged(); // this updates spatial accelerators
4394 end;
4396 Exit;
4397 end;
4399 FActionChanged := False;
4401 if FAlive then
4402 begin
4403 // Let alive player do some actions
4404 if FKeys[KEY_LEFT].Pressed then Run(TDirection.D_LEFT);
4405 if FKeys[KEY_RIGHT].Pressed then Run(TDirection.D_RIGHT);
4406 if FKeys[KEY_FIRE].Pressed and AnyServer then Fire()
4407 else
4408 begin
4409 if AnyServer then
4410 begin
4411 FlamerOff;
4412 if NetServer then MH_SEND_PlayerStats(FUID);
4413 end;
4414 end;
4415 if FKeys[KEY_OPEN].Pressed and AnyServer then Use();
4416 if FKeys[KEY_JUMP].Pressed then Jump()
4417 else
4418 begin
4419 if AnyServer and FJetpack then
4420 begin
4421 FJetpack := False;
4422 JetpackOff;
4423 if NetServer then MH_SEND_PlayerStats(FUID);
4424 end;
4425 FCanJetpack := True;
4426 end;
4427 end
4428 else // Dead
4429 begin
4430 dospawn := False;
4431 if not FGhost then
4432 for k := Low(FKeys) to KEY_CHAT-1 do
4433 begin
4434 if FKeys[k].Pressed then
4435 begin
4436 dospawn := True;
4437 break;
4438 end;
4439 end;
4440 if dospawn then
4441 begin
4442 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
4443 Respawn(False)
4444 else // Single
4445 if (FTime[T_RESPAWN] <= gTime) and
4446 gGameOn and (not FAlive) then
4447 begin
4448 if (g_Player_GetCount() > 1) then
4449 Respawn(False)
4450 else
4451 begin
4452 gExit := EXIT_RESTART;
4453 Exit;
4454 end;
4455 end;
4456 end;
4457 // Dead spectator actions
4458 if FGhost then
4459 begin
4460 if FKeys[KEY_OPEN].Pressed and AnyServer then Fire();
4461 if FKeys[KEY_FIRE].Pressed and AnyServer then
4462 begin
4463 if FSpectator then
4464 begin
4465 if (FSpectatePlayer >= High(gPlayers)) then
4466 FSpectatePlayer := -1
4467 else
4468 begin
4469 SetSpect := False;
4470 for I := FSpectatePlayer + 1 to High(gPlayers) do
4471 if gPlayers[I] <> nil then
4472 if gPlayers[I].alive then
4473 if gPlayers[I].UID <> FUID then
4474 begin
4475 FSpectatePlayer := I;
4476 SetSpect := True;
4477 break;
4478 end;
4480 if not SetSpect then FSpectatePlayer := -1;
4481 end;
4483 ReleaseKeys;
4484 end;
4485 end;
4486 end;
4487 end;
4488 // No clipping
4489 if FGhost then
4490 begin
4491 if FKeys[KEY_UP].Pressed or FKeys[KEY_JUMP].Pressed then
4492 begin
4493 FYTo := FObj.Y - 32;
4494 FSpectatePlayer := -1;
4495 end;
4496 if FKeys[KEY_DOWN].Pressed then
4497 begin
4498 FYTo := FObj.Y + 32;
4499 FSpectatePlayer := -1;
4500 end;
4501 if FKeys[KEY_LEFT].Pressed then
4502 begin
4503 FXTo := FObj.X - 32;
4504 FSpectatePlayer := -1;
4505 end;
4506 if FKeys[KEY_RIGHT].Pressed then
4507 begin
4508 FXTo := FObj.X + 32;
4509 FSpectatePlayer := -1;
4510 end;
4512 if (FXTo < -64) then
4513 FXTo := -64
4514 else if (FXTo > gMapInfo.Width + 32) then
4515 FXTo := gMapInfo.Width + 32;
4516 if (FYTo < -72) then
4517 FYTo := -72
4518 else if (FYTo > gMapInfo.Height + 32) then
4519 FYTo := gMapInfo.Height + 32;
4520 end;
4522 if FPhysics then
4523 begin
4524 g_Obj_Move(@FObj, True, True, True);
4525 positionChanged(); // this updates spatial accelerators
4526 end
4527 else
4528 begin
4529 FObj.Vel.X := 0;
4530 FObj.Vel.Y := 0;
4531 if FSpectator then
4532 if (FSpectatePlayer <= High(gPlayers)) and (FSpectatePlayer >= 0) then
4533 if gPlayers[FSpectatePlayer] <> nil then
4534 if gPlayers[FSpectatePlayer].alive then
4535 begin
4536 FXTo := gPlayers[FSpectatePlayer].GameX;
4537 FYTo := gPlayers[FSpectatePlayer].GameY;
4538 end;
4539 end;
4541 blockmon := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X, FObj.Y+PLAYER_HEADRECT.Y,
4542 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
4543 PANEL_BLOCKMON, True);
4544 headwater := HeadInLiquid(0, 0);
4546 // Сопротивление воздуха:
4547 if (not FAlive) or not (FKeys[KEY_LEFT].Pressed or FKeys[KEY_RIGHT].Pressed) then
4548 if FObj.Vel.X <> 0 then
4549 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
4551 if (FLastHit = HIT_TRAP) and (FPain > 90) then FPain := 90;
4552 DecMin(FPain, 5, 0);
4553 DecMin(FPickup, 1, 0);
4555 if FAlive and (FObj.Y > Integer(gMapInfo.Height)+128) and AnyServer then
4556 begin
4557 // Обнулить действия примочек, чтобы фон пропал
4558 FMegaRulez[MR_SUIT] := 0;
4559 FMegaRulez[MR_INVUL] := 0;
4560 FMegaRulez[MR_INVIS] := 0;
4561 Kill(K_FALLKILL, 0, HIT_FALL);
4562 end;
4564 i := 9;
4566 if FAlive then
4567 begin
4568 if FCurrWeap = WEAPON_SAW then
4569 if not (FSawSound.IsPlaying() or FSawSoundHit.IsPlaying() or
4570 FSawSoundSelect.IsPlaying()) then
4571 FSawSoundIdle.PlayAt(FObj.X, FObj.Y);
4573 if FJetpack then
4574 if (not FJetSoundFly.IsPlaying()) and (not FJetSoundOn.IsPlaying()) and
4575 (not FJetSoundOff.IsPlaying()) then
4576 begin
4577 FJetSoundFly.SetPosition(0);
4578 FJetSoundFly.PlayAt(FObj.X, FObj.Y);
4579 end;
4581 for b := WP_FIRST to WP_LAST do
4582 if FReloading[b] > 0 then
4583 if FNoReload then
4584 FReloading[b] := 0
4585 else
4586 Dec(FReloading[b]);
4588 if FShellTimer > -1 then
4589 if FShellTimer = 0 then
4590 begin
4591 if FShellType = SHELL_SHELL then
4592 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4593 GameVelX, GameVelY-2, SHELL_SHELL)
4594 else if FShellType = SHELL_DBLSHELL then
4595 begin
4596 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4597 GameVelX+1, GameVelY-2, SHELL_SHELL);
4598 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4599 GameVelX-1, GameVelY-2, SHELL_SHELL);
4600 end;
4601 FShellTimer := -1;
4602 end else Dec(FShellTimer);
4604 if (FBFGFireCounter > -1) then
4605 if FBFGFireCounter = 0 then
4606 begin
4607 if AnyServer then
4608 begin
4609 wx := FObj.X+WEAPONPOINT[FDirection].X;
4610 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
4611 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
4612 yd := wy+firediry();
4613 g_Weapon_bfgshot(wx, wy, xd, yd, FUID);
4614 if NetServer then MH_SEND_PlayerFire(FUID, WEAPON_BFG, wx, wy, xd, yd);
4615 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4616 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4617 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4618 end;
4620 FReloading[WEAPON_BFG] := WEAPON_RELOAD[WEAPON_BFG];
4621 FBFGFireCounter := -1;
4622 end else
4623 if FNoReload then
4624 FBFGFireCounter := 0
4625 else
4626 Dec(FBFGFireCounter);
4628 if (FMegaRulez[MR_SUIT] < gTime) and AnyServer then
4629 begin
4630 b := g_GetAcidHit(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width, PLAYER_RECT.Height);
4632 if (b > 0) and (gTime mod (15*GAME_TICK) = 0) then Damage(b, 0, 0, 0, HIT_ACID);
4633 end;
4635 if (headwater or blockmon) then
4636 begin
4637 Dec(FAir);
4639 if FAir < -9 then
4640 begin
4641 if AnyServer then Damage(10, 0, 0, 0, HIT_WATER);
4642 FAir := 0;
4643 end
4644 else if (FAir mod 31 = 0) and not blockmon then
4645 begin
4646 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2), FObj.Y+PLAYER_RECT.Y-4, 5+Random(6), 8, 4);
4647 if Random(2) = 0
4648 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
4649 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
4650 end;
4651 end else if FAir < AIR_DEF then
4652 FAir := AIR_DEF;
4654 if FFireTime > 0 then
4655 begin
4656 if BodyInLiquid(0, 0) then
4657 begin
4658 FFireTime := 0;
4659 FFirePainTime := 0;
4660 end
4661 else if FMegaRulez[MR_SUIT] >= gTime then
4662 begin
4663 if FMegaRulez[MR_SUIT] = gTime then
4664 FFireTime := 1;
4665 FFirePainTime := 0;
4666 end
4667 else
4668 begin
4669 OnFireFlame(1);
4670 if FFirePainTime <= 0 then
4671 begin
4672 if g_Game_IsServer then
4673 Damage(2, FFireAttacker, 0, 0, HIT_FLAME);
4674 FFirePainTime := 12 - FFireTime div 12;
4675 end;
4676 FFirePainTime := FFirePainTime - 1;
4677 FFireTime := FFireTime - 1;
4678 if ((FFireTime mod 33) = 0) and (FMegaRulez[MR_INVUL] < gTime) then
4679 FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
4680 if (FFireTime = 0) and g_Game_IsNet and g_Game_IsServer then
4681 MH_SEND_PlayerStats(FUID);
4682 end;
4683 end;
4685 if FDamageBuffer > 0 then
4686 begin
4687 if FDamageBuffer >= 9 then
4688 begin
4689 SetAction(A_PAIN);
4691 if FDamageBuffer < 30 then i := 9
4692 else if FDamageBuffer < 100 then i := 18
4693 else i := 27;
4694 end;
4696 ii := Round(FDamageBuffer*FHealth / nonz(FArmor*(3/4)+FHealth));
4697 FArmor := FArmor-(FDamageBuffer-ii);
4698 FHealth := FHealth-ii;
4699 if FArmor < 0 then
4700 begin
4701 FHealth := FHealth+FArmor;
4702 FArmor := 0;
4703 end;
4705 if AnyServer then
4706 if FHealth <= 0 then
4707 if FHealth > -30 then Kill(K_SIMPLEKILL, FLastSpawnerUID, FLastHit)
4708 else if FHealth > -50 then Kill(K_HARDKILL, FLastSpawnerUID, FLastHit)
4709 else Kill(K_EXTRAHARDKILL, FLastSpawnerUID, FLastHit);
4711 if FAlive and ((FLastHit <> HIT_FLAME) or (FFireTime <= 0)) then
4712 begin
4713 if FDamageBuffer <= 20 then FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y)
4714 else if FDamageBuffer <= 55 then FModel.PlaySound(MODELSOUND_PAIN, 2, FObj.X, FObj.Y)
4715 else if FDamageBuffer <= 120 then FModel.PlaySound(MODELSOUND_PAIN, 3, FObj.X, FObj.Y)
4716 else FModel.PlaySound(MODELSOUND_PAIN, 4, FObj.X, FObj.Y);
4717 end;
4719 FDamageBuffer := 0;
4720 end;
4722 {CollideItem();}
4723 end; // if FAlive then ...
4725 if (FActionAnim = A_PAIN) and (FModel.Animation <> A_PAIN) then
4726 begin
4727 FModel.ChangeAnimation(FActionAnim, FActionForce);
4728 FModel.AnimState.MinLength := i;
4729 end else FModel.ChangeAnimation(FActionAnim, FActionForce and (FModel.Animation <> A_STAND));
4731 if (FModel.AnimState.Played or ((not FActionChanged) and (FModel.Animation = A_WALK)))
4732 then SetAction(A_STAND, True);
4734 if not ((FModel.Animation = A_WALK) and (Abs(FObj.Vel.X) < 4) and not FModel.GetFire()) then FModel.Update;
4736 for b := Low(FKeys) to High(FKeys) do
4737 if FKeys[b].Time = 0 then FKeys[b].Pressed := False else Dec(FKeys[b].Time);
4738 end;
4741 procedure TPlayer.getMapBox (out x, y, w, h: Integer); inline;
4742 begin
4743 x := FObj.X+PLAYER_RECT.X;
4744 y := FObj.Y+PLAYER_RECT.Y;
4745 w := PLAYER_RECT.Width;
4746 h := PLAYER_RECT.Height;
4747 end;
4750 procedure TPlayer.moveBy (dx, dy: Integer); inline;
4751 begin
4752 if (dx <> 0) or (dy <> 0) then
4753 begin
4754 FObj.X += dx;
4755 FObj.Y += dy;
4756 positionChanged();
4757 end;
4758 end;
4761 function TPlayer.Collide(X, Y: Integer; Width, Height: Word): 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 X, Y,
4768 Width, Height);
4769 end;
4771 function TPlayer.Collide(Panel: TPanel): Boolean;
4772 begin
4773 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4774 FObj.Y+PLAYER_RECT.Y,
4775 PLAYER_RECT.Width,
4776 PLAYER_RECT.Height,
4777 Panel.X, Panel.Y,
4778 Panel.Width, Panel.Height);
4779 end;
4781 function TPlayer.Collide(X, Y: Integer): Boolean;
4782 begin
4783 X := X-FObj.X-PLAYER_RECT.X;
4784 Y := Y-FObj.Y-PLAYER_RECT.Y;
4785 Result := (x >= 0) and (x <= PLAYER_RECT.Width) and
4786 (y >= 0) and (y <= PLAYER_RECT.Height);
4787 end;
4789 function g_Player_ValidName(Name: string): Boolean;
4790 var
4791 a: Integer;
4792 begin
4793 Result := True;
4795 if gPlayers = nil then Exit;
4797 for a := 0 to High(gPlayers) do
4798 if gPlayers[a] <> nil then
4799 if LowerCase(Name) = LowerCase(gPlayers[a].FName) then
4800 begin
4801 Result := False;
4802 Exit;
4803 end;
4804 end;
4806 procedure TPlayer.SetDirection(Direction: TDirection);
4807 var
4808 d: TDirection;
4809 begin
4810 d := FModel.Direction;
4812 FModel.Direction := Direction;
4813 if d <> Direction then FModel.ChangeAnimation(FModel.Animation, True);
4815 FDirection := Direction;
4816 end;
4818 function TPlayer.GetKeys(): Byte;
4819 begin
4820 Result := 0;
4822 if R_KEY_RED in FRulez then Result := KEY_RED;
4823 if R_KEY_GREEN in FRulez then Result := Result or KEY_GREEN;
4824 if R_KEY_BLUE in FRulez then Result := Result or KEY_BLUE;
4826 if FTeam = TEAM_RED then Result := Result or KEY_REDTEAM;
4827 if FTeam = TEAM_BLUE then Result := Result or KEY_BLUETEAM;
4828 end;
4830 procedure TPlayer.Use();
4831 var
4832 a: Integer;
4833 begin
4834 if FTime[T_USE] > gTime then Exit;
4836 g_Triggers_PressR(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
4837 PLAYER_RECT.Height, FUID, ACTIVATE_PLAYERPRESS);
4839 for a := 0 to High(gPlayers) do
4840 if (gPlayers[a] <> nil) and (gPlayers[a] <> Self) and
4841 gPlayers[a].alive and SameTeam(FUID, gPlayers[a].FUID) and
4842 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4843 FObj.Rect.Width, FObj.Rect.Height, @gPlayers[a].FObj) then
4844 begin
4845 gPlayers[a].Touch();
4846 if g_Game_IsNet and g_Game_IsServer then
4847 MH_SEND_GameEvent(NET_EV_PLAYER_TOUCH, gPlayers[a].FUID);
4848 end;
4850 FTime[T_USE] := gTime+120;
4851 end;
4853 procedure TPlayer.NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
4854 var
4855 locObj: TObj;
4856 visible: Boolean = True;
4857 WX, WY, XD, YD: Integer;
4858 begin
4859 WX := X;
4860 WY := Y;
4861 XD := AX;
4862 YD := AY;
4864 case FCurrWeap of
4865 WEAPON_KASTET:
4866 begin
4867 visible := False;
4868 DoPunch();
4869 if R_BERSERK in FRulez then
4870 begin
4871 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
4872 locobj.X := FObj.X+FObj.Rect.X;
4873 locobj.Y := FObj.Y+FObj.Rect.Y;
4874 locobj.rect.X := 0;
4875 locobj.rect.Y := 0;
4876 locobj.rect.Width := 39;
4877 locobj.rect.Height := 52;
4878 locobj.Vel.X := (xd-wx) div 2;
4879 locobj.Vel.Y := (yd-wy) div 2;
4880 locobj.Accel.X := xd-wx;
4881 locobj.Accel.y := yd-wy;
4883 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
4884 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
4885 else
4886 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
4888 if gFlash = 1 then
4889 if FPain < 50 then
4890 FPain := min(FPain + 25, 50);
4891 end else
4892 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
4893 end;
4895 WEAPON_SAW:
4896 begin
4897 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4898 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
4899 begin
4900 FSawSoundSelect.Stop();
4901 FSawSound.Stop();
4902 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
4903 end
4904 else if not FSawSoundHit.IsPlaying() then
4905 begin
4906 FSawSoundSelect.Stop();
4907 FSawSound.PlayAt(FObj.X, FObj.Y);
4908 end;
4909 end;
4911 WEAPON_PISTOL:
4912 begin
4913 g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', GameX, Gamey);
4914 FFireAngle := FAngle;
4915 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4916 GameVelX, GameVelY-2, SHELL_BULLET);
4917 end;
4919 WEAPON_SHOTGUN1:
4920 begin
4921 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4922 FFireAngle := FAngle;
4923 FShellTimer := 10;
4924 FShellType := SHELL_SHELL;
4925 end;
4927 WEAPON_SHOTGUN2:
4928 begin
4929 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN2', Gamex, Gamey);
4930 FFireAngle := FAngle;
4931 FShellTimer := 13;
4932 FShellType := SHELL_DBLSHELL;
4933 end;
4935 WEAPON_CHAINGUN:
4936 begin
4937 g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', Gamex, Gamey);
4938 FFireAngle := FAngle;
4939 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4940 GameVelX, GameVelY-2, SHELL_BULLET);
4941 end;
4943 WEAPON_ROCKETLAUNCHER:
4944 begin
4945 g_Weapon_Rocket(wx, wy, xd, yd, FUID, WID);
4946 FFireAngle := FAngle;
4947 end;
4949 WEAPON_PLASMA:
4950 begin
4951 g_Weapon_Plasma(wx, wy, xd, yd, FUID, WID);
4952 FFireAngle := FAngle;
4953 end;
4955 WEAPON_BFG:
4956 begin
4957 g_Weapon_BFGShot(wx, wy, xd, yd, FUID, WID);
4958 FFireAngle := FAngle;
4959 end;
4961 WEAPON_SUPERPULEMET:
4962 begin
4963 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4964 FFireAngle := FAngle;
4965 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4966 GameVelX, GameVelY-2, SHELL_SHELL);
4967 end;
4969 WEAPON_FLAMETHROWER:
4970 begin
4971 g_Weapon_flame(wx, wy, xd, yd, FUID, WID);
4972 FlamerOn;
4973 FFireAngle := FAngle;
4974 end;
4975 end;
4977 if not visible then Exit;
4979 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4980 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4981 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4982 end;
4984 procedure TPlayer.DoLerp(Level: Integer = 2);
4985 begin
4986 if FObj.X <> FXTo then FObj.X := Lerp(FObj.X, FXTo, Level);
4987 if FObj.Y <> FYTo then FObj.Y := Lerp(FObj.Y, FYTo, Level);
4988 end;
4990 procedure TPlayer.SetLerp(XTo, YTo: Integer);
4991 var
4992 AX, AY: Integer;
4993 begin
4994 FXTo := XTo;
4995 FYTo := YTo;
4996 if FJustTeleported or (NetInterpLevel < 1) then
4997 begin
4998 FObj.X := XTo;
4999 FObj.Y := YTo;
5000 if FJustTeleported then
5001 begin
5002 FObj.oldX := FObj.X;
5003 FObj.oldY := FObj.Y;
5004 end;
5005 end
5006 else
5007 begin
5008 AX := Abs(FXTo - FObj.X);
5009 AY := Abs(FYTo - FObj.Y);
5010 if (AX > 32) or (AX <= NetInterpLevel) then
5011 FObj.X := FXTo;
5012 if (AY > 32) or (AY <= NetInterpLevel) then
5013 FObj.Y := FYTo;
5014 end;
5015 end;
5017 function TPlayer.FullInLift(XInc, YInc: Integer): Integer;
5018 begin
5019 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5020 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5021 PANEL_LIFTUP, False) then Result := -1
5022 else
5023 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5024 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5025 PANEL_LIFTDOWN, False) then Result := 1
5026 else Result := 0;
5027 end;
5029 function TPlayer.GetFlag(Flag: Byte): Boolean;
5030 var
5031 s, ts: String;
5032 evtype, a: Byte;
5033 begin
5034 Result := False;
5036 if Flag = FLAG_NONE then
5037 Exit;
5039 if not g_Game_IsServer then Exit;
5041 // Принес чужой флаг на свою базу:
5042 if (Flag = FTeam) and
5043 (gFlags[Flag].State = FLAG_STATE_NORMAL) and
5044 (FFlag <> FLAG_NONE) then
5045 begin
5046 if FFlag = FLAG_RED then
5047 s := _lc[I_PLAYER_FLAG_RED]
5048 else
5049 s := _lc[I_PLAYER_FLAG_BLUE];
5051 evtype := FLAG_STATE_SCORED;
5053 ts := Format('%.4d', [gFlags[FFlag].CaptureTime]);
5054 Insert('.', ts, Length(ts) + 1 - 3);
5055 g_Console_Add(Format(_lc[I_PLAYER_FLAG_CAPTURE], [FName, s, ts]), True);
5057 g_Map_ResetFlag(FFlag);
5058 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_CAPTURE], [AnsiUpperCase(s)]), 144);
5060 if ((Self = gPlayer1) or (Self = gPlayer2)
5061 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5062 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5063 a := 0
5064 else
5065 a := 1;
5067 if not sound_cap_flag[a].IsPlaying() then
5068 sound_cap_flag[a].Play();
5070 gTeamStat[FTeam].Score += 1;
5072 Result := True;
5073 if g_Game_IsNet then
5074 begin
5075 MH_SEND_FlagEvent(evtype, FFlag, FUID, False);
5076 MH_SEND_GameStats;
5077 end;
5079 gFlags[FFlag].CaptureTime := 0;
5080 SetFlag(FLAG_NONE);
5081 Exit;
5082 end;
5084 // Подобрал свой флаг - вернул его на базу:
5085 if (Flag = FTeam) and
5086 (gFlags[Flag].State = FLAG_STATE_DROPPED) then
5087 begin
5088 if Flag = FLAG_RED then
5089 s := _lc[I_PLAYER_FLAG_RED]
5090 else
5091 s := _lc[I_PLAYER_FLAG_BLUE];
5093 evtype := FLAG_STATE_RETURNED;
5094 gFlags[Flag].CaptureTime := 0;
5096 g_Console_Add(Format(_lc[I_PLAYER_FLAG_RETURN], [FName, s]), True);
5098 g_Map_ResetFlag(Flag);
5099 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
5101 if ((Self = gPlayer1) or (Self = gPlayer2)
5102 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5103 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5104 a := 0
5105 else
5106 a := 1;
5108 if not sound_ret_flag[a].IsPlaying() then
5109 sound_ret_flag[a].Play();
5111 Result := True;
5112 if g_Game_IsNet then
5113 begin
5114 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5115 MH_SEND_GameStats;
5116 end;
5117 Exit;
5118 end;
5120 // Подобрал чужой флаг:
5121 if (Flag <> FTeam) and (FTime[T_FLAGCAP] <= gTime) then
5122 begin
5123 SetFlag(Flag);
5125 if Flag = FLAG_RED then
5126 s := _lc[I_PLAYER_FLAG_RED]
5127 else
5128 s := _lc[I_PLAYER_FLAG_BLUE];
5130 evtype := FLAG_STATE_CAPTURED;
5132 g_Console_Add(Format(_lc[I_PLAYER_FLAG_GET], [FName, s]), True);
5134 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_GET], [AnsiUpperCase(s)]), 144);
5136 gFlags[Flag].State := FLAG_STATE_CAPTURED;
5138 if ((Self = gPlayer1) or (Self = gPlayer2)
5139 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5140 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5141 a := 0
5142 else
5143 a := 1;
5145 if not sound_get_flag[a].IsPlaying() then
5146 sound_get_flag[a].Play();
5148 Result := True;
5149 if g_Game_IsNet then
5150 begin
5151 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5152 MH_SEND_GameStats;
5153 end;
5154 end;
5155 end;
5157 procedure TPlayer.SetFlag(Flag: Byte);
5158 begin
5159 FFlag := Flag;
5160 if FModel <> nil then
5161 FModel.SetFlag(FFlag);
5162 end;
5164 function TPlayer.TryDropFlag(): Boolean;
5165 begin
5166 if LongBool(gGameSettings.Options and GAME_OPTION_ALLOWDROPFLAG) then
5167 Result := DropFlag(False, LongBool(gGameSettings.Options and GAME_OPTION_THROWFLAG))
5168 else
5169 Result := False;
5170 end;
5172 function TPlayer.DropFlag(Silent: Boolean = True; DoThrow: Boolean = False): Boolean;
5173 var
5174 s: String;
5175 a: Byte;
5176 xv, yv: Integer;
5177 begin
5178 Result := False;
5179 if (not g_Game_IsServer) or (FFlag = FLAG_NONE) then
5180 Exit;
5181 FTime[T_FLAGCAP] := gTime + 2000;
5182 with gFlags[FFlag] do
5183 begin
5184 Obj.X := FObj.X;
5185 Obj.Y := FObj.Y;
5186 Direction := FDirection;
5187 State := FLAG_STATE_DROPPED;
5188 Count := FLAG_TIME;
5189 if DoThrow then
5190 begin
5191 xv := FObj.Vel.X + IfThen(Direction = TDirection.D_RIGHT, 10, -10);
5192 yv := FObj.Vel.Y - 2;
5193 end
5194 else
5195 begin
5196 xv := (FObj.Vel.X div 2);
5197 yv := (FObj.Vel.Y div 2) - 2;
5198 end;
5199 g_Obj_Push(@Obj, xv, yv);
5201 positionChanged(); // this updates spatial accelerators
5203 if FFlag = FLAG_RED then
5204 s := _lc[I_PLAYER_FLAG_RED]
5205 else
5206 s := _lc[I_PLAYER_FLAG_BLUE];
5208 g_Console_Add(Format(_lc[I_PLAYER_FLAG_DROP], [FName, s]), True);
5209 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_DROP], [AnsiUpperCase(s)]), 144);
5211 if ((Self = gPlayer1) or (Self = gPlayer2)
5212 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5213 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5214 a := 0
5215 else
5216 a := 1;
5218 if (not Silent) and (not sound_lost_flag[a].IsPlaying()) then
5219 sound_lost_flag[a].Play();
5221 if g_Game_IsNet then
5222 MH_SEND_FlagEvent(FLAG_STATE_DROPPED, Flag, FUID, False);
5223 end;
5224 SetFlag(FLAG_NONE);
5225 Result := True;
5226 end;
5228 procedure TPlayer.GetSecret();
5229 begin
5230 if (self = gPlayer1) or (self = gPlayer2) then
5231 begin
5232 g_Console_Add(Format(_lc[I_PLAYER_SECRET], [FName]), True);
5233 g_Sound_PlayEx('SOUND_GAME_SECRET');
5234 end;
5235 Inc(FSecrets);
5236 end;
5238 procedure TPlayer.PressKey(Key: Byte; Time: Word = 1);
5239 begin
5240 Assert(Key <= High(FKeys));
5242 FKeys[Key].Pressed := True;
5243 FKeys[Key].Time := Time;
5244 end;
5246 function TPlayer.IsKeyPressed(K: Byte): Boolean;
5247 begin
5248 Result := FKeys[K].Pressed;
5249 end;
5251 procedure TPlayer.ReleaseKeys();
5252 var
5253 a: Integer;
5254 begin
5255 for a := Low(FKeys) to High(FKeys) do
5256 begin
5257 FKeys[a].Pressed := False;
5258 FKeys[a].Time := 0;
5259 end;
5260 end;
5262 procedure TPlayer.OnDamage(Angle: SmallInt);
5263 begin
5264 end;
5266 function TPlayer.firediry(): Integer;
5267 begin
5268 if FKeys[KEY_UP].Pressed then Result := -42
5269 else if FKeys[KEY_DOWN].Pressed then Result := 19
5270 else Result := 0;
5271 end;
5273 procedure TPlayer.RememberState();
5274 var
5275 i: Integer;
5276 SavedState: TPlayerSavedState;
5277 begin
5278 SavedState.Health := FHealth;
5279 SavedState.Armor := FArmor;
5280 SavedState.Air := FAir;
5281 SavedState.JetFuel := FJetFuel;
5282 SavedState.CurrWeap := FCurrWeap;
5283 SavedState.NextWeap := FNextWeap;
5284 SavedState.NextWeapDelay := FNextWeapDelay;
5285 for i := Low(FWeapon) to High(FWeapon) do
5286 SavedState.Weapon[i] := FWeapon[i];
5287 for i := Low(FAmmo) to High(FAmmo) do
5288 SavedState.Ammo[i] := FAmmo[i];
5289 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5290 SavedState.MaxAmmo[i] := FMaxAmmo[i];
5291 SavedState.Rulez := FRulez - [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5293 FSavedStateNum := -1;
5294 for i := Low(SavedStates) to High(SavedStates) do
5295 if not SavedStates[i].Used then
5296 begin
5297 FSavedStateNum := i;
5298 break;
5299 end;
5300 if FSavedStateNum < 0 then
5301 begin
5302 SetLength(SavedStates, Length(SavedStates) + 1);
5303 FSavedStateNum := High(SavedStates);
5304 end;
5306 SavedState.Used := True;
5307 SavedStates[FSavedStateNum] := SavedState;
5308 end;
5310 procedure TPlayer.RecallState();
5311 var
5312 i: Integer;
5313 SavedState: TPlayerSavedState;
5314 begin
5315 if(FSavedStateNum < 0) or (FSavedStateNum > High(SavedStates)) then
5316 Exit;
5318 SavedState := SavedStates[FSavedStateNum];
5319 SavedStates[FSavedStateNum].Used := False;
5320 FSavedStateNum := -1;
5322 FHealth := SavedState.Health;
5323 FArmor := SavedState.Armor;
5324 FAir := SavedState.Air;
5325 FJetFuel := SavedState.JetFuel;
5326 FCurrWeap := SavedState.CurrWeap;
5327 FNextWeap := SavedState.NextWeap;
5328 FNextWeapDelay := SavedState.NextWeapDelay;
5329 for i := Low(FWeapon) to High(FWeapon) do
5330 FWeapon[i] := SavedState.Weapon[i];
5331 for i := Low(FAmmo) to High(FAmmo) do
5332 FAmmo[i] := SavedState.Ammo[i];
5333 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5334 FMaxAmmo[i] := SavedState.MaxAmmo[i];
5335 FRulez := SavedState.Rulez;
5337 if gGameSettings.GameType = GT_SERVER then
5338 MH_SEND_PlayerStats(FUID);
5339 end;
5341 procedure TPlayer.SaveState (st: TStream);
5342 var
5343 i: Integer;
5344 b: Byte;
5345 begin
5346 // Сигнатура игрока
5347 utils.writeSign(st, 'PLYR');
5348 utils.writeInt(st, Byte(PLR_SAVE_VERSION)); // version
5349 // Бот или человек
5350 utils.writeBool(st, FIamBot);
5351 // UID игрока
5352 utils.writeInt(st, Word(FUID));
5353 // Имя игрока
5354 utils.writeStr(st, FName);
5355 // Команда
5356 utils.writeInt(st, Byte(FTeam));
5357 // Жив ли
5358 utils.writeBool(st, FAlive);
5359 // Израсходовал ли все жизни
5360 utils.writeBool(st, FNoRespawn);
5361 // Направление
5362 if FDirection = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
5363 utils.writeInt(st, Byte(b));
5364 // Здоровье
5365 utils.writeInt(st, LongInt(FHealth));
5366 // Коэффициент инвалидности
5367 utils.writeInt(st, LongInt(FHandicap));
5368 // Жизни
5369 utils.writeInt(st, Byte(FLives));
5370 // Броня
5371 utils.writeInt(st, LongInt(FArmor));
5372 // Запас воздуха
5373 utils.writeInt(st, LongInt(FAir));
5374 // Запас горючего
5375 utils.writeInt(st, LongInt(FJetFuel));
5376 // Боль
5377 utils.writeInt(st, LongInt(FPain));
5378 // Убил
5379 utils.writeInt(st, LongInt(FKills));
5380 // Убил монстров
5381 utils.writeInt(st, LongInt(FMonsterKills));
5382 // Фрагов
5383 utils.writeInt(st, LongInt(FFrags));
5384 // Фрагов подряд
5385 utils.writeInt(st, Byte(FFragCombo));
5386 // Время последнего фрага
5387 utils.writeInt(st, LongWord(FLastFrag));
5388 // Смертей
5389 utils.writeInt(st, LongInt(FDeath));
5390 // Какой флаг несет
5391 utils.writeInt(st, Byte(FFlag));
5392 // Нашел секретов
5393 utils.writeInt(st, LongInt(FSecrets));
5394 // Текущее оружие
5395 utils.writeInt(st, Byte(FCurrWeap));
5396 // Желаемое оружие
5397 utils.writeInt(st, Word(FNextWeap));
5398 // ...и пауза
5399 utils.writeInt(st, Byte(FNextWeapDelay));
5400 // Время зарядки BFG
5401 utils.writeInt(st, SmallInt(FBFGFireCounter));
5402 // Буфер урона
5403 utils.writeInt(st, LongInt(FDamageBuffer));
5404 // Последний ударивший
5405 utils.writeInt(st, Word(FLastSpawnerUID));
5406 // Тип последнего полученного урона
5407 utils.writeInt(st, Byte(FLastHit));
5408 // Объект игрока
5409 Obj_SaveState(st, @FObj);
5410 // Текущее количество патронов
5411 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FAmmo[i]));
5412 // Максимальное количество патронов
5413 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FMaxAmmo[i]));
5414 // Наличие оружия
5415 for i := WP_FIRST to WP_LAST do utils.writeBool(st, FWeapon[i]);
5416 // Время перезарядки оружия
5417 for i := WP_FIRST to WP_LAST do utils.writeInt(st, Word(FReloading[i]));
5418 // Наличие рюкзака
5419 utils.writeBool(st, (R_ITEM_BACKPACK in FRulez));
5420 // Наличие красного ключа
5421 utils.writeBool(st, (R_KEY_RED in FRulez));
5422 // Наличие зеленого ключа
5423 utils.writeBool(st, (R_KEY_GREEN in FRulez));
5424 // Наличие синего ключа
5425 utils.writeBool(st, (R_KEY_BLUE in FRulez));
5426 // Наличие берсерка
5427 utils.writeBool(st, (R_BERSERK in FRulez));
5428 // Время действия специальных предметов
5429 for i := MR_SUIT to MR_MAX do utils.writeInt(st, LongWord(FMegaRulez[i]));
5430 // Время до повторного респауна, смены оружия, исользования, захвата флага
5431 for i := T_RESPAWN to T_FLAGCAP do utils.writeInt(st, LongWord(FTime[i]));
5432 // Название модели
5433 utils.writeStr(st, FModel.GetName());
5434 // Цвет модели
5435 utils.writeInt(st, Byte(FColor.R));
5436 utils.writeInt(st, Byte(FColor.G));
5437 utils.writeInt(st, Byte(FColor.B));
5438 end;
5441 procedure TPlayer.LoadState (st: TStream);
5442 var
5443 i: Integer;
5444 str: String;
5445 b: Byte;
5446 begin
5447 assert(st <> nil);
5449 // Сигнатура игрока
5450 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
5451 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
5452 // Бот или человек:
5453 FIamBot := utils.readBool(st);
5454 // UID игрока
5455 FUID := utils.readWord(st);
5456 // Имя игрока
5457 str := utils.readStr(st);
5458 if (self <> gPlayer1) and (self <> gPlayer2) then FName := str;
5459 // Команда
5460 FTeam := utils.readByte(st);
5461 // Жив ли
5462 FAlive := utils.readBool(st);
5463 // Израсходовал ли все жизни
5464 FNoRespawn := utils.readBool(st);
5465 // Направление
5466 b := utils.readByte(st);
5467 if b = 1 then FDirection := TDirection.D_LEFT else FDirection := TDirection.D_RIGHT; // b = 2
5468 // Здоровье
5469 FHealth := utils.readLongInt(st);
5470 // Коэффициент инвалидности
5471 FHandicap := utils.readLongInt(st);
5472 // Жизни
5473 FLives := utils.readByte(st);
5474 // Броня
5475 FArmor := utils.readLongInt(st);
5476 // Запас воздуха
5477 FAir := utils.readLongInt(st);
5478 // Запас горючего
5479 FJetFuel := utils.readLongInt(st);
5480 // Боль
5481 FPain := utils.readLongInt(st);
5482 // Убил
5483 FKills := utils.readLongInt(st);
5484 // Убил монстров
5485 FMonsterKills := utils.readLongInt(st);
5486 // Фрагов
5487 FFrags := utils.readLongInt(st);
5488 // Фрагов подряд
5489 FFragCombo := utils.readByte(st);
5490 // Время последнего фрага
5491 FLastFrag := utils.readLongWord(st);
5492 // Смертей
5493 FDeath := utils.readLongInt(st);
5494 // Какой флаг несет
5495 FFlag := utils.readByte(st);
5496 // Нашел секретов
5497 FSecrets := utils.readLongInt(st);
5498 // Текущее оружие
5499 FCurrWeap := utils.readByte(st);
5500 // Желаемое оружие
5501 FNextWeap := utils.readWord(st);
5502 // ...и пауза
5503 FNextWeapDelay := utils.readByte(st);
5504 // Время зарядки BFG
5505 FBFGFireCounter := utils.readSmallInt(st);
5506 // Буфер урона
5507 FDamageBuffer := utils.readLongInt(st);
5508 // Последний ударивший
5509 FLastSpawnerUID := utils.readWord(st);
5510 // Тип последнего полученного урона
5511 FLastHit := utils.readByte(st);
5512 // Объект игрока
5513 Obj_LoadState(@FObj, st);
5514 // Текущее количество патронов
5515 for i := A_BULLETS to A_HIGH do FAmmo[i] := utils.readWord(st);
5516 // Максимальное количество патронов
5517 for i := A_BULLETS to A_HIGH do FMaxAmmo[i] := utils.readWord(st);
5518 // Наличие оружия
5519 for i := WP_FIRST to WP_LAST do FWeapon[i] := utils.readBool(st);
5520 // Время перезарядки оружия
5521 for i := WP_FIRST to WP_LAST do FReloading[i] := utils.readWord(st);
5522 // Наличие рюкзака
5523 if utils.readBool(st) then Include(FRulez, R_ITEM_BACKPACK);
5524 // Наличие красного ключа
5525 if utils.readBool(st) then Include(FRulez, R_KEY_RED);
5526 // Наличие зеленого ключа
5527 if utils.readBool(st) then Include(FRulez, R_KEY_GREEN);
5528 // Наличие синего ключа
5529 if utils.readBool(st) then Include(FRulez, R_KEY_BLUE);
5530 // Наличие берсерка
5531 if utils.readBool(st) then Include(FRulez, R_BERSERK);
5532 // Время действия специальных предметов
5533 for i := MR_SUIT to MR_MAX do FMegaRulez[i] := utils.readLongWord(st);
5534 // Время до повторного респауна, смены оружия, исользования, захвата флага
5535 for i := T_RESPAWN to T_FLAGCAP do FTime[i] := utils.readLongWord(st);
5536 // Название модели
5537 str := utils.readStr(st);
5538 // Цвет модели
5539 FColor.R := utils.readByte(st);
5540 FColor.G := utils.readByte(st);
5541 FColor.B := utils.readByte(st);
5542 if (self = gPlayer1) then
5543 begin
5544 str := gPlayer1Settings.Model;
5545 FColor := gPlayer1Settings.Color;
5546 end
5547 else if (self = gPlayer2) then
5548 begin
5549 str := gPlayer2Settings.Model;
5550 FColor := gPlayer2Settings.Color;
5551 end;
5552 // Обновляем модель игрока
5553 SetModel(str);
5554 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
5555 FModel.Color := TEAMCOLOR[FTeam]
5556 else
5557 FModel.Color := FColor;
5558 end;
5561 procedure TPlayer.AllRulez(Health: Boolean);
5562 var
5563 a: Integer;
5564 begin
5565 if Health then
5566 begin
5567 FHealth := PLAYER_HP_LIMIT;
5568 FArmor := PLAYER_AP_LIMIT;
5569 Exit;
5570 end;
5572 for a := WP_FIRST to WP_LAST do FWeapon[a] := True;
5573 for a := A_BULLETS to A_HIGH do FAmmo[a] := 30000;
5574 FRulez := FRulez+[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5575 end;
5577 procedure TPlayer.RestoreHealthArmor();
5578 begin
5579 FHealth := PLAYER_HP_LIMIT;
5580 FArmor := PLAYER_AP_LIMIT;
5581 end;
5583 procedure TPlayer.FragCombo();
5584 var
5585 Param: Integer;
5586 begin
5587 if (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) or g_Game_IsClient then
5588 Exit;
5589 if gTime - FLastFrag < FRAG_COMBO_TIME then
5590 begin
5591 if FFragCombo < 5 then
5592 Inc(FFragCombo);
5593 Param := FUID or (FFragCombo shl 16);
5594 if (FComboEvnt >= Low(gDelayedEvents)) and
5595 (FComboEvnt <= High(gDelayedEvents)) and
5596 gDelayedEvents[FComboEvnt].Pending and
5597 (gDelayedEvents[FComboEvnt].DEType = DE_KILLCOMBO) and
5598 (gDelayedEvents[FComboEvnt].DENum and $FFFF = FUID) then
5599 begin
5600 gDelayedEvents[FComboEvnt].Time := gTime + 500;
5601 gDelayedEvents[FComboEvnt].DENum := Param;
5602 end
5603 else
5604 FComboEvnt := g_Game_DelayEvent(DE_KILLCOMBO, 500, Param);
5605 end
5606 else
5607 FFragCombo := 1;
5609 FLastFrag := gTime;
5610 end;
5612 procedure TPlayer.GiveItem(ItemType: Byte);
5613 begin
5614 case ItemType of
5615 ITEM_SUIT:
5616 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
5617 begin
5618 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
5619 end;
5621 ITEM_OXYGEN:
5622 if FAir < AIR_MAX then
5623 begin
5624 FAir := AIR_MAX;
5625 end;
5627 ITEM_MEDKIT_BLACK:
5628 begin
5629 if not (R_BERSERK in FRulez) then
5630 begin
5631 Include(FRulez, R_BERSERK);
5632 if FBFGFireCounter < 1 then
5633 begin
5634 FCurrWeap := WEAPON_KASTET;
5635 resetWeaponQueue();
5636 FModel.SetWeapon(WEAPON_KASTET);
5637 end;
5638 if gFlash <> 0 then
5639 Inc(FPain, 100);
5640 FBerserk := gTime+30000;
5641 end;
5642 if FHealth < PLAYER_HP_SOFT then
5643 begin
5644 FHealth := PLAYER_HP_SOFT;
5645 FBerserk := gTime+30000;
5646 end;
5647 end;
5649 ITEM_INVUL:
5650 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
5651 begin
5652 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
5653 FSpawnInvul := 0;
5654 end;
5656 ITEM_INVIS:
5657 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
5658 begin
5659 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
5660 end;
5662 ITEM_JETPACK:
5663 if FJetFuel < JET_MAX then
5664 begin
5665 FJetFuel := JET_MAX;
5666 end;
5668 ITEM_MEDKIT_SMALL: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
5669 ITEM_MEDKIT_LARGE: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
5671 ITEM_ARMOR_GREEN: if FArmor < PLAYER_AP_SOFT then FArmor := PLAYER_AP_SOFT;
5672 ITEM_ARMOR_BLUE: if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5674 ITEM_SPHERE_BLUE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
5675 ITEM_SPHERE_WHITE:
5676 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) then
5677 begin
5678 if FHealth < PLAYER_HP_LIMIT then FHealth := PLAYER_HP_LIMIT;
5679 if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5680 end;
5682 ITEM_WEAPON_SAW: FWeapon[WEAPON_SAW] := True;
5683 ITEM_WEAPON_SHOTGUN1: FWeapon[WEAPON_SHOTGUN1] := True;
5684 ITEM_WEAPON_SHOTGUN2: FWeapon[WEAPON_SHOTGUN2] := True;
5685 ITEM_WEAPON_CHAINGUN: FWeapon[WEAPON_CHAINGUN] := True;
5686 ITEM_WEAPON_ROCKETLAUNCHER: FWeapon[WEAPON_ROCKETLAUNCHER] := True;
5687 ITEM_WEAPON_PLASMA: FWeapon[WEAPON_PLASMA] := True;
5688 ITEM_WEAPON_BFG: FWeapon[WEAPON_BFG] := True;
5689 ITEM_WEAPON_SUPERPULEMET: FWeapon[WEAPON_SUPERPULEMET] := True;
5690 ITEM_WEAPON_FLAMETHROWER: FWeapon[WEAPON_FLAMETHROWER] := True;
5692 ITEM_AMMO_BULLETS: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5693 ITEM_AMMO_BULLETS_BOX: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
5694 ITEM_AMMO_SHELLS: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5695 ITEM_AMMO_SHELLS_BOX: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
5696 ITEM_AMMO_ROCKET: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5697 ITEM_AMMO_ROCKET_BOX: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
5698 ITEM_AMMO_CELL: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5699 ITEM_AMMO_CELL_BIG: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
5700 ITEM_AMMO_FUELCAN: if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
5702 ITEM_AMMO_BACKPACK:
5703 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
5704 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
5705 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
5706 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
5707 (FMaxAmmo[A_FUEL] < AmmoLimits[1, A_FUEL]) then
5708 begin
5709 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
5710 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
5711 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
5712 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
5713 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
5715 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5716 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5717 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5718 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5720 FRulez := FRulez + [R_ITEM_BACKPACK];
5721 end;
5723 ITEM_KEY_RED: if not (R_KEY_RED in FRulez) then Include(FRulez, R_KEY_RED);
5724 ITEM_KEY_GREEN: if not (R_KEY_GREEN in FRulez) then Include(FRulez, R_KEY_GREEN);
5725 ITEM_KEY_BLUE: if not (R_KEY_BLUE in FRulez) then Include(FRulez, R_KEY_BLUE);
5727 ITEM_BOTTLE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
5728 ITEM_HELMET: if FArmor < PLAYER_AP_LIMIT then IncMax(FArmor, 5, PLAYER_AP_LIMIT);
5730 else
5731 Exit;
5732 end;
5733 if g_Game_IsNet and g_Game_IsServer then
5734 MH_SEND_PlayerStats(FUID);
5735 end;
5737 procedure TPlayer.FlySmoke(Times: DWORD = 1);
5738 var i: DWORD;
5739 begin
5740 if (Random(5) = 1) and (Times = 1) then
5741 Exit;
5743 if BodyInLiquid(0, 0) then
5744 begin
5745 g_GFX_Bubbles(Obj.X+Obj.Rect.X+(Obj.Rect.Width div 2)+Random(3)-1,
5746 Obj.Y+Obj.Rect.Height+8, 1, 8, 4);
5747 if Random(2) = 0
5748 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
5749 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
5750 Exit;
5751 end;
5753 for i := 1 to Times do
5754 begin
5755 g_GFX_QueueEffect(
5756 R_GFX_SMOKE_TRANS,
5757 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_SMOKE_WIDTH div 2),
5758 Obj.Y+Obj.Rect.Height-4+Random(8+Times*2)
5759 );
5760 end;
5761 end;
5763 procedure TPlayer.OnFireFlame(Times: DWORD = 1);
5764 var i: DWORD;
5765 begin
5766 if (Random(10) = 1) and (Times = 1) then
5767 Exit;
5769 for i := 1 to Times do
5770 begin
5771 g_GFX_QueueEffect(
5772 R_GFX_FLAME,
5773 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_FLAME_WIDTH div 2),
5774 Obj.Y+8+Random(8+Times*2)
5775 );
5776 end;
5777 end;
5779 procedure TPlayer.PauseSounds(Enable: Boolean);
5780 begin
5781 FSawSound.Pause(Enable);
5782 FSawSoundIdle.Pause(Enable);
5783 FSawSoundHit.Pause(Enable);
5784 FSawSoundSelect.Pause(Enable);
5785 FFlameSoundOn.Pause(Enable);
5786 FFlameSoundOff.Pause(Enable);
5787 FFlameSoundWork.Pause(Enable);
5788 FJetSoundFly.Pause(Enable);
5789 FJetSoundOn.Pause(Enable);
5790 FJetSoundOff.Pause(Enable);
5791 end;
5793 { T C o r p s e : }
5795 constructor TCorpse.Create(X, Y: Integer; ModelName: String; aMess: Boolean);
5796 begin
5797 g_Obj_Init(@FObj);
5798 FObj.X := X;
5799 FObj.Y := Y;
5800 FObj.Rect := PLAYER_CORPSERECT;
5801 FMess := aMess;
5802 FModel := g_PlayerModel_Get(ModelName);
5804 if FMess then
5805 begin
5806 FState := CORPSE_STATE_MESS;
5807 FModel.ChangeAnimation(A_DIE2);
5808 end
5809 else
5810 begin
5811 FState := CORPSE_STATE_NORMAL;
5812 FModel.ChangeAnimation(A_DIE1);
5813 end;
5814 end;
5816 destructor TCorpse.Destroy();
5817 begin
5818 FModel.Free;
5819 inherited;
5820 end;
5822 function TCorpse.ObjPtr (): PObj; inline; begin result := @FObj; end;
5824 procedure TCorpse.positionChanged (); inline; begin end;
5826 procedure TCorpse.moveBy (dx, dy: Integer); inline;
5827 begin
5828 if (dx <> 0) or (dy <> 0) then
5829 begin
5830 FObj.X += dx;
5831 FObj.Y += dy;
5832 positionChanged();
5833 end;
5834 end;
5837 procedure TCorpse.getMapBox (out x, y, w, h: Integer); inline;
5838 begin
5839 x := FObj.X+PLAYER_CORPSERECT.X;
5840 y := FObj.Y+PLAYER_CORPSERECT.Y;
5841 w := PLAYER_CORPSERECT.Width;
5842 h := PLAYER_CORPSERECT.Height;
5843 end;
5846 procedure TCorpse.Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
5847 var Blood: TModelBlood;
5848 begin
5849 if FState = CORPSE_STATE_REMOVEME then
5850 Exit;
5852 FDamage := FDamage + Value;
5854 if FDamage > 150 then
5855 begin
5856 if FModel <> nil then
5857 begin
5858 FState := CORPSE_STATE_REMOVEME;
5860 g_Player_CreateGibs(
5861 FObj.X + FObj.Rect.X + (FObj.Rect.Width div 2),
5862 FObj.Y + FObj.Rect.Y + (FObj.Rect.Height div 2),
5863 FModel.id,
5864 FModel.Color
5865 );
5867 // Звук мяса от трупа:
5868 FModel.PlaySound(MODELSOUND_DIE, 5, FObj.X, FObj.Y);
5870 // Зловещий смех:
5871 if (gBodyKillEvent <> -1) and gDelayedEvents[gBodyKillEvent].Pending then
5872 gDelayedEvents[gBodyKillEvent].Pending := False;
5873 gBodyKillEvent := g_Game_DelayEvent(DE_BODYKILL, 1050, SpawnerUID);
5875 FModel.Free;
5876 FModel := nil;
5877 end
5878 end
5879 else
5880 begin
5881 Blood := FModel.GetBlood();
5882 FObj.Vel.X := FObj.Vel.X + vx;
5883 FObj.Vel.Y := FObj.Vel.Y + vy;
5884 g_GFX_Blood(FObj.X+PLAYER_CORPSERECT.X+(PLAYER_CORPSERECT.Width div 2),
5885 FObj.Y+PLAYER_CORPSERECT.Y+(PLAYER_CORPSERECT.Height div 2),
5886 Value, vx, vy, 16, (PLAYER_CORPSERECT.Height*2) div 3,
5887 Blood.R, Blood.G, Blood.B, Blood.Kind);
5888 end;
5889 end;
5891 procedure TCorpse.Update();
5892 var
5893 st: Word;
5894 begin
5895 if FState = CORPSE_STATE_REMOVEME then
5896 Exit;
5898 FObj.oldX := FObj.X;
5899 FObj.oldY := FObj.Y;
5901 if gTime mod (GAME_TICK*2) <> 0 then
5902 begin
5903 g_Obj_Move(@FObj, True, True, True);
5904 positionChanged(); // this updates spatial accelerators
5905 Exit;
5906 end;
5908 // Сопротивление воздуха для трупа:
5909 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
5911 st := g_Obj_Move(@FObj, True, True, True);
5912 positionChanged(); // this updates spatial accelerators
5914 if WordBool(st and MOVE_FALLOUT) then
5915 begin
5916 FState := CORPSE_STATE_REMOVEME;
5917 Exit;
5918 end;
5920 if FModel <> nil then
5921 FModel.Update;
5922 end;
5925 procedure TCorpse.SaveState (st: TStream);
5926 var anim: Boolean;
5927 begin
5928 assert(st <> nil);
5930 // Сигнатура трупа
5931 utils.writeSign(st, 'CORP');
5932 utils.writeInt(st, Byte(0));
5933 // Состояние
5934 utils.writeInt(st, Byte(FState));
5935 // Накопленный урон
5936 utils.writeInt(st, Byte(FDamage));
5937 // Цвет
5938 utils.writeInt(st, Byte(FModel.Color.R));
5939 utils.writeInt(st, Byte(FModel.Color.G));
5940 utils.writeInt(st, Byte(FModel.Color.B));
5941 // Объект трупа
5942 Obj_SaveState(st, @FObj);
5943 utils.writeInt(st, Word(FPlayerUID));
5944 // animation
5945 anim := (FModel <> nil);
5946 utils.writeBool(st, anim);
5947 if anim then FModel.AnimState.SaveState(st);
5948 // animation for mask (same as animation, compat with older saves)
5949 anim := (FModel <> nil);
5950 utils.writeBool(st, anim);
5951 if anim then FModel.AnimState.SaveState(st);
5952 end;
5955 procedure TCorpse.LoadState (st: TStream);
5956 var anim: Boolean; r, g, b: Byte; stub: TAnimationState;
5957 begin
5958 assert(st <> nil);
5960 // Сигнатура трупа
5961 if not utils.checkSign(st, 'CORP') then raise XStreamError.Create('invalid corpse signature');
5962 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid corpse version');
5963 // Состояние
5964 FState := utils.readByte(st);
5965 // Накопленный урон
5966 FDamage := utils.readByte(st);
5967 // Цвет
5968 r := utils.readByte(st);
5969 g := utils.readByte(st);
5970 b := utils.readByte(st);
5971 FModel.SetColor(r, g, b);
5972 // Объект трупа
5973 Obj_LoadState(@FObj, st);
5974 FPlayerUID := utils.readWord(st);
5975 // animation
5976 stub := TAnimationState.Create(False, 0, 0);
5977 anim := utils.readBool(st);
5978 if anim then
5979 begin
5980 stub.LoadState(st);
5981 FModel.AnimState.CurrentFrame := Min(stub.CurrentFrame, FModel.AnimState.Length);
5982 end
5983 else
5984 begin
5985 FModel.Free;
5986 FModel := nil
5987 end;
5988 // animation for mask (same as animation, compat with older saves)
5989 anim := utils.readBool(st);
5990 if anim then stub.LoadState(st);
5991 stub.Free;
5992 end;
5994 { T B o t : }
5996 constructor TBot.Create();
5997 var
5998 a: Integer;
5999 begin
6000 inherited Create();
6002 FPhysics := True;
6003 FSpectator := False;
6004 FGhost := False;
6006 FIamBot := True;
6008 Inc(gNumBots);
6010 for a := WP_FIRST to WP_LAST do
6011 begin
6012 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
6013 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
6014 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
6015 end;
6016 end;
6018 destructor TBot.Destroy();
6019 begin
6020 Dec(gNumBots);
6021 inherited Destroy();
6022 end;
6024 procedure TBot.Respawn(Silent: Boolean; Force: Boolean = False);
6025 begin
6026 inherited Respawn(Silent, Force);
6028 FAIFlags := nil;
6029 FSelectedWeapon := FCurrWeap;
6030 resetWeaponQueue();
6031 FTargetUID := 0;
6032 end;
6034 procedure TBot.UpdateCombat();
6035 type
6036 TTarget = record
6037 UID: Word;
6038 X, Y: Integer;
6039 Rect: TRectWH;
6040 cX, cY: Integer;
6041 Dist: Word;
6042 Line: Boolean;
6043 Visible: Boolean;
6044 IsPlayer: Boolean;
6045 end;
6047 TTargetRecord = array of TTarget;
6049 function Compare(a, b: TTarget): Integer;
6050 begin
6051 if a.Line and not b.Line then // A на линии огня
6052 Result := -1
6053 else
6054 if not a.Line and b.Line then // B на линии огня
6055 Result := 1
6056 else // И A, и B на линии или не на линии огня
6057 if (a.Line and b.Line) or ((not a.Line) and (not b.Line)) then
6058 begin
6059 if a.Dist > b.Dist then // B ближе
6060 Result := 1
6061 else // A ближе или равноудаленно с B
6062 Result := -1;
6063 end
6064 else // Странно -> A
6065 Result := -1;
6066 end;
6068 var
6069 a, x1, y1, x2, y2: Integer;
6070 targets: TTargetRecord;
6071 ammo: Word;
6072 Target, BestTarget: TTarget;
6073 firew, fireh: Integer;
6074 angle: SmallInt;
6075 mon: TMonster;
6076 pla, tpla: TPlayer;
6077 vsPlayer, vsMonster, ok: Boolean;
6080 function monsUpdate (mon: TMonster): Boolean;
6081 begin
6082 result := false; // don't stop
6083 if mon.alive and (mon.MonsterType <> MONSTER_BARREL) then
6084 begin
6085 if not TargetOnScreen(mon.Obj.X+mon.Obj.Rect.X, mon.Obj.Y+mon.Obj.Rect.Y) then exit;
6087 x2 := mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2);
6088 y2 := mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2);
6090 // Если монстр на экране и не прикрыт стеной
6091 if g_TraceVector(x1, y1, x2, y2) then
6092 begin
6093 // Добавляем к списку возможных целей
6094 SetLength(targets, Length(targets)+1);
6095 with targets[High(targets)] do
6096 begin
6097 UID := mon.UID;
6098 X := mon.Obj.X;
6099 Y := mon.Obj.Y;
6100 cX := x2;
6101 cY := y2;
6102 Rect := mon.Obj.Rect;
6103 Dist := g_PatchLength(x1, y1, x2, y2);
6104 Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6105 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6106 Visible := True;
6107 IsPlayer := False;
6108 end;
6109 end;
6110 end;
6111 end;
6113 begin
6114 vsPlayer := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER);
6115 vsMonster := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER);
6117 // Если текущее оружие не то, что нужно, то меняем:
6118 if FCurrWeap <> FSelectedWeapon then
6119 NextWeapon();
6121 // Если нужно стрелять и нужное оружие, то нажать "Стрелять":
6122 if (GetAIFlag('NEEDFIRE') <> '') and (FCurrWeap = FSelectedWeapon) then
6123 begin
6124 RemoveAIFlag('NEEDFIRE');
6126 case FCurrWeap of
6127 WEAPON_PLASMA, WEAPON_SUPERPULEMET, WEAPON_CHAINGUN: PressKey(KEY_FIRE, 20);
6128 WEAPON_SAW, WEAPON_KASTET, WEAPON_FLAMETHROWER: PressKey(KEY_FIRE, 40);
6129 else PressKey(KEY_FIRE);
6130 end;
6131 end;
6133 // Координаты ствола:
6134 x1 := FObj.X + WEAPONPOINT[FDirection].X;
6135 y1 := FObj.Y + WEAPONPOINT[FDirection].Y;
6137 Target.UID := FTargetUID;
6139 ok := False;
6140 if Target.UID <> 0 then
6141 begin // Цель есть - настраиваем
6142 if (g_GetUIDType(Target.UID) = UID_PLAYER) and
6143 vsPlayer then
6144 begin // Игрок
6145 tpla := g_Player_Get(Target.UID);
6146 if tpla <> nil then
6147 with tpla do
6148 begin
6149 if (@FObj) <> nil then
6150 begin
6151 Target.X := FObj.X;
6152 Target.Y := FObj.Y;
6153 end;
6154 end;
6156 Target.cX := Target.X + PLAYER_RECT_CX;
6157 Target.cY := Target.Y + PLAYER_RECT_CY;
6158 Target.Rect := PLAYER_RECT;
6159 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6160 Target.Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6161 (y1-4 > Target.Y+PLAYER_RECT.Y);
6162 Target.IsPlayer := True;
6163 ok := True;
6164 end
6165 else
6166 if (g_GetUIDType(Target.UID) = UID_MONSTER) and
6167 vsMonster then
6168 begin // Монстр
6169 mon := g_Monsters_ByUID(Target.UID);
6170 if mon <> nil then
6171 begin
6172 Target.X := mon.Obj.X;
6173 Target.Y := mon.Obj.Y;
6175 Target.cX := Target.X + mon.Obj.Rect.X + (mon.Obj.Rect.Width div 2);
6176 Target.cY := Target.Y + mon.Obj.Rect.Y + (mon.Obj.Rect.Height div 2);
6177 Target.Rect := mon.Obj.Rect;
6178 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6179 Target.Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6180 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6181 Target.IsPlayer := False;
6182 ok := True;
6183 end;
6184 end;
6185 end;
6187 if not ok then
6188 begin // Цели нет - обнуляем
6189 Target.X := 0;
6190 Target.Y := 0;
6191 Target.cX := 0;
6192 Target.cY := 0;
6193 Target.Visible := False;
6194 Target.Line := False;
6195 Target.IsPlayer := False;
6196 end;
6198 targets := nil;
6200 // Если цель не видима или не на линии огня, то ищем все возможные цели:
6201 if (not Target.Line) or (not Target.Visible) then
6202 begin
6203 // Игроки:
6204 if vsPlayer then
6205 for a := 0 to High(gPlayers) do
6206 if (gPlayers[a] <> nil) and (gPlayers[a].alive) and
6207 (gPlayers[a].FUID <> FUID) and
6208 (not SameTeam(FUID, gPlayers[a].FUID)) and
6209 (not gPlayers[a].NoTarget) and
6210 (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
6211 begin
6212 if not TargetOnScreen(gPlayers[a].FObj.X + PLAYER_RECT.X,
6213 gPlayers[a].FObj.Y + PLAYER_RECT.Y) then
6214 Continue;
6216 x2 := gPlayers[a].FObj.X + PLAYER_RECT_CX;
6217 y2 := gPlayers[a].FObj.Y + PLAYER_RECT_CY;
6219 // Если игрок на экране и не прикрыт стеной:
6220 if g_TraceVector(x1, y1, x2, y2) then
6221 begin
6222 // Добавляем к списку возможных целей:
6223 SetLength(targets, Length(targets)+1);
6224 with targets[High(targets)] do
6225 begin
6226 UID := gPlayers[a].FUID;
6227 X := gPlayers[a].FObj.X;
6228 Y := gPlayers[a].FObj.Y;
6229 cX := x2;
6230 cY := y2;
6231 Rect := PLAYER_RECT;
6232 Dist := g_PatchLength(x1, y1, x2, y2);
6233 Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6234 (y1-4 > Target.Y+PLAYER_RECT.Y);
6235 Visible := True;
6236 IsPlayer := True;
6237 end;
6238 end;
6239 end;
6241 // Монстры:
6242 if vsMonster then g_Mons_ForEach(monsUpdate);
6243 end;
6245 // Если есть возможные цели:
6246 // (Выбираем лучшую, меняем оружие и бежим к ней/от нее)
6247 if targets <> nil then
6248 begin
6249 // Выбираем наилучшую цель:
6250 BestTarget := targets[0];
6251 if Length(targets) > 1 then
6252 for a := 1 to High(targets) do
6253 if Compare(BestTarget, targets[a]) = 1 then
6254 BestTarget := targets[a];
6256 // Если лучшая цель "виднее" текущей, то текущая := лучшая:
6257 if ((not Target.Visible) and BestTarget.Visible and (Target.UID <> BestTarget.UID)) or
6258 ((not Target.Line) and BestTarget.Line and BestTarget.Visible) then
6259 begin
6260 Target := BestTarget;
6262 if (Healthy() = 3) or ((Healthy() = 2)) then
6263 begin // Если здоровы - догоняем
6264 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6265 SetAIFlag('GORIGHT', '1');
6266 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6267 SetAIFlag('GOLEFT', '1');
6268 end
6269 else
6270 begin // Если побиты - убегаем
6271 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6272 SetAIFlag('GORIGHT', '1');
6273 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6274 SetAIFlag('GOLEFT', '1');
6275 end;
6277 // Выбираем оружие на основе расстояния и приоритетов:
6278 SelectWeapon(Abs(x1-Target.cX));
6279 end;
6280 end;
6282 // Если есть цель:
6283 // (Догоняем/убегаем, стреляем по направлению к цели)
6284 // (Если цель далеко, то хватит следить за ней)
6285 if Target.UID <> 0 then
6286 begin
6287 if not TargetOnScreen(Target.X + Target.Rect.X,
6288 Target.Y + Target.Rect.Y) then
6289 begin // Цель сбежала с "экрана"
6290 if (Healthy() = 3) or ((Healthy() = 2)) then
6291 begin // Если здоровы - догоняем
6292 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6293 SetAIFlag('GORIGHT', '1');
6294 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6295 SetAIFlag('GOLEFT', '1');
6296 end
6297 else
6298 begin // Если побиты - забываем о цели и убегаем
6299 Target.UID := 0;
6300 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6301 SetAIFlag('GORIGHT', '1');
6302 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6303 SetAIFlag('GOLEFT', '1');
6304 end;
6305 end
6306 else
6307 begin // Цель пока на "экране"
6308 // Если цель не загорожена стеной, то отмечаем, когда ее видели:
6309 if g_TraceVector(x1, y1, Target.cX, Target.cY) then
6310 FLastVisible := gTime;
6311 // Если разница высот не велика, то догоняем:
6312 if (Abs(FObj.Y-Target.Y) <= 128) then
6313 begin
6314 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6315 SetAIFlag('GORIGHT', '1');
6316 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6317 SetAIFlag('GOLEFT', '1');
6318 end;
6319 end;
6321 // Выбираем угол вверх:
6322 if FDirection = TDirection.D_LEFT then
6323 angle := ANGLE_LEFTUP
6324 else
6325 angle := ANGLE_RIGHTUP;
6327 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6328 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6330 // Если при угле вверх можно попасть в приблизительное положение цели:
6331 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6332 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128), //96
6333 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6334 Target.Rect.Width, Target.Rect.Height) and
6335 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6336 begin // то нужно стрелять вверх
6337 SetAIFlag('NEEDFIRE', '1');
6338 SetAIFlag('NEEDSEEUP', '1');
6339 end;
6341 // Выбираем угол вниз:
6342 if FDirection = TDirection.D_LEFT then
6343 angle := ANGLE_LEFTDOWN
6344 else
6345 angle := ANGLE_RIGHTDOWN;
6347 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6348 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6350 // Если при угле вниз можно попасть в приблизительное положение цели:
6351 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6352 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6353 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6354 Target.Rect.Width, Target.Rect.Height) and
6355 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6356 begin // то нужно стрелять вниз
6357 SetAIFlag('NEEDFIRE', '1');
6358 SetAIFlag('NEEDSEEDOWN', '1');
6359 end;
6361 // Если цель видно и она на такой же высоте:
6362 if Target.Visible and
6363 (y1+4 < Target.Y+Target.Rect.Y+Target.Rect.Height) and
6364 (y1-4 > Target.Y+Target.Rect.Y) then
6365 begin
6366 // Если идем в сторону цели, то надо стрелять:
6367 if ((FDirection = TDirection.D_LEFT) and (Target.X < FObj.X)) or
6368 ((FDirection = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6369 begin // то нужно стрелять вперед
6370 SetAIFlag('NEEDFIRE', '1');
6371 SetAIFlag('NEEDSEEDOWN', '');
6372 SetAIFlag('NEEDSEEUP', '');
6373 end;
6374 // Если цель в пределах "экрана" и сложность позволяет прыжки сближения:
6375 if Abs(FObj.X-Target.X) < Trunc(gPlayerScreenSize.X*0.75) then
6376 if GetRnd(FDifficult.CloseJump) then
6377 begin // то если повезет - прыгаем (особенно, если близко)
6378 if Abs(FObj.X-Target.X) < 128 then
6379 a := 4
6380 else
6381 a := 30;
6382 if Random(a) = 0 then
6383 SetAIFlag('NEEDJUMP', '1');
6384 end;
6385 end;
6387 // Если цель все еще есть:
6388 if Target.UID <> 0 then
6389 if gTime-FLastVisible > 2000 then // Если видели давно
6390 Target.UID := 0 // то забыть цель
6391 else // Если видели недавно
6392 begin // но цель убили
6393 if Target.IsPlayer then
6394 begin // Цель - игрок
6395 pla := g_Player_Get(Target.UID);
6396 if (pla = nil) or (not pla.alive) or pla.NoTarget or
6397 (pla.FMegaRulez[MR_INVIS] >= gTime) then
6398 Target.UID := 0; // то забыть цель
6399 end
6400 else
6401 begin // Цель - монстр
6402 mon := g_Monsters_ByUID(Target.UID);
6403 if (mon = nil) or (not mon.alive) then
6404 Target.UID := 0; // то забыть цель
6405 end;
6406 end;
6407 end; // if Target.UID <> 0
6409 FTargetUID := Target.UID;
6411 // Если возможных целей нет:
6412 // (Атака чего-нибудь слева или справа)
6413 if targets = nil then
6414 if GetAIFlag('ATTACKLEFT') <> '' then
6415 begin // Если нужно атаковать налево
6416 RemoveAIFlag('ATTACKLEFT');
6418 SetAIFlag('NEEDJUMP', '1');
6420 if RunDirection() = TDirection.D_RIGHT then
6421 begin // Идем не в ту сторону
6422 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6423 begin // Если здоровы, то, возможно, стреляем бежим влево и стреляем
6424 SetAIFlag('NEEDFIRE', '1');
6425 SetAIFlag('GOLEFT', '1');
6426 end;
6427 end
6428 else
6429 begin // Идем в нужную сторону
6430 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6431 SetAIFlag('NEEDFIRE', '1');
6432 if Healthy() <= 1 then // Побиты - убегаем
6433 SetAIFlag('GORIGHT', '1');
6434 end;
6435 end
6436 else
6437 if GetAIFlag('ATTACKRIGHT') <> '' then
6438 begin // Если нужно атаковать направо
6439 RemoveAIFlag('ATTACKRIGHT');
6441 SetAIFlag('NEEDJUMP', '1');
6443 if RunDirection() = TDirection.D_LEFT then
6444 begin // Идем не в ту сторону
6445 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6446 begin // Если здоровы, то, возможно, бежим вправо и стреляем
6447 SetAIFlag('NEEDFIRE', '1');
6448 SetAIFlag('GORIGHT', '1');
6449 end;
6450 end
6451 else
6452 begin
6453 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6454 SetAIFlag('NEEDFIRE', '1');
6455 if Healthy() <= 1 then // Побиты - убегаем
6456 SetAIFlag('GOLEFT', '1');
6457 end;
6458 end;
6460 //HACK! (does it belongs there?)
6461 RealizeCurrentWeapon();
6463 // Если есть возможные цели:
6464 // (Стреляем по направлению к целям)
6465 if (targets <> nil) and (GetAIFlag('NEEDFIRE') <> '') then
6466 for a := 0 to High(targets) do
6467 begin
6468 // Если можем стрелять по диагонали:
6469 if GetRnd(FDifficult.DiagFire) then
6470 begin
6471 // Ищем цель сверху и стреляем, если есть:
6472 if FDirection = TDirection.D_LEFT then
6473 angle := ANGLE_LEFTUP
6474 else
6475 angle := ANGLE_RIGHTUP;
6477 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6478 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6480 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6481 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6482 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6483 targets[a].Rect.Width, targets[a].Rect.Height) and
6484 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6485 begin
6486 SetAIFlag('NEEDFIRE', '1');
6487 SetAIFlag('NEEDSEEUP', '1');
6488 end;
6490 // Ищем цель снизу и стреляем, если есть:
6491 if FDirection = TDirection.D_LEFT then
6492 angle := ANGLE_LEFTDOWN
6493 else
6494 angle := ANGLE_RIGHTDOWN;
6496 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6497 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6499 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6500 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6501 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6502 targets[a].Rect.Width, targets[a].Rect.Height) and
6503 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6504 begin
6505 SetAIFlag('NEEDFIRE', '1');
6506 SetAIFlag('NEEDSEEDOWN', '1');
6507 end;
6508 end;
6510 // Если цель "перед носом", то стреляем:
6511 if targets[a].Line and targets[a].Visible and
6512 (((FDirection = TDirection.D_LEFT) and (targets[a].X < FObj.X)) or
6513 ((FDirection = TDirection.D_RIGHT) and (targets[a].X > FObj.X))) then
6514 begin
6515 SetAIFlag('NEEDFIRE', '1');
6516 Break;
6517 end;
6518 end;
6520 // Если летит пуля, то, возможно, подпрыгиваем:
6521 if g_Weapon_Danger(FUID, FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y,
6522 PLAYER_RECT.Width, PLAYER_RECT.Height,
6523 40+GetInterval(FDifficult.Cover, 40)) then
6524 SetAIFlag('NEEDJUMP', '1');
6526 // Если кончились паторны, то нужно сменить оружие:
6527 ammo := GetAmmoByWeapon(FCurrWeap);
6528 if ((FCurrWeap = WEAPON_SHOTGUN2) and (ammo < 2)) or
6529 ((FCurrWeap = WEAPON_BFG) and (ammo < 40)) or
6530 (ammo = 0) then
6531 SetAIFlag('SELECTWEAPON', '1');
6533 // Если нужно сменить оружие, то выбираем нужное:
6534 if GetAIFlag('SELECTWEAPON') = '1' then
6535 begin
6536 SelectWeapon(-1);
6537 RemoveAIFlag('SELECTWEAPON');
6538 end;
6539 end;
6541 procedure TBot.Update();
6542 var
6543 EnableAI: Boolean;
6544 begin
6545 if not FAlive then
6546 begin // Respawn
6547 ReleaseKeys();
6548 PressKey(KEY_UP);
6549 end
6550 else
6551 begin
6552 EnableAI := True;
6554 // Проверяем, отключён ли AI ботов
6555 if (g_debug_BotAIOff = 1) and (Team = TEAM_RED) then
6556 EnableAI := False;
6557 if (g_debug_BotAIOff = 2) and (Team = TEAM_BLUE) then
6558 EnableAI := False;
6559 if g_debug_BotAIOff = 3 then
6560 EnableAI := False;
6562 if EnableAI then
6563 begin
6564 UpdateMove();
6565 UpdateCombat();
6566 end
6567 else
6568 begin
6569 RealizeCurrentWeapon();
6570 end;
6571 end;
6573 inherited Update();
6574 end;
6576 procedure TBot.ReleaseKey(Key: Byte);
6577 begin
6578 with FKeys[Key] do
6579 begin
6580 Pressed := False;
6581 Time := 0;
6582 end;
6583 end;
6585 function TBot.KeyPressed(Key: Word): Boolean;
6586 begin
6587 Result := FKeys[Key].Pressed;
6588 end;
6590 function TBot.GetAIFlag(aName: String20): String20;
6591 var
6592 a: Integer;
6593 begin
6594 Result := '';
6596 aName := LowerCase(aName);
6598 if FAIFlags <> nil then
6599 for a := 0 to High(FAIFlags) do
6600 if LowerCase(FAIFlags[a].Name) = aName then
6601 begin
6602 Result := FAIFlags[a].Value;
6603 Break;
6604 end;
6605 end;
6607 procedure TBot.RemoveAIFlag(aName: String20);
6608 var
6609 a, b: Integer;
6610 begin
6611 if FAIFlags = nil then Exit;
6613 aName := LowerCase(aName);
6615 for a := 0 to High(FAIFlags) do
6616 if LowerCase(FAIFlags[a].Name) = aName then
6617 begin
6618 if a <> High(FAIFlags) then
6619 for b := a to High(FAIFlags)-1 do
6620 FAIFlags[b] := FAIFlags[b+1];
6622 SetLength(FAIFlags, Length(FAIFlags)-1);
6623 Break;
6624 end;
6625 end;
6627 procedure TBot.SetAIFlag(aName, fValue: String20);
6628 var
6629 a: Integer;
6630 ok: Boolean;
6631 begin
6632 a := 0;
6633 ok := False;
6635 aName := LowerCase(aName);
6637 if FAIFlags <> nil then
6638 for a := 0 to High(FAIFlags) do
6639 if LowerCase(FAIFlags[a].Name) = aName then
6640 begin
6641 ok := True;
6642 Break;
6643 end;
6645 if ok then FAIFlags[a].Value := fValue
6646 else
6647 begin
6648 SetLength(FAIFlags, Length(FAIFlags)+1);
6649 with FAIFlags[High(FAIFlags)] do
6650 begin
6651 Name := aName;
6652 Value := fValue;
6653 end;
6654 end;
6655 end;
6657 procedure TBot.UpdateMove;
6659 procedure GoLeft(Time: Word = 1);
6660 begin
6661 ReleaseKey(KEY_LEFT);
6662 ReleaseKey(KEY_RIGHT);
6663 PressKey(KEY_LEFT, Time);
6664 SetDirection(TDirection.D_LEFT);
6665 end;
6667 procedure GoRight(Time: Word = 1);
6668 begin
6669 ReleaseKey(KEY_LEFT);
6670 ReleaseKey(KEY_RIGHT);
6671 PressKey(KEY_RIGHT, Time);
6672 SetDirection(TDirection.D_RIGHT);
6673 end;
6675 function Rnd(a: Word): Boolean;
6676 begin
6677 Result := Random(a) = 0;
6678 end;
6680 procedure Turn(Time: Word = 1200);
6681 begin
6682 if RunDirection() = TDirection.D_LEFT then GoRight(Time) else GoLeft(Time);
6683 end;
6685 procedure Stop();
6686 begin
6687 ReleaseKey(KEY_LEFT);
6688 ReleaseKey(KEY_RIGHT);
6689 end;
6691 function CanRunLeft(): Boolean;
6692 begin
6693 Result := not CollideLevel(-1, 0);
6694 end;
6696 function CanRunRight(): Boolean;
6697 begin
6698 Result := not CollideLevel(1, 0);
6699 end;
6701 function CanRun(): Boolean;
6702 begin
6703 if RunDirection() = TDirection.D_LEFT then Result := CanRunLeft() else Result := CanRunRight();
6704 end;
6706 procedure Jump(Time: Word = 30);
6707 begin
6708 PressKey(KEY_JUMP, Time);
6709 end;
6711 function NearHole(): Boolean;
6712 var
6713 x, sx: Integer;
6714 begin
6715 { TODO 5 : Лестницы }
6716 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6717 for x := 1 to PLAYER_RECT.Width do
6718 if (not StayOnStep(x*sx, 0)) and
6719 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6720 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6721 begin
6722 Result := True;
6723 Exit;
6724 end;
6726 Result := False;
6727 end;
6729 function BorderHole(): Boolean;
6730 var
6731 x, sx, xx: Integer;
6732 begin
6733 { TODO 5 : Лестницы }
6734 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6735 for x := 1 to PLAYER_RECT.Width do
6736 if (not StayOnStep(x*sx, 0)) and
6737 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6738 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6739 begin
6740 for xx := x to x+32 do
6741 if CollideLevel(xx*sx, PLAYER_RECT.Height) then
6742 begin
6743 Result := True;
6744 Exit;
6745 end;
6746 end;
6748 Result := False;
6749 end;
6751 function NearDeepHole(): Boolean;
6752 var
6753 x, sx, y: Integer;
6754 begin
6755 Result := False;
6757 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6758 y := 3;
6760 for x := 1 to PLAYER_RECT.Width do
6761 if (not StayOnStep(x*sx, 0)) and
6762 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6763 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6764 begin
6765 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6766 begin
6767 if CollideLevel(x*sx, PLAYER_RECT.Height*y) then Exit;
6768 y := y+1;
6769 end;
6771 Result := True;
6772 end else Result := False;
6773 end;
6775 function OverDeepHole(): Boolean;
6776 var
6777 y: Integer;
6778 begin
6779 Result := False;
6781 y := 1;
6782 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6783 begin
6784 if CollideLevel(0, PLAYER_RECT.Height*y) then Exit;
6785 y := y+1;
6786 end;
6788 Result := True;
6789 end;
6791 function OnGround(): Boolean;
6792 begin
6793 Result := StayOnStep(0, 0) or CollideLevel(0, 1);
6794 end;
6796 function OnLadder(): Boolean;
6797 begin
6798 Result := FullInStep(0, 0);
6799 end;
6801 function BelowLadder(): Boolean;
6802 begin
6803 Result := (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) and
6804 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6805 (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) and
6806 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6807 end;
6809 function BelowLiftUp(): Boolean;
6810 begin
6811 Result := ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) = -1) and
6812 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6813 ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) = -1) and
6814 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6815 end;
6817 function OnTopLift(): Boolean;
6818 begin
6819 Result := (FullInLift(0, 0) = -1) and (FullInLift(0, -32) = 0);
6820 end;
6822 function CanJumpOver(): Boolean;
6823 var
6824 sx, y: Integer;
6825 begin
6826 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6828 Result := False;
6830 if not CollideLevel(sx, 0) then Exit;
6832 for y := 1 to BOT_MAXJUMP do
6833 if CollideLevel(0, -y) then Exit else
6834 if not CollideLevel(sx, -y) then
6835 begin
6836 Result := True;
6837 Exit;
6838 end;
6839 end;
6841 function CanJumpUp(Dist: ShortInt): Boolean;
6842 var
6843 y, yy: Integer;
6844 c: Boolean;
6845 begin
6846 Result := False;
6848 if CollideLevel(Dist, 0) then Exit;
6850 c := False;
6851 for y := 0 to BOT_MAXJUMP do
6852 if CollideLevel(Dist, -y) then
6853 begin
6854 c := True;
6855 Break;
6856 end;
6858 if not c then Exit;
6860 c := False;
6861 for yy := y+1 to BOT_MAXJUMP do
6862 if not CollideLevel(Dist, -yy) then
6863 begin
6864 c := True;
6865 Break;
6866 end;
6868 if not c then Exit;
6870 c := False;
6871 for y := 0 to BOT_MAXJUMP do
6872 if CollideLevel(0, -y) then
6873 begin
6874 c := True;
6875 Break;
6876 end;
6878 if c then Exit;
6880 if y < yy then Exit;
6882 Result := True;
6883 end;
6885 function IsSafeTrigger(): Boolean;
6886 var
6887 a: Integer;
6888 begin
6889 Result := True;
6890 if gTriggers = nil then
6891 Exit;
6892 for a := 0 to High(gTriggers) do
6893 if Collide(gTriggers[a].X,
6894 gTriggers[a].Y,
6895 gTriggers[a].Width,
6896 gTriggers[a].Height) and
6897 (gTriggers[a].TriggerType in [TRIGGER_EXIT, TRIGGER_CLOSEDOOR,
6898 TRIGGER_CLOSETRAP, TRIGGER_TRAP,
6899 TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF,
6900 TRIGGER_ONOFF, TRIGGER_SPAWNMONSTER,
6901 TRIGGER_DAMAGE, TRIGGER_SHOT]) then
6902 Result := False;
6903 end;
6905 begin
6906 // Возможно, нажимаем кнопку:
6907 if Rnd(16) and IsSafeTrigger() then
6908 PressKey(KEY_OPEN);
6910 // Если под лифтом или ступеньками, то, возможно, прыгаем:
6911 if OnLadder() or ((BelowLadder() or BelowLiftUp()) and Rnd(8)) then
6912 begin
6913 ReleaseKey(KEY_LEFT);
6914 ReleaseKey(KEY_RIGHT);
6915 Jump();
6916 end;
6918 // Идем влево, если надо было:
6919 if GetAIFlag('GOLEFT') <> '' then
6920 begin
6921 RemoveAIFlag('GOLEFT');
6922 if CanRunLeft() then
6923 GoLeft(360);
6924 end;
6926 // Идем вправо, если надо было:
6927 if GetAIFlag('GORIGHT') <> '' then
6928 begin
6929 RemoveAIFlag('GORIGHT');
6930 if CanRunRight() then
6931 GoRight(360);
6932 end;
6934 // Если вылетели за карту, то пробуем вернуться:
6935 if FObj.X < -32 then
6936 GoRight(360)
6937 else
6938 if FObj.X+32 > gMapInfo.Width then
6939 GoLeft(360);
6941 // Прыгаем, если надо было:
6942 if GetAIFlag('NEEDJUMP') <> '' then
6943 begin
6944 Jump(0);
6945 RemoveAIFlag('NEEDJUMP');
6946 end;
6948 // Смотрим вверх, если надо было:
6949 if GetAIFlag('NEEDSEEUP') <> '' then
6950 begin
6951 ReleaseKey(KEY_UP);
6952 ReleaseKey(KEY_DOWN);
6953 PressKey(KEY_UP, 20);
6954 RemoveAIFlag('NEEDSEEUP');
6955 end;
6957 // Смотрим вниз, если надо было:
6958 if GetAIFlag('NEEDSEEDOWN') <> '' then
6959 begin
6960 ReleaseKey(KEY_UP);
6961 ReleaseKey(KEY_DOWN);
6962 PressKey(KEY_DOWN, 20);
6963 RemoveAIFlag('NEEDSEEDOWN');
6964 end;
6966 // Если нужно было в дыру и мы не на земле, то покорно летим:
6967 if GetAIFlag('GOINHOLE') <> '' then
6968 if not OnGround() then
6969 begin
6970 ReleaseKey(KEY_LEFT);
6971 ReleaseKey(KEY_RIGHT);
6972 RemoveAIFlag('GOINHOLE');
6973 SetAIFlag('FALLINHOLE', '1');
6974 end;
6976 // Если падали и достигли земли, то хватит падать:
6977 if GetAIFlag('FALLINHOLE') <> '' then
6978 if OnGround() then
6979 RemoveAIFlag('FALLINHOLE');
6981 // Если летели прямо и сейчас не на лестнице или на вершине лифта, то отходим в сторону:
6982 if not (KeyPressed(KEY_LEFT) or KeyPressed(KEY_RIGHT)) then
6983 if GetAIFlag('FALLINHOLE') = '' then
6984 if (not OnLadder()) or (FObj.Vel.Y >= 0) or (OnTopLift()) then
6985 if Rnd(2) then
6986 GoLeft(360)
6987 else
6988 GoRight(360);
6990 // Если на земле и можно подпрыгнуть, то, возможно, прыгаем:
6991 if OnGround() and
6992 CanJumpUp(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*32) and
6993 Rnd(8) then
6994 Jump();
6996 // Если на земле и возле дыры (глубина > 2 ростов игрока):
6997 if OnGround() and NearHole() then
6998 if NearDeepHole() then // Если это бездна
6999 case Random(6) of
7000 0..3: Turn(); // Бежим обратно
7001 4: Jump(); // Прыгаем
7002 5: begin // Прыгаем обратно
7003 Turn();
7004 Jump();
7005 end;
7006 end
7007 else // Это не бездна и мы еще не летим туда
7008 if GetAIFlag('GOINHOLE') = '' then
7009 case Random(6) of
7010 0: Turn(); // Не нужно туда
7011 1: Jump(); // Вдруг повезет - прыгаем
7012 else // Если яма с границей, то при случае можно туда прыгнуть
7013 if BorderHole() then
7014 SetAIFlag('GOINHOLE', '1');
7015 end;
7017 // Если на земле, но некуда идти:
7018 if (not CanRun()) and OnGround() then
7019 begin
7020 // Если мы на лестнице или можно перепрыгнуть, то прыгаем:
7021 if CanJumpOver() or OnLadder() then
7022 Jump()
7023 else // иначе попытаемся в другую сторону
7024 if Random(2) = 0 then
7025 begin
7026 if IsSafeTrigger() then
7027 PressKey(KEY_OPEN);
7028 end else
7029 Turn();
7030 end;
7032 // Осталось мало воздуха:
7033 if FAir < 36 * 2 then
7034 Jump(20);
7036 // Выбираемся из кислоты, если нет костюма, обожглись, или мало здоровья:
7037 if (FMegaRulez[MR_SUIT] < gTime) and ((FLastHit = HIT_ACID) or (Healthy() <= 1)) then
7038 if BodyInAcid(0, 0) then
7039 Jump();
7040 end;
7042 function TBot.FullInStep(XInc, YInc: Integer): Boolean;
7043 begin
7044 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
7045 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_STEP, False);
7046 end;
7048 {function TBot.NeedItem(Item: Byte): Byte;
7049 begin
7050 Result := 4;
7051 end;}
7053 procedure TBot.SelectWeapon(Dist: Integer);
7054 var
7055 a: Integer;
7057 function HaveAmmo(weapon: Byte): Boolean;
7058 begin
7059 case weapon of
7060 WEAPON_PISTOL: Result := FAmmo[A_BULLETS] >= 1;
7061 WEAPON_SHOTGUN1: Result := FAmmo[A_SHELLS] >= 1;
7062 WEAPON_SHOTGUN2: Result := FAmmo[A_SHELLS] >= 2;
7063 WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS] >= 10;
7064 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS] >= 1;
7065 WEAPON_PLASMA: Result := FAmmo[A_CELLS] >= 10;
7066 WEAPON_BFG: Result := FAmmo[A_CELLS] >= 40;
7067 WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS] >= 1;
7068 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL] >= 1;
7069 else Result := True;
7070 end;
7071 end;
7073 begin
7074 if Dist = -1 then Dist := BOT_LONGDIST;
7076 if Dist > BOT_LONGDIST then
7077 begin // Дальний бой
7078 for a := 0 to 9 do
7079 if FWeapon[FDifficult.WeaponPrior[a]] and HaveAmmo(FDifficult.WeaponPrior[a]) then
7080 begin
7081 FSelectedWeapon := FDifficult.WeaponPrior[a];
7082 Break;
7083 end;
7084 end
7085 else //if Dist > BOT_UNSAFEDIST then
7086 begin // Ближний бой
7087 for a := 0 to 9 do
7088 if FWeapon[FDifficult.CloseWeaponPrior[a]] and HaveAmmo(FDifficult.CloseWeaponPrior[a]) then
7089 begin
7090 FSelectedWeapon := FDifficult.CloseWeaponPrior[a];
7091 Break;
7092 end;
7093 end;
7094 { else
7095 begin
7096 for a := 0 to 9 do
7097 if FWeapon[FDifficult.SafeWeaponPrior[a]] and HaveAmmo(FDifficult.SafeWeaponPrior[a]) then
7098 begin
7099 FSelectedWeapon := FDifficult.SafeWeaponPrior[a];
7100 Break;
7101 end;
7102 end;}
7103 end;
7105 function TBot.PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean;
7106 begin
7107 Result := inherited PickItem(ItemType, force, remove);
7109 if Result then SetAIFlag('SELECTWEAPON', '1');
7110 end;
7112 function TBot.Heal(value: Word; Soft: Boolean): Boolean;
7113 begin
7114 Result := inherited Heal(value, Soft);
7115 end;
7117 function TBot.Healthy(): Byte;
7118 begin
7119 if FMegaRulez[MR_INVUL] >= gTime then Result := 3
7120 else if (FHealth > 80) or ((FHealth > 50) and (FArmor > 20)) then Result := 3
7121 else if (FHealth > 50) then Result := 2
7122 else if (FHealth > 20) then Result := 1
7123 else Result := 0;
7124 end;
7126 function TBot.TargetOnScreen(TX, TY: Integer): Boolean;
7127 begin
7128 Result := (Abs(FObj.X-TX) <= Trunc(gPlayerScreenSize.X*0.6)) and
7129 (Abs(FObj.Y-TY) <= Trunc(gPlayerScreenSize.Y*0.6));
7130 end;
7132 procedure TBot.OnDamage(Angle: SmallInt);
7133 var
7134 pla: TPlayer;
7135 mon: TMonster;
7136 ok: Boolean;
7137 begin
7138 inherited;
7140 if (Angle = 0) or (Angle = 180) then
7141 begin
7142 ok := False;
7143 if (g_GetUIDType(FLastSpawnerUID) = UID_PLAYER) and
7144 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER) then
7145 begin // Игрок
7146 pla := g_Player_Get(FLastSpawnerUID);
7147 ok := not TargetOnScreen(pla.FObj.X + PLAYER_RECT.X,
7148 pla.FObj.Y + PLAYER_RECT.Y);
7149 end
7150 else
7151 if (g_GetUIDType(FLastSpawnerUID) = UID_MONSTER) and
7152 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER) then
7153 begin // Монстр
7154 mon := g_Monsters_ByUID(FLastSpawnerUID);
7155 ok := not TargetOnScreen(mon.Obj.X + mon.Obj.Rect.X,
7156 mon.Obj.Y + mon.Obj.Rect.Y);
7157 end;
7159 if ok then
7160 if Angle = 0 then
7161 SetAIFlag('ATTACKLEFT', '1')
7162 else
7163 SetAIFlag('ATTACKRIGHT', '1');
7164 end;
7165 end;
7167 function TBot.RunDirection(): TDirection;
7168 begin
7169 if Abs(Vel.X) >= 1 then
7170 begin
7171 if Vel.X > 0 then Result := TDirection.D_RIGHT else Result := TDirection.D_LEFT;
7172 end else
7173 Result := FDirection;
7174 end;
7176 function TBot.GetRnd(a: Byte): Boolean;
7177 begin
7178 if a = 0 then Result := False
7179 else if a = 255 then Result := True
7180 else Result := Random(256) > 255-a;
7181 end;
7183 function TBot.GetInterval(a: Byte; radius: SmallInt): SmallInt;
7184 begin
7185 Result := Round((255-a)/255*radius*(Random(2)-1));
7186 end;
7189 procedure TDifficult.save (st: TStream);
7190 begin
7191 utils.writeInt(st, Byte(DiagFire));
7192 utils.writeInt(st, Byte(InvisFire));
7193 utils.writeInt(st, Byte(DiagPrecision));
7194 utils.writeInt(st, Byte(FlyPrecision));
7195 utils.writeInt(st, Byte(Cover));
7196 utils.writeInt(st, Byte(CloseJump));
7197 st.WriteBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7198 st.WriteBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7199 end;
7201 procedure TDifficult.load (st: TStream);
7202 begin
7203 DiagFire := utils.readByte(st);
7204 InvisFire := utils.readByte(st);
7205 DiagPrecision := utils.readByte(st);
7206 FlyPrecision := utils.readByte(st);
7207 Cover := utils.readByte(st);
7208 CloseJump := utils.readByte(st);
7209 st.ReadBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7210 st.ReadBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7211 end;
7214 procedure TBot.SaveState (st: TStream);
7215 var
7216 i: Integer;
7217 dw: Integer;
7218 begin
7219 inherited SaveState(st);
7220 utils.writeSign(st, 'BOT0');
7221 // Выбранное оружие
7222 utils.writeInt(st, Byte(FSelectedWeapon));
7223 // UID цели
7224 utils.writeInt(st, Word(FTargetUID));
7225 // Время потери цели
7226 utils.writeInt(st, LongWord(FLastVisible));
7227 // Количество флагов ИИ
7228 dw := Length(FAIFlags);
7229 utils.writeInt(st, LongInt(dw));
7230 // Флаги ИИ
7231 for i := 0 to dw-1 do
7232 begin
7233 utils.writeStr(st, FAIFlags[i].Name, 20);
7234 utils.writeStr(st, FAIFlags[i].Value, 20);
7235 end;
7236 // Настройки сложности
7237 FDifficult.save(st);
7238 end;
7241 procedure TBot.LoadState (st: TStream);
7242 var
7243 i: Integer;
7244 dw: Integer;
7245 begin
7246 inherited LoadState(st);
7247 if not utils.checkSign(st, 'BOT0') then raise XStreamError.Create('invalid bot signature');
7248 // Выбранное оружие
7249 FSelectedWeapon := utils.readByte(st);
7250 // UID цели
7251 FTargetUID := utils.readWord(st);
7252 // Время потери цели
7253 FLastVisible := utils.readLongWord(st);
7254 // Количество флагов ИИ
7255 dw := utils.readLongInt(st);
7256 if (dw < 0) or (dw > 16384) then raise XStreamError.Create('invalid number of bot AI flags');
7257 SetLength(FAIFlags, dw);
7258 // Флаги ИИ
7259 for i := 0 to dw-1 do
7260 begin
7261 FAIFlags[i].Name := utils.readStr(st, 20);
7262 FAIFlags[i].Value := utils.readStr(st, 20);
7263 end;
7264 // Настройки сложности
7265 FDifficult.load(st);
7266 end;
7269 begin
7270 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');
7271 conRegVar('player_indicator_style', @gPlayerIndicatorStyle, 'Visual appearance of indicator', 'Visual appearance of indicator');
7272 end.