DEADSOFTWARE

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