DEADSOFTWARE

render: hide gib textures within render
[d2df-sdl.git] / src / game / g_player.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 {$M+}
17 unit g_player;
19 interface
21 uses
22 SysUtils, Classes,
23 {$IFDEF USE_MEMPOOL}mempool,{$ENDIF}
24 g_base, g_playermodel, g_basic, g_textures,
25 g_weapons, g_phys, g_sound, g_saveload, MAPDEF,
26 g_panel, 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: TAnimation;
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: TAnimation 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;
2149 resetWeaponQueue();
2150 end;
2152 procedure TPlayer.positionChanged (); inline;
2153 begin
2154 end;
2156 procedure TPlayer.doDamage (v: Integer);
2157 begin
2158 if (v <= 0) then exit;
2159 if (v > 32767) then v := 32767;
2160 Damage(v, 0, 0, 0, mEDamageType);
2161 end;
2163 procedure TPlayer.Damage(value: Word; SpawnerUID: Word; vx, vy: Integer; t: Byte);
2164 var
2165 c: Word;
2166 begin
2167 if (not g_Game_IsClient) and (not FAlive) then
2168 Exit;
2170 FLastHit := t;
2172 // Неуязвимость не спасает от ловушек:
2173 if ((t = HIT_TRAP) or (t = HIT_SELF)) and (not FGodMode) then
2174 begin
2175 if not g_Game_IsClient then
2176 begin
2177 FArmor := 0;
2178 if t = HIT_TRAP then
2179 begin
2180 // Ловушка убивает сразу:
2181 FHealth := -100;
2182 Kill(K_EXTRAHARDKILL, SpawnerUID, t);
2183 end;
2184 if t = HIT_SELF then
2185 begin
2186 // Самоубийство:
2187 FHealth := 0;
2188 Kill(K_SIMPLEKILL, SpawnerUID, t);
2189 end;
2190 end;
2191 // Обнулить действия примочек, чтобы фон пропал
2192 FMegaRulez[MR_SUIT] := 0;
2193 FMegaRulez[MR_INVUL] := 0;
2194 FMegaRulez[MR_INVIS] := 0;
2195 FSpawnInvul := 0;
2196 FBerserk := 0;
2197 end;
2199 // Но от остального спасает:
2200 if FMegaRulez[MR_INVUL] >= gTime then
2201 Exit;
2203 // Чит-код "ГОРЕЦ":
2204 if FGodMode then
2205 Exit;
2207 // Если есть урон своим, или ранил сам себя, или тебя ранил противник:
2208 if LongBool(gGameSettings.Options and GAME_OPTION_TEAMDAMAGE) or
2209 (SpawnerUID = FUID) or
2210 (not SameTeam(FUID, SpawnerUID)) then
2211 begin
2212 FLastSpawnerUID := SpawnerUID;
2214 // Кровь (пузырьки, если в воде):
2215 if gBloodCount > 0 then
2216 begin
2217 c := Min(value, 200)*gBloodCount + Random(Min(value, 200) div 2);
2218 if value div 4 <= c then
2219 c := c - (value div 4)
2220 else
2221 c := 0;
2223 if (t = HIT_SOME) and (vx = 0) and (vy = 0) then
2224 MakeBloodSimple(c)
2225 else
2226 case t of
2227 HIT_TRAP, HIT_ACID, HIT_FLAME, HIT_SELF: MakeBloodSimple(c);
2228 HIT_BFG, HIT_ROCKET, HIT_SOME: MakeBloodVector(c, vx, vy);
2229 end;
2231 if t = HIT_WATER then
2232 begin
2233 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
2234 FObj.Y+PLAYER_RECT.Y-4, value div 2, 8, 4);
2235 if Random(2) = 0
2236 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
2237 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
2238 end;
2239 end;
2241 // Буфер урона:
2242 if FAlive then
2243 Inc(FDamageBuffer, value);
2245 // Вспышка боли:
2246 if gFlash <> 0 then
2247 FPain := FPain + value;
2248 end;
2250 if g_Game_IsServer and g_Game_IsNet then
2251 begin
2252 MH_SEND_PlayerDamage(FUID, t, SpawnerUID, value, vx, vy);
2253 MH_SEND_PlayerStats(FUID);
2254 MH_SEND_PlayerPos(False, FUID);
2255 end;
2256 end;
2258 function TPlayer.Heal(value: Word; Soft: Boolean): Boolean;
2259 begin
2260 Result := False;
2261 if g_Game_IsClient then
2262 Exit;
2263 if not FAlive then
2264 Exit;
2266 if Soft and (FHealth < PLAYER_HP_SOFT) then
2267 begin
2268 IncMax(FHealth, value, PLAYER_HP_SOFT);
2269 Result := True;
2270 end;
2271 if (not Soft) and (FHealth < PLAYER_HP_LIMIT) then
2272 begin
2273 IncMax(FHealth, value, PLAYER_HP_LIMIT);
2274 Result := True;
2275 end;
2277 if Result and g_Game_IsServer and g_Game_IsNet then
2278 MH_SEND_PlayerStats(FUID);
2279 end;
2281 destructor TPlayer.Destroy();
2282 begin
2283 if (gPlayer1 <> nil) and (gPlayer1.FUID = FUID) then
2284 gPlayer1 := nil;
2285 if (gPlayer2 <> nil) and (gPlayer2.FUID = FUID) then
2286 gPlayer2 := nil;
2288 FSawSound.Free();
2289 FSawSoundIdle.Free();
2290 FSawSoundHit.Free();
2291 FSawSoundSelect.Free();
2292 FFlameSoundOn.Free();
2293 FFlameSoundOff.Free();
2294 FFlameSoundWork.Free();
2295 FJetSoundFly.Free();
2296 FJetSoundOn.Free();
2297 FJetSoundOff.Free();
2298 FModel.Free();
2299 if FPunchAnim <> nil then
2300 FPunchAnim.Free();
2302 inherited;
2303 end;
2305 procedure TPlayer.DoPunch();
2306 var
2307 id: DWORD;
2308 st: String;
2309 begin
2310 if FPunchAnim <> nil then begin
2311 FPunchAnim.reset();
2312 FPunchAnim.Free;
2313 FPunchAnim := nil;
2314 end;
2315 st := 'FRAMES_PUNCH';
2316 if R_BERSERK in FRulez then
2317 st := st + '_BERSERK';
2318 if FKeys[KEY_UP].Pressed then
2319 st := st + '_UP'
2320 else if FKeys[KEY_DOWN].Pressed then
2321 st := st + '_DN';
2322 g_Frames_Get(id, st);
2323 FPunchAnim := TAnimation.Create(id, False, 1);
2324 end;
2326 procedure TPlayer.Fire();
2327 var
2328 f, DidFire: Boolean;
2329 wx, wy, xd, yd: Integer;
2330 locobj: TObj;
2331 begin
2332 if g_Game_IsClient then Exit;
2333 // FBFGFireCounter - время перед выстрелом (для BFG)
2334 // FReloading - время после выстрела (для всего)
2336 if FSpectator then
2337 begin
2338 Respawn(False);
2339 Exit;
2340 end;
2342 if FReloading[FCurrWeap] <> 0 then Exit;
2344 DidFire := False;
2346 f := False;
2347 wx := FObj.X+WEAPONPOINT[FDirection].X;
2348 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
2349 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
2350 yd := wy+firediry();
2352 case FCurrWeap of
2353 WEAPON_KASTET:
2354 begin
2355 DoPunch();
2356 if R_BERSERK in FRulez then
2357 begin
2358 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
2359 locobj.X := FObj.X+FObj.Rect.X;
2360 locobj.Y := FObj.Y+FObj.Rect.Y;
2361 locobj.rect.X := 0;
2362 locobj.rect.Y := 0;
2363 locobj.rect.Width := 39;
2364 locobj.rect.Height := 52;
2365 locobj.Vel.X := (xd-wx) div 2;
2366 locobj.Vel.Y := (yd-wy) div 2;
2367 locobj.Accel.X := xd-wx;
2368 locobj.Accel.y := yd-wy;
2370 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
2371 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
2372 else
2373 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
2375 if (gFlash = 1) and (FPain < 50) then FPain := min(FPain + 25, 50);
2376 end
2377 else
2378 begin
2379 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
2380 end;
2382 DidFire := True;
2383 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2384 end;
2386 WEAPON_SAW:
2387 begin
2388 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
2389 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
2390 begin
2391 FSawSoundSelect.Stop();
2392 FSawSound.Stop();
2393 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
2394 end
2395 else if not FSawSoundHit.IsPlaying() then
2396 begin
2397 FSawSoundSelect.Stop();
2398 FSawSound.PlayAt(FObj.X, FObj.Y);
2399 end;
2401 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2402 DidFire := True;
2403 f := True;
2404 end;
2406 WEAPON_PISTOL:
2407 if FAmmo[A_BULLETS] > 0 then
2408 begin
2409 g_Weapon_pistol(wx, wy, xd, yd, FUID);
2410 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2411 Dec(FAmmo[A_BULLETS]);
2412 FFireAngle := FAngle;
2413 f := True;
2414 DidFire := True;
2415 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2416 GameVelX, GameVelY-2, SHELL_BULLET);
2417 end;
2419 WEAPON_SHOTGUN1:
2420 if FAmmo[A_SHELLS] > 0 then
2421 begin
2422 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2423 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', wx, wy);
2424 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2425 Dec(FAmmo[A_SHELLS]);
2426 FFireAngle := FAngle;
2427 f := True;
2428 DidFire := True;
2429 FShellTimer := 10;
2430 FShellType := SHELL_SHELL;
2431 end;
2433 WEAPON_SHOTGUN2:
2434 if FAmmo[A_SHELLS] >= 2 then
2435 begin
2436 g_Weapon_dshotgun(wx, wy, xd, yd, FUID);
2437 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2438 Dec(FAmmo[A_SHELLS], 2);
2439 FFireAngle := FAngle;
2440 f := True;
2441 DidFire := True;
2442 FShellTimer := 13;
2443 FShellType := SHELL_DBLSHELL;
2444 end;
2446 WEAPON_CHAINGUN:
2447 if FAmmo[A_BULLETS] > 0 then
2448 begin
2449 g_Weapon_mgun(wx, wy, xd, yd, FUID);
2450 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', wx, wy);
2451 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2452 Dec(FAmmo[A_BULLETS]);
2453 FFireAngle := FAngle;
2454 f := True;
2455 DidFire := True;
2456 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2457 GameVelX, GameVelY-2, SHELL_BULLET);
2458 end;
2460 WEAPON_ROCKETLAUNCHER:
2461 if FAmmo[A_ROCKETS] > 0 then
2462 begin
2463 g_Weapon_rocket(wx, wy, xd, yd, FUID);
2464 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2465 Dec(FAmmo[A_ROCKETS]);
2466 FFireAngle := FAngle;
2467 f := True;
2468 DidFire := True;
2469 end;
2471 WEAPON_PLASMA:
2472 if FAmmo[A_CELLS] > 0 then
2473 begin
2474 g_Weapon_plasma(wx, wy, xd, yd, FUID);
2475 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2476 Dec(FAmmo[A_CELLS]);
2477 FFireAngle := FAngle;
2478 f := True;
2479 DidFire := True;
2480 end;
2482 WEAPON_BFG:
2483 if (FAmmo[A_CELLS] >= 40) and (FBFGFireCounter = -1) then
2484 begin
2485 FBFGFireCounter := 17;
2486 if not FNoReload then
2487 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', FObj.X, FObj.Y);
2488 Dec(FAmmo[A_CELLS], 40);
2489 DidFire := True;
2490 end;
2492 WEAPON_SUPERPULEMET:
2493 if FAmmo[A_SHELLS] > 0 then
2494 begin
2495 g_Weapon_shotgun(wx, wy, xd, yd, FUID);
2496 if not gSoundEffectsDF then g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', wx, wy);
2497 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2498 Dec(FAmmo[A_SHELLS]);
2499 FFireAngle := FAngle;
2500 f := True;
2501 DidFire := True;
2502 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
2503 GameVelX, GameVelY-2, SHELL_SHELL);
2504 end;
2506 WEAPON_FLAMETHROWER:
2507 if FAmmo[A_FUEL] > 0 then
2508 begin
2509 g_Weapon_flame(wx, wy, xd, yd, FUID);
2510 FlamerOn;
2511 FReloading[FCurrWeap] := WEAPON_RELOAD[FCurrWeap];
2512 Dec(FAmmo[A_FUEL]);
2513 FFireAngle := FAngle;
2514 f := True;
2515 DidFire := True;
2516 end
2517 else
2518 begin
2519 FlamerOff;
2520 if g_Game_IsNet and g_Game_IsServer then MH_SEND_PlayerStats(FUID);
2521 end;
2522 end;
2524 if g_Game_IsNet then
2525 begin
2526 if DidFire then
2527 begin
2528 if FCurrWeap <> WEAPON_BFG then
2529 MH_SEND_PlayerFire(FUID, FCurrWeap, wx, wy, xd, yd, LastShotID)
2530 else
2531 if not FNoReload then
2532 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_WEAPON_STARTFIREBFG');
2533 end;
2535 MH_SEND_PlayerStats(FUID);
2536 end;
2538 if not f then Exit;
2540 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
2541 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
2542 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
2543 end;
2545 function TPlayer.GetAmmoByWeapon(Weapon: Byte): Word;
2546 begin
2547 case Weapon of
2548 WEAPON_PISTOL, WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS];
2549 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS];
2550 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS];
2551 WEAPON_PLASMA, WEAPON_BFG: Result := FAmmo[A_CELLS];
2552 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL];
2553 else Result := 0;
2554 end;
2555 end;
2557 function TPlayer.HeadInLiquid(XInc, YInc: Integer): Boolean;
2558 begin
2559 Result := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X+XInc, FObj.Y+PLAYER_HEADRECT.Y+YInc,
2560 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
2561 PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, True);
2562 end;
2564 procedure TPlayer.FlamerOn;
2565 begin
2566 FFlameSoundOff.Stop();
2567 FFlameSoundOff.SetPosition(0);
2568 if FFlaming then
2569 begin
2570 if (not FFlameSoundOn.IsPlaying()) and (not FFlameSoundWork.IsPlaying()) then
2571 FFlameSoundWork.PlayAt(FObj.X, FObj.Y);
2572 end
2573 else
2574 begin
2575 FFlameSoundOn.PlayAt(FObj.X, FObj.Y);
2576 FFlaming := True;
2577 end;
2578 end;
2580 procedure TPlayer.FlamerOff;
2581 begin
2582 if FFlaming then
2583 begin
2584 FFlameSoundOn.Stop();
2585 FFlameSoundOn.SetPosition(0);
2586 FFlameSoundWork.Stop();
2587 FFlameSoundWork.SetPosition(0);
2588 FFlameSoundOff.PlayAt(FObj.X, FObj.Y);
2589 FFlaming := False;
2590 end;
2591 end;
2593 procedure TPlayer.JetpackOn;
2594 begin
2595 FJetSoundFly.Stop;
2596 FJetSoundOff.Stop;
2597 FJetSoundOn.SetPosition(0);
2598 FJetSoundOn.PlayAt(FObj.X, FObj.Y);
2599 FlySmoke(8);
2600 end;
2602 procedure TPlayer.JetpackOff;
2603 begin
2604 FJetSoundFly.Stop;
2605 FJetSoundOn.Stop;
2606 FJetSoundOff.SetPosition(0);
2607 FJetSoundOff.PlayAt(FObj.X, FObj.Y);
2608 end;
2610 procedure TPlayer.CatchFire(Attacker: Word; Timeout: Integer = PLAYER_BURN_TIME);
2611 begin
2612 if Timeout <= 0 then
2613 exit;
2614 if (FMegaRulez[MR_SUIT] > gTime) or (FMegaRulez[MR_INVUL] > gTime) then
2615 exit; // Не загораемся когда есть защита
2616 if g_Obj_CollidePanel(@FObj, 0, 0, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2) then
2617 exit; // Не подгораем в воде на всякий случай
2618 if FFireTime <= 0 then
2619 g_Sound_PlayExAt('SOUND_IGNITE', FObj.X, FObj.Y);
2620 FFireTime := Timeout;
2621 FFireAttacker := Attacker;
2622 if g_Game_IsNet and g_Game_IsServer then
2623 MH_SEND_PlayerStats(FUID);
2624 end;
2626 procedure TPlayer.Jump();
2627 begin
2628 if gFly or FJetpack then
2629 begin
2630 // Полет (чит-код или джетпак):
2631 if FObj.Vel.Y > -VEL_FLY then
2632 FObj.Vel.Y := FObj.Vel.Y - 3;
2633 if FJetpack then
2634 begin
2635 if FJetFuel > 0 then
2636 Dec(FJetFuel);
2637 if (FJetFuel < 1) and g_Game_IsServer then
2638 begin
2639 FJetpack := False;
2640 JetpackOff;
2641 if g_Game_IsNet then
2642 MH_SEND_PlayerStats(FUID);
2643 end;
2644 end;
2645 Exit;
2646 end;
2648 // Не включать джетпак в режиме прохождения сквозь стены
2649 if FGhost then
2650 FCanJetpack := False;
2652 // Прыгаем или всплываем:
2653 if (CollideLevel(0, 1) or
2654 g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y+36, PLAYER_RECT.Width,
2655 PLAYER_RECT.Height-33, PANEL_STEP, False)
2656 ) and (FObj.Accel.Y = 0) then // Не прыгать, если есть вертикальное ускорение
2657 begin
2658 FObj.Vel.Y := -VEL_JUMP;
2659 FCanJetpack := False;
2660 end
2661 else
2662 begin
2663 if BodyInLiquid(0, 0) then
2664 FObj.Vel.Y := -VEL_SW
2665 else if (FJetFuel > 0) and FCanJetpack and
2666 g_Game_IsServer and (not g_Obj_CollideLiquid(@FObj, 0, 0)) then
2667 begin
2668 FJetpack := True;
2669 JetpackOn;
2670 if g_Game_IsNet then
2671 MH_SEND_PlayerStats(FUID);
2672 end;
2673 end;
2674 end;
2676 procedure TPlayer.Kill(KillType: Byte; SpawnerUID: Word; t: Byte);
2677 var
2678 a, i, k, ab, ar: Byte;
2679 s: String;
2680 mon: TMonster;
2681 plr: TPlayer;
2682 srv, netsrv: Boolean;
2683 DoFrags: Boolean;
2684 OldLR: Byte;
2685 KP: TPlayer;
2686 it: PItem;
2688 procedure PushItem(t: Byte);
2689 var
2690 id: DWORD;
2691 begin
2692 id := g_Items_Create(FObj.X, FObj.Y, t, True, False);
2693 it := g_Items_ByIdx(id);
2694 if KillType = K_EXTRAHARDKILL then // -7..+7; -8..0
2695 begin
2696 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-7+Random(15),
2697 (FObj.Vel.Y div 2)-Random(9));
2698 it.positionChanged(); // this updates spatial accelerators
2699 end
2700 else
2701 begin
2702 if KillType = K_HARDKILL then // -5..+5; -5..0
2703 begin
2704 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-5+Random(11),
2705 (FObj.Vel.Y div 2)-Random(6));
2706 end
2707 else // -3..+3; -3..0
2708 begin
2709 g_Obj_Push(@it.Obj, (FObj.Vel.X div 2)-3+Random(7),
2710 (FObj.Vel.Y div 2)-Random(4));
2711 end;
2712 it.positionChanged(); // this updates spatial accelerators
2713 end;
2715 if g_Game_IsNet and g_Game_IsServer then
2716 MH_SEND_ItemSpawn(True, id);
2717 end;
2719 begin
2720 DoFrags := (gGameSettings.MaxLives = 0) or (gGameSettings.GameMode = GM_COOP);
2721 Srv := g_Game_IsServer;
2722 Netsrv := g_Game_IsServer and g_Game_IsNet;
2723 if Srv then FDeath := FDeath + 1;
2724 if FAlive then
2725 begin
2726 if FGhost then
2727 FGhost := False;
2728 if not FPhysics then
2729 FPhysics := True;
2730 FAlive := False;
2731 end;
2732 FShellTimer := -1;
2734 if (gGameSettings.MaxLives > 0) and Srv and (gLMSRespawn = LMS_RESPAWN_NONE) then
2735 begin
2736 if FLives > 0 then FLives := FLives - 1;
2737 if FLives = 0 then FNoRespawn := True;
2738 end;
2740 // Номер типа смерти:
2741 a := 1;
2742 case KillType of
2743 K_SIMPLEKILL: a := 1;
2744 K_HARDKILL: a := 2;
2745 K_EXTRAHARDKILL: a := 3;
2746 K_FALLKILL: a := 4;
2747 end;
2749 // Звук смерти:
2750 if not FModel.PlaySound(MODELSOUND_DIE, a, FObj.X, FObj.Y) then
2751 for i := 1 to 3 do
2752 if FModel.PlaySound(MODELSOUND_DIE, i, FObj.X, FObj.Y) then
2753 Break;
2755 // Время респауна:
2756 if Srv then
2757 case KillType of
2758 K_SIMPLEKILL:
2759 FTime[T_RESPAWN] := gTime + TIME_RESPAWN1;
2760 K_HARDKILL:
2761 FTime[T_RESPAWN] := gTime + TIME_RESPAWN2;
2762 K_EXTRAHARDKILL, K_FALLKILL:
2763 FTime[T_RESPAWN] := gTime + TIME_RESPAWN3;
2764 end;
2766 // Переключаем состояние:
2767 case KillType of
2768 K_SIMPLEKILL:
2769 SetAction(A_DIE1);
2770 K_HARDKILL, K_EXTRAHARDKILL:
2771 SetAction(A_DIE2);
2772 end;
2774 // Реакция монстров на смерть игрока:
2775 if (KillType <> K_FALLKILL) and (Srv) then
2776 g_Monsters_killedp();
2778 if SpawnerUID = FUID then
2779 begin // Самоубился
2780 if Srv then
2781 begin
2782 if gGameSettings.GameMode = GM_TDM then
2783 Dec(gTeamStat[FTeam].Score);
2784 if DoFrags or (gGameSettings.GameMode = GM_TDM) then
2785 begin
2786 Dec(FFrags);
2787 FLastFrag := 0;
2788 end;
2789 end;
2790 g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2791 end
2792 else
2793 if g_GetUIDType(SpawnerUID) = UID_PLAYER then
2794 begin // Убит другим игроком
2795 KP := g_Player_Get(SpawnerUID);
2796 if (KP <> nil) and Srv then
2797 begin
2798 if (DoFrags or (gGameSettings.GameMode = GM_TDM)) then
2799 if SameTeam(FUID, SpawnerUID) then
2800 begin
2801 Dec(KP.FFrags);
2802 KP.FLastFrag := 0;
2803 end else
2804 begin
2805 Inc(KP.FFrags);
2806 KP.FragCombo();
2807 end;
2809 if (gGameSettings.GameMode = GM_TDM) and DoFrags then
2810 Inc(gTeamStat[KP.Team].Score,
2811 IfThen(SameTeam(FUID, SpawnerUID), -1, 1));
2813 if netsrv then MH_SEND_PlayerStats(SpawnerUID);
2814 end;
2816 plr := g_Player_Get(SpawnerUID);
2817 if plr = nil then
2818 s := '?'
2819 else
2820 s := plr.FName;
2822 case KillType of
2823 K_HARDKILL:
2824 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2825 [FName, s]),
2826 gShowKillMsg);
2827 K_EXTRAHARDKILL:
2828 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2829 [FName, s]),
2830 gShowKillMsg);
2831 else
2832 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2833 [FName, s]),
2834 gShowKillMsg);
2835 end;
2836 end
2837 else if g_GetUIDType(SpawnerUID) = UID_MONSTER then
2838 begin // Убит монстром
2839 mon := g_Monsters_ByUID(SpawnerUID);
2840 if mon = nil then
2841 s := '?'
2842 else
2843 s := g_Mons_GetKilledByTypeId(mon.MonsterType);
2845 case KillType of
2846 K_HARDKILL:
2847 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_2],
2848 [FName, s]),
2849 gShowKillMsg);
2850 K_EXTRAHARDKILL:
2851 g_Console_Add(Format(_lc[I_PLAYER_KILL_EXTRAHARD_1],
2852 [FName, s]),
2853 gShowKillMsg);
2854 else
2855 g_Console_Add(Format(_lc[I_PLAYER_KILL],
2856 [FName, s]),
2857 gShowKillMsg);
2858 end;
2859 end
2860 else // Особые типы смерти
2861 case t of
2862 HIT_DISCON: ;
2863 HIT_SELF: g_Console_Add(Format(_lc[I_PLAYER_KILL_SELF], [FName]), True);
2864 HIT_FALL: g_Console_Add(Format(_lc[I_PLAYER_KILL_FALL], [FName]), True);
2865 HIT_WATER: g_Console_Add(Format(_lc[I_PLAYER_KILL_WATER], [FName]), True);
2866 HIT_ACID: g_Console_Add(Format(_lc[I_PLAYER_KILL_ACID], [FName]), True);
2867 HIT_TRAP: g_Console_Add(Format(_lc[I_PLAYER_KILL_TRAP], [FName]), True);
2868 else g_Console_Add(Format(_lc[I_PLAYER_DIED], [FName]), True);
2869 end;
2871 if Srv then
2872 begin
2873 // Выброс оружия:
2874 for a := WP_FIRST to WP_LAST do
2875 if FWeapon[a] then
2876 begin
2877 case a of
2878 WEAPON_SAW: i := ITEM_WEAPON_SAW;
2879 WEAPON_SHOTGUN1: i := ITEM_WEAPON_SHOTGUN1;
2880 WEAPON_SHOTGUN2: i := ITEM_WEAPON_SHOTGUN2;
2881 WEAPON_CHAINGUN: i := ITEM_WEAPON_CHAINGUN;
2882 WEAPON_ROCKETLAUNCHER: i := ITEM_WEAPON_ROCKETLAUNCHER;
2883 WEAPON_PLASMA: i := ITEM_WEAPON_PLASMA;
2884 WEAPON_BFG: i := ITEM_WEAPON_BFG;
2885 WEAPON_SUPERPULEMET: i := ITEM_WEAPON_SUPERPULEMET;
2886 WEAPON_FLAMETHROWER: i := ITEM_WEAPON_FLAMETHROWER;
2887 else i := 0;
2888 end;
2890 if i <> 0 then
2891 PushItem(i);
2892 end;
2894 // Выброс рюкзака:
2895 if R_ITEM_BACKPACK in FRulez then
2896 PushItem(ITEM_AMMO_BACKPACK);
2898 // Выброс ракетного ранца:
2899 if FJetFuel > 0 then
2900 PushItem(ITEM_JETPACK);
2902 // Выброс ключей:
2903 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) or
2904 (not LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS)) then
2905 begin
2906 if R_KEY_RED in FRulez then
2907 PushItem(ITEM_KEY_RED);
2909 if R_KEY_GREEN in FRulez then
2910 PushItem(ITEM_KEY_GREEN);
2912 if R_KEY_BLUE in FRulez then
2913 PushItem(ITEM_KEY_BLUE);
2914 end;
2916 // Выброс флага:
2917 DropFlag(KillType = K_FALLKILL);
2918 end;
2920 FCorpse := g_Player_CreateCorpse(Self);
2922 if Srv and (gGameSettings.MaxLives > 0) and FNoRespawn and
2923 (gLMSRespawn = LMS_RESPAWN_NONE) then
2924 begin
2925 a := 0;
2926 k := 0;
2927 ar := 0;
2928 ab := 0;
2929 for i := Low(gPlayers) to High(gPlayers) do
2930 begin
2931 if gPlayers[i] = nil then continue;
2932 if (not gPlayers[i].FNoRespawn) and (not gPlayers[i].FSpectator) then
2933 begin
2934 Inc(a);
2935 if gPlayers[i].FTeam = TEAM_RED then Inc(ar)
2936 else if gPlayers[i].FTeam = TEAM_BLUE then Inc(ab);
2937 k := i;
2938 end;
2939 end;
2941 OldLR := gLMSRespawn;
2942 if (gGameSettings.GameMode = GM_COOP) then
2943 begin
2944 if (a = 0) then
2945 begin
2946 // everyone is dead, restart the map
2947 g_Game_Message(_lc[I_MESSAGE_LMS_LOSE], 144);
2948 if Netsrv then
2949 MH_SEND_GameEvent(NET_EV_LMS_LOSE);
2950 gLMSRespawn := LMS_RESPAWN_FINAL;
2951 gLMSRespawnTime := gTime + 5000;
2952 end
2953 else if (a = 1) then
2954 begin
2955 if (gPlayers[k] <> nil) and not (gPlayers[k] is TBot) then
2956 if (gPlayers[k] = gPlayer1) or
2957 (gPlayers[k] = gPlayer2) then
2958 g_Console_Add('*** ' + _lc[I_MESSAGE_LMS_SURVIVOR] + ' ***', True)
2959 else if Netsrv and (gPlayers[k].FClientID >= 0) then
2960 MH_SEND_GameEvent(NET_EV_LMS_SURVIVOR, 0, 'N', gPlayers[k].FClientID);
2961 end;
2962 end
2963 else if (gGameSettings.GameMode = GM_TDM) then
2964 begin
2965 if (ab = 0) and (ar <> 0) then
2966 begin
2967 // blu team ded
2968 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 144);
2969 if Netsrv then
2970 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_RED);
2971 Inc(gTeamStat[TEAM_RED].Score);
2972 gLMSRespawn := LMS_RESPAWN_FINAL;
2973 gLMSRespawnTime := gTime + 5000;
2974 end
2975 else if (ar = 0) and (ab <> 0) then
2976 begin
2977 // red team ded
2978 g_Game_Message(Format(_lc[I_MESSAGE_TLMS_WIN], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 144);
2979 if Netsrv then
2980 MH_SEND_GameEvent(NET_EV_TLMS_WIN, TEAM_BLUE);
2981 Inc(gTeamStat[TEAM_BLUE].Score);
2982 gLMSRespawn := LMS_RESPAWN_FINAL;
2983 gLMSRespawnTime := gTime + 5000;
2984 end
2985 else if (ar = 0) and (ab = 0) then
2986 begin
2987 // everyone ded
2988 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
2989 if Netsrv then
2990 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
2991 gLMSRespawn := LMS_RESPAWN_FINAL;
2992 gLMSRespawnTime := gTime + 5000;
2993 end;
2994 end
2995 else if (gGameSettings.GameMode = GM_DM) then
2996 begin
2997 if (a = 1) then
2998 begin
2999 if gPlayers[k] <> nil then
3000 with gPlayers[k] do
3001 begin
3002 // survivor is the winner
3003 g_Game_Message(Format(_lc[I_MESSAGE_LMS_WIN], [AnsiUpperCase(FName)]), 144);
3004 if Netsrv then
3005 MH_SEND_GameEvent(NET_EV_LMS_WIN, 0, FName);
3006 Inc(FFrags);
3007 end;
3008 gLMSRespawn := LMS_RESPAWN_FINAL;
3009 gLMSRespawnTime := gTime + 5000;
3010 end
3011 else if (a = 0) then
3012 begin
3013 // everyone is dead, restart the map
3014 g_Game_Message(_lc[I_GAME_WIN_DRAW], 144);
3015 if Netsrv then
3016 MH_SEND_GameEvent(NET_EV_LMS_DRAW, 0, FName);
3017 gLMSRespawn := LMS_RESPAWN_FINAL;
3018 gLMSRespawnTime := gTime + 5000;
3019 end;
3020 end;
3021 if srv and (OldLR = LMS_RESPAWN_NONE) and (gLMSRespawn > LMS_RESPAWN_NONE) then
3022 begin
3023 if NetMode = NET_SERVER then
3024 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime)
3025 else
3026 g_Console_Add(Format(_lc[I_MSG_WARMUP_START], [(gLMSRespawnTime - gTime) div 1000]), True);
3027 end;
3028 end;
3030 if Netsrv then
3031 begin
3032 MH_SEND_PlayerStats(FUID);
3033 MH_SEND_PlayerDeath(FUID, KillType, t, SpawnerUID);
3034 if gGameSettings.GameMode = GM_TDM then MH_SEND_GameStats;
3035 end;
3037 if srv and FNoRespawn then Spectate(True);
3038 FWantsInGame := True;
3039 end;
3041 function TPlayer.BodyInLiquid(XInc, YInc: Integer): Boolean;
3042 begin
3043 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3044 PLAYER_RECT.Height-20, PANEL_WATER or PANEL_ACID1 or PANEL_ACID2, False);
3045 end;
3047 function TPlayer.BodyInAcid(XInc, YInc: Integer): Boolean;
3048 begin
3049 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc, PLAYER_RECT.Width,
3050 PLAYER_RECT.Height-20, PANEL_ACID1 or PANEL_ACID2, False);
3051 end;
3053 procedure TPlayer.MakeBloodSimple(Count: Word);
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)+8,
3058 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3059 Count div 2, 3, -1, 16, (PLAYER_RECT.Height*2 div 3),
3060 Blood.R, Blood.G, Blood.B, Blood.Kind);
3061 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-8,
3062 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3063 Count div 2, -3, -1, 16, (PLAYER_RECT.Height*2) div 3,
3064 Blood.R, Blood.G, Blood.B, Blood.Kind);
3065 end;
3067 procedure TPlayer.MakeBloodVector(Count: Word; VelX, VelY: Integer);
3068 var Blood: TModelBlood;
3069 begin
3070 Blood := SELF.FModel.GetBlood();
3071 g_GFX_Blood(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2),
3072 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2),
3073 Count, VelX, VelY, 16, (PLAYER_RECT.Height*2) div 3,
3074 Blood.R, Blood.G, Blood.B, Blood.Kind);
3075 end;
3077 procedure TPlayer.ProcessWeaponAction(Action: Byte);
3078 begin
3079 if g_Game_IsClient then Exit;
3080 case Action of
3081 WP_PREV: PrevWeapon();
3082 WP_NEXT: NextWeapon();
3083 end;
3084 end;
3086 procedure TPlayer.QueueWeaponSwitch(Weapon: Byte);
3087 begin
3088 if g_Game_IsClient then Exit;
3089 if Weapon > High(FWeapon) then Exit;
3090 FNextWeap := FNextWeap or (1 shl Weapon);
3091 end;
3093 procedure TPlayer.resetWeaponQueue ();
3094 begin
3095 FNextWeap := 0;
3096 FNextWeapDelay := 0;
3097 end;
3099 function TPlayer.hasAmmoForWeapon (weapon: Byte): Boolean;
3100 begin
3101 result := false;
3102 case weapon of
3103 WEAPON_KASTET, WEAPON_SAW: result := true;
3104 WEAPON_SHOTGUN1, WEAPON_SHOTGUN2, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3105 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3106 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3107 WEAPON_PLASMA, WEAPON_BFG: result := (FAmmo[A_CELLS] > 0);
3108 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3109 else result := (weapon < length(FWeapon));
3110 end;
3111 end;
3113 function TPlayer.hasAmmoForShooting (weapon: Byte): Boolean;
3114 begin
3115 result := false;
3116 case weapon of
3117 WEAPON_KASTET, WEAPON_SAW: result := true;
3118 WEAPON_SHOTGUN1, WEAPON_SUPERPULEMET: result := (FAmmo[A_SHELLS] > 0);
3119 WEAPON_SHOTGUN2: result := (FAmmo[A_SHELLS] > 1);
3120 WEAPON_PISTOL, WEAPON_CHAINGUN: result := (FAmmo[A_BULLETS] > 0);
3121 WEAPON_ROCKETLAUNCHER: result := (FAmmo[A_ROCKETS] > 0);
3122 WEAPON_PLASMA: result := (FAmmo[A_CELLS] > 0);
3123 WEAPON_BFG: result := (FAmmo[A_CELLS] >= 40);
3124 WEAPON_FLAMETHROWER: result := (FAmmo[A_FUEL] > 0);
3125 else result := (weapon < length(FWeapon));
3126 end;
3127 end;
3129 function TPlayer.shouldSwitch (weapon: Byte; hadWeapon: Boolean): Boolean;
3130 begin
3131 result := false;
3132 if (weapon > WP_LAST + 1) then
3133 begin
3134 result := false;
3135 exit;
3136 end;
3137 if (FWeapSwitchMode = 1) and not hadWeapon then
3138 result := true
3139 else if (FWeapSwitchMode = 2) then
3140 result := (FWeapPreferences[weapon] > FWeapPreferences[FCurrWeap]);
3141 end;
3143 // return 255 for "no switch"
3144 function TPlayer.getNextWeaponIndex (): Byte;
3145 var
3146 i: Word;
3147 wantThisWeapon: array[0..64] of Boolean;
3148 wwc: Integer = 0; //HACK!
3149 dir, cwi: Integer;
3150 begin
3151 result := 255; // default result: "no switch"
3152 //e_LogWriteFln('FSWITCHTOEMPTY: %s', [FSwitchToEmpty], TMsgType.Notify);
3153 // had weapon cycling on previous frame? remove that flag
3154 if (FNextWeap and $2000) <> 0 then
3155 begin
3156 FNextWeap := FNextWeap and $1FFF;
3157 FNextWeapDelay := 0;
3158 end;
3159 // cycling has priority
3160 if (FNextWeap and $C000) <> 0 then
3161 begin
3162 if (FNextWeap and $8000) <> 0 then
3163 dir := 1
3164 else
3165 dir := -1;
3166 FNextWeap := FNextWeap or $2000; // we need this
3167 if FNextWeapDelay > 0 then
3168 exit; // cooldown time
3169 cwi := FCurrWeap;
3170 for i := 0 to High(FWeapon) do
3171 begin
3172 cwi := (cwi+length(FWeapon)+dir) mod length(FWeapon);
3173 if FWeapon[cwi] and maySwitch(cwi) then
3174 begin
3175 //e_LogWriteFln(' SWITCH: cur=%d; new=%d %s %s', [FCurrWeap, cwi, FSwitchToEmpty, hasAmmoForWeapon(cwi)], TMsgType.Notify);
3176 result := Byte(cwi);
3177 FNextWeapDelay := WEAPON_DELAY;
3178 exit;
3179 end;
3180 end;
3181 resetWeaponQueue();
3182 exit;
3183 end;
3184 // no cycling
3185 for i := 0 to High(wantThisWeapon) do
3186 wantThisWeapon[i] := false;
3187 for i := 0 to High(FWeapon) do
3188 if (FNextWeap and (1 shl i)) <> 0 then
3189 begin
3190 wantThisWeapon[i] := true;
3191 Inc(wwc);
3192 end;
3194 // exclude currently selected weapon from the set
3195 wantThisWeapon[FCurrWeap] := false;
3196 // slow down alterations a little
3197 if wwc > 1 then
3198 begin
3199 //e_WriteLog(Format(' FNextWeap=%x; delay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3200 // more than one weapon requested, assume "alteration" and check alteration delay
3201 if FNextWeapDelay > 0 then
3202 begin
3203 FNextWeap := 0;
3204 exit;
3205 end; // yeah
3206 end;
3207 // do not reset weapon queue, it will be done in `RealizeCurrentWeapon()`
3208 // but clear all counters if no weapon should be switched
3209 if wwc < 1 then
3210 begin
3211 resetWeaponQueue();
3212 exit;
3213 end;
3214 //e_WriteLog(Format('wwc=%d', [wwc]), MSG_WARNING);
3215 // try weapons in descending order
3216 for i := High(FWeapon) downto 0 do
3217 begin
3218 if wantThisWeapon[i] and FWeapon[i] and ((wwc = 1) or hasAmmoForWeapon(i)) then
3219 begin
3220 // i found her!
3221 result := Byte(i);
3222 resetWeaponQueue();
3223 FNextWeapDelay := WEAPON_DELAY * 2; // anyway, 'cause why not
3224 //e_LogWriteFln('FOUND %s %s %s', [result, FSwitchToEmpty, hasAmmoForWeapon(i)], TMsgType.Notify);
3225 exit;
3226 end;
3227 end;
3228 // no suitable weapon found, so reset the queue, to avoid accidental "queuing" of weapon w/o ammo
3229 resetWeaponQueue();
3230 end;
3232 procedure TPlayer.RealizeCurrentWeapon();
3233 function switchAllowed (): Boolean;
3234 var
3235 i: Byte;
3236 begin
3237 result := false;
3238 if FBFGFireCounter <> -1 then
3239 exit;
3240 if FTime[T_SWITCH] > gTime then
3241 exit;
3242 for i := WP_FIRST to WP_LAST do
3243 if FReloading[i] > 0 then
3244 exit;
3245 result := true;
3246 end;
3248 var
3249 nw: Byte;
3250 begin
3251 //e_WriteLog(Format('***RealizeCurrentWeapon: FNextWeap=%x; FNextWeapDelay=%d', [FNextWeap, FNextWeapDelay]), MSG_WARNING);
3252 //FNextWeap := FNextWeap and $1FFF;
3253 if FNextWeapDelay > 0 then Dec(FNextWeapDelay); // "alteration delay"
3255 if not switchAllowed then
3256 begin
3257 //HACK for weapon cycling
3258 if (FNextWeap and $E000) <> 0 then FNextWeap := 0;
3259 exit;
3260 end;
3262 nw := getNextWeaponIndex();
3263 //
3264 if nw = 255 then exit; // don't reset anything here
3265 if nw > High(FWeapon) then
3266 begin
3267 // don't forget to reset queue here!
3268 //e_WriteLog(' RealizeCurrentWeapon: WUTAFUUUU', MSG_WARNING);
3269 resetWeaponQueue();
3270 exit;
3271 end;
3273 if FWeapon[nw] then
3274 begin
3275 FCurrWeap := nw;
3276 FTime[T_SWITCH] := gTime+156;
3277 if FCurrWeap = WEAPON_SAW then FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3278 FModel.SetWeapon(FCurrWeap);
3279 if g_Game_IsNet then MH_SEND_PlayerStats(FUID);
3280 end;
3281 end;
3283 procedure TPlayer.NextWeapon();
3284 begin
3285 if g_Game_IsClient then Exit;
3286 FNextWeap := $8000;
3287 end;
3289 procedure TPlayer.PrevWeapon();
3290 begin
3291 if g_Game_IsClient then Exit;
3292 FNextWeap := $4000;
3293 end;
3295 procedure TPlayer.SetWeapon(W: Byte);
3296 begin
3297 if FCurrWeap <> W then
3298 if W = WEAPON_SAW then
3299 FSawSoundSelect.PlayAt(FObj.X, FObj.Y);
3301 FCurrWeap := W;
3302 FModel.SetWeapon(CurrWeap);
3303 resetWeaponQueue();
3304 end;
3306 function TPlayer.PickItem(ItemType: Byte; arespawn: Boolean; var remove: Boolean): Boolean;
3307 var
3308 a: Boolean;
3309 switchWeapon: Byte = 255;
3310 hadWeapon: Boolean = False;
3311 begin
3312 Result := False;
3313 if g_Game_IsClient then Exit;
3315 // a = true - место спавна предмета:
3316 a := LongBool(gGameSettings.Options and GAME_OPTION_WEAPONSTAY) and arespawn;
3317 remove := not a;
3318 case ItemType of
3319 ITEM_MEDKIT_SMALL:
3320 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3321 begin
3322 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
3323 Result := True;
3324 remove := True;
3325 FFireTime := 0;
3326 if gFlash = 2 then Inc(FPickup, 5);
3327 end;
3329 ITEM_MEDKIT_LARGE:
3330 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3331 begin
3332 if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
3333 Result := True;
3334 remove := True;
3335 FFireTime := 0;
3336 if gFlash = 2 then Inc(FPickup, 5);
3337 end;
3339 ITEM_ARMOR_GREEN:
3340 if FArmor < PLAYER_AP_SOFT then
3341 begin
3342 FArmor := PLAYER_AP_SOFT;
3343 Result := True;
3344 remove := True;
3345 if gFlash = 2 then Inc(FPickup, 5);
3346 end;
3348 ITEM_ARMOR_BLUE:
3349 if FArmor < PLAYER_AP_LIMIT then
3350 begin
3351 FArmor := PLAYER_AP_LIMIT;
3352 Result := True;
3353 remove := True;
3354 if gFlash = 2 then Inc(FPickup, 5);
3355 end;
3357 ITEM_SPHERE_BLUE:
3358 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3359 begin
3360 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
3361 Result := True;
3362 remove := True;
3363 FFireTime := 0;
3364 if gFlash = 2 then Inc(FPickup, 5);
3365 end;
3367 ITEM_SPHERE_WHITE:
3368 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) or (FFireTime > 0) then
3369 begin
3370 if FHealth < PLAYER_HP_LIMIT then
3371 FHealth := PLAYER_HP_LIMIT;
3372 if FArmor < PLAYER_AP_LIMIT then
3373 FArmor := PLAYER_AP_LIMIT;
3374 Result := True;
3375 remove := True;
3376 FFireTime := 0;
3377 if gFlash = 2 then Inc(FPickup, 5);
3378 end;
3380 ITEM_WEAPON_SAW:
3381 if (not FWeapon[WEAPON_SAW]) or ((not arespawn) and (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) then
3382 begin
3383 hadWeapon := FWeapon[WEAPON_SAW];
3384 switchWeapon := WEAPON_SAW;
3385 FWeapon[WEAPON_SAW] := 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_SHOTGUN1:
3392 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN1] then
3393 begin
3394 // Нужно, чтобы не взять все пули сразу:
3395 if a and FWeapon[WEAPON_SHOTGUN1] then Exit;
3396 hadWeapon := FWeapon[WEAPON_SHOTGUN1];
3397 switchWeapon := WEAPON_SHOTGUN1;
3398 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3399 FWeapon[WEAPON_SHOTGUN1] := True;
3400 Result := True;
3401 if gFlash = 2 then Inc(FPickup, 5);
3402 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3403 end;
3405 ITEM_WEAPON_SHOTGUN2:
3406 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SHOTGUN2] then
3407 begin
3408 if a and FWeapon[WEAPON_SHOTGUN2] then Exit;
3409 hadWeapon := FWeapon[WEAPON_SHOTGUN2];
3410 switchWeapon := WEAPON_SHOTGUN2;
3411 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3412 FWeapon[WEAPON_SHOTGUN2] := True;
3413 Result := True;
3414 if gFlash = 2 then Inc(FPickup, 5);
3415 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3416 end;
3418 ITEM_WEAPON_CHAINGUN:
3419 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or not FWeapon[WEAPON_CHAINGUN] then
3420 begin
3421 if a and FWeapon[WEAPON_CHAINGUN] then Exit;
3422 hadWeapon := FWeapon[WEAPON_CHAINGUN];
3423 switchWeapon := WEAPON_CHAINGUN;
3424 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3425 FWeapon[WEAPON_CHAINGUN] := True;
3426 Result := True;
3427 if gFlash = 2 then Inc(FPickup, 5);
3428 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3429 end;
3431 ITEM_WEAPON_ROCKETLAUNCHER:
3432 if (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or not FWeapon[WEAPON_ROCKETLAUNCHER] then
3433 begin
3434 if a and FWeapon[WEAPON_ROCKETLAUNCHER] then Exit;
3435 switchWeapon := WEAPON_ROCKETLAUNCHER;
3436 hadWeapon := FWeapon[WEAPON_ROCKETLAUNCHER];
3437 IncMax(FAmmo[A_ROCKETS], 2, FMaxAmmo[A_ROCKETS]);
3438 FWeapon[WEAPON_ROCKETLAUNCHER] := True;
3439 Result := True;
3440 if gFlash = 2 then Inc(FPickup, 5);
3441 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3442 end;
3444 ITEM_WEAPON_PLASMA:
3445 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_PLASMA] then
3446 begin
3447 if a and FWeapon[WEAPON_PLASMA] then Exit;
3448 switchWeapon := WEAPON_PLASMA;
3449 hadWeapon := FWeapon[WEAPON_PLASMA];
3450 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3451 FWeapon[WEAPON_PLASMA] := True;
3452 Result := True;
3453 if gFlash = 2 then Inc(FPickup, 5);
3454 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3455 end;
3457 ITEM_WEAPON_BFG:
3458 if (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or not FWeapon[WEAPON_BFG] then
3459 begin
3460 if a and FWeapon[WEAPON_BFG] then Exit;
3461 switchWeapon := WEAPON_BFG;
3462 hadWeapon := FWeapon[WEAPON_BFG];
3463 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3464 FWeapon[WEAPON_BFG] := True;
3465 Result := True;
3466 if gFlash = 2 then Inc(FPickup, 5);
3467 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3468 end;
3470 ITEM_WEAPON_SUPERPULEMET:
3471 if (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or not FWeapon[WEAPON_SUPERPULEMET] then
3472 begin
3473 if a and FWeapon[WEAPON_SUPERPULEMET] then Exit;
3474 switchWeapon := WEAPON_SUPERPULEMET;
3475 hadWeapon := FWeapon[WEAPON_SUPERPULEMET];
3476 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3477 FWeapon[WEAPON_SUPERPULEMET] := True;
3478 Result := True;
3479 if gFlash = 2 then Inc(FPickup, 5);
3480 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3481 end;
3483 ITEM_WEAPON_FLAMETHROWER:
3484 if (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) or not FWeapon[WEAPON_FLAMETHROWER] then
3485 begin
3486 if a and FWeapon[WEAPON_FLAMETHROWER] then Exit;
3487 switchWeapon := WEAPON_FLAMETHROWER;
3488 hadWeapon := FWeapon[WEAPON_FLAMETHROWER];
3489 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3490 FWeapon[WEAPON_FLAMETHROWER] := True;
3491 Result := True;
3492 if gFlash = 2 then Inc(FPickup, 5);
3493 if a and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETWEAPON');
3494 end;
3496 ITEM_AMMO_BULLETS:
3497 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3498 begin
3499 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3500 Result := True;
3501 remove := True;
3502 if gFlash = 2 then Inc(FPickup, 5);
3503 end;
3505 ITEM_AMMO_BULLETS_BOX:
3506 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3507 begin
3508 IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
3509 Result := True;
3510 remove := True;
3511 if gFlash = 2 then Inc(FPickup, 5);
3512 end;
3514 ITEM_AMMO_SHELLS:
3515 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3516 begin
3517 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3518 Result := True;
3519 remove := True;
3520 if gFlash = 2 then Inc(FPickup, 5);
3521 end;
3523 ITEM_AMMO_SHELLS_BOX:
3524 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3525 begin
3526 IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
3527 Result := True;
3528 remove := True;
3529 if gFlash = 2 then Inc(FPickup, 5);
3530 end;
3532 ITEM_AMMO_ROCKET:
3533 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3534 begin
3535 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3536 Result := True;
3537 remove := True;
3538 if gFlash = 2 then Inc(FPickup, 5);
3539 end;
3541 ITEM_AMMO_ROCKET_BOX:
3542 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3543 begin
3544 IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
3545 Result := True;
3546 remove := True;
3547 if gFlash = 2 then Inc(FPickup, 5);
3548 end;
3550 ITEM_AMMO_CELL:
3551 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3552 begin
3553 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3554 Result := True;
3555 remove := True;
3556 if gFlash = 2 then Inc(FPickup, 5);
3557 end;
3559 ITEM_AMMO_CELL_BIG:
3560 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3561 begin
3562 IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
3563 Result := True;
3564 remove := True;
3565 if gFlash = 2 then Inc(FPickup, 5);
3566 end;
3568 ITEM_AMMO_FUELCAN:
3569 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3570 begin
3571 IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
3572 Result := True;
3573 remove := True;
3574 if gFlash = 2 then Inc(FPickup, 5);
3575 end;
3577 ITEM_AMMO_BACKPACK:
3578 if not(R_ITEM_BACKPACK in FRulez) or
3579 (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
3580 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
3581 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
3582 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
3583 (FAmmo[A_FUEL] < FMaxAmmo[A_FUEL]) then
3584 begin
3585 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
3586 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
3587 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
3588 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
3589 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
3591 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then
3592 IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
3593 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then
3594 IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
3595 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then
3596 IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
3597 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then
3598 IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
3599 if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then
3600 IncMax(FAmmo[A_FUEL], 50, FMaxAmmo[A_FUEL]);
3602 FRulez := FRulez + [R_ITEM_BACKPACK];
3603 Result := True;
3604 remove := True;
3605 if gFlash = 2 then Inc(FPickup, 5);
3606 end;
3608 ITEM_KEY_RED:
3609 if not(R_KEY_RED in FRulez) then
3610 begin
3611 Include(FRulez, R_KEY_RED);
3612 Result := True;
3613 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3614 if gFlash = 2 then Inc(FPickup, 5);
3615 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3616 end;
3618 ITEM_KEY_GREEN:
3619 if not(R_KEY_GREEN in FRulez) then
3620 begin
3621 Include(FRulez, R_KEY_GREEN);
3622 Result := True;
3623 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3624 if gFlash = 2 then Inc(FPickup, 5);
3625 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3626 end;
3628 ITEM_KEY_BLUE:
3629 if not(R_KEY_BLUE in FRulez) then
3630 begin
3631 Include(FRulez, R_KEY_BLUE);
3632 Result := True;
3633 remove := (gGameSettings.GameMode <> GM_COOP) and (g_Player_GetCount() < 2);
3634 if gFlash = 2 then Inc(FPickup, 5);
3635 if (not remove) and g_Game_IsNet then MH_SEND_Sound(GameX, GameY, 'SOUND_ITEM_GETITEM');
3636 end;
3638 ITEM_SUIT:
3639 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
3640 begin
3641 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
3642 Result := True;
3643 remove := True;
3644 FFireTime := 0;
3645 if gFlash = 2 then Inc(FPickup, 5);
3646 end;
3648 ITEM_OXYGEN:
3649 if FAir < AIR_MAX then
3650 begin
3651 FAir := AIR_MAX;
3652 Result := True;
3653 remove := True;
3654 if gFlash = 2 then Inc(FPickup, 5);
3655 end;
3657 ITEM_MEDKIT_BLACK:
3658 begin
3659 if not (R_BERSERK in FRulez) then
3660 begin
3661 Include(FRulez, R_BERSERK);
3662 if (FBFGFireCounter = -1) then
3663 begin
3664 FCurrWeap := WEAPON_KASTET;
3665 resetWeaponQueue();
3666 FModel.SetWeapon(WEAPON_KASTET);
3667 end;
3668 if gFlash <> 0 then
3669 begin
3670 Inc(FPain, 100);
3671 if gFlash = 2 then Inc(FPickup, 5);
3672 end;
3673 FBerserk := gTime+30000;
3674 Result := True;
3675 remove := True;
3676 FFireTime := 0;
3677 end;
3678 if (FHealth < PLAYER_HP_SOFT) or (FFireTime > 0) then
3679 begin
3680 if FHealth < PLAYER_HP_SOFT then FHealth := PLAYER_HP_SOFT;
3681 FBerserk := gTime+30000;
3682 Result := True;
3683 remove := True;
3684 FFireTime := 0;
3685 end;
3686 end;
3688 ITEM_INVUL:
3689 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
3690 begin
3691 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
3692 FSpawnInvul := 0;
3693 Result := True;
3694 remove := True;
3695 if gFlash = 2 then Inc(FPickup, 5);
3696 end;
3698 ITEM_BOTTLE:
3699 if (FHealth < PLAYER_HP_LIMIT) or (FFireTime > 0) then
3700 begin
3701 if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
3702 Result := True;
3703 remove := True;
3704 FFireTime := 0;
3705 if gFlash = 2 then Inc(FPickup, 5);
3706 end;
3708 ITEM_HELMET:
3709 if FArmor < PLAYER_AP_LIMIT then
3710 begin
3711 IncMax(FArmor, 5, PLAYER_AP_LIMIT);
3712 Result := True;
3713 remove := True;
3714 if gFlash = 2 then Inc(FPickup, 5);
3715 end;
3717 ITEM_JETPACK:
3718 if FJetFuel < JET_MAX then
3719 begin
3720 FJetFuel := JET_MAX;
3721 Result := True;
3722 remove := True;
3723 if gFlash = 2 then Inc(FPickup, 5);
3724 end;
3726 ITEM_INVIS:
3727 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
3728 begin
3729 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
3730 Result := True;
3731 remove := True;
3732 if gFlash = 2 then Inc(FPickup, 5);
3733 end;
3734 end;
3736 if (shouldSwitch(switchWeapon, hadWeapon)) then
3737 QueueWeaponSwitch(switchWeapon);
3738 end;
3740 procedure TPlayer.Touch();
3741 begin
3742 if not FAlive then
3743 Exit;
3744 //FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
3745 if FIamBot then
3746 begin
3747 // Бросить флаг товарищу:
3748 if gGameSettings.GameMode = GM_CTF then
3749 DropFlag();
3750 end;
3751 end;
3753 procedure TPlayer.Push(vx, vy: Integer);
3754 begin
3755 if (not FPhysics) and FGhost then
3756 Exit;
3757 FObj.Accel.X := FObj.Accel.X + vx;
3758 FObj.Accel.Y := FObj.Accel.Y + vy;
3759 if g_Game_IsNet and g_Game_IsServer then
3760 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
3761 end;
3763 procedure TPlayer.Reset(Force: Boolean);
3764 begin
3765 if Force then
3766 FAlive := False;
3768 FSpawned := False;
3769 FTime[T_RESPAWN] := 0;
3770 FTime[T_FLAGCAP] := 0;
3771 FGodMode := False;
3772 FNoTarget := False;
3773 FNoReload := False;
3774 FFrags := 0;
3775 FLastFrag := 0;
3776 FComboEvnt := -1;
3777 FKills := 0;
3778 FMonsterKills := 0;
3779 FDeath := 0;
3780 FSecrets := 0;
3781 FSpawnInvul := 0;
3782 FCorpse := -1;
3783 FReady := False;
3784 if FNoRespawn then
3785 begin
3786 FSpectator := False;
3787 FGhost := False;
3788 FPhysics := True;
3789 FSpectatePlayer := -1;
3790 FNoRespawn := False;
3791 end;
3792 FLives := gGameSettings.MaxLives;
3794 SetFlag(FLAG_NONE);
3795 end;
3797 procedure TPlayer.SoftReset();
3798 begin
3799 ReleaseKeys();
3801 FDamageBuffer := 0;
3802 FSlopeOld := 0;
3803 FIncCamOld := 0;
3804 FIncCam := 0;
3805 FBFGFireCounter := -1;
3806 FShellTimer := -1;
3807 FPain := 0;
3808 FLastHit := 0;
3809 FLastFrag := 0;
3810 FComboEvnt := -1;
3812 SetFlag(FLAG_NONE);
3813 SetAction(A_STAND, True);
3814 end;
3816 function TPlayer.GetRespawnPoint(): Byte;
3817 var
3818 c: Byte;
3819 begin
3820 Result := 255;
3821 // На будущее: FSpawn - игрок уже играл и перерождается
3823 // Одиночная игра/кооператив
3824 if gGameSettings.GameMode in [GM_COOP, GM_SINGLE] then
3825 begin
3826 if Self = gPlayer1 then
3827 begin
3828 // player 1 should try to spawn on the player 1 point
3829 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3830 Exit(RESPAWNPOINT_PLAYER1)
3831 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3832 Exit(RESPAWNPOINT_PLAYER2);
3833 end
3834 else if Self = gPlayer2 then
3835 begin
3836 // player 2 should try to spawn on the player 2 point
3837 if g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) > 0 then
3838 Exit(RESPAWNPOINT_PLAYER2)
3839 else if g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) > 0 then
3840 Exit(RESPAWNPOINT_PLAYER1);
3841 end
3842 else
3843 begin
3844 // other players randomly pick either the first or the second point
3845 c := IfThen((Random(2) = 0), RESPAWNPOINT_PLAYER1, RESPAWNPOINT_PLAYER2);
3846 if g_Map_GetPointCount(c) > 0 then
3847 Exit(c);
3848 // try the other one
3849 c := IfThen((c = RESPAWNPOINT_PLAYER1), RESPAWNPOINT_PLAYER2, RESPAWNPOINT_PLAYER1);
3850 if g_Map_GetPointCount(c) > 0 then
3851 Exit(c);
3852 end;
3853 end;
3855 // Мясоповал
3856 if gGameSettings.GameMode = GM_DM then
3857 begin
3858 // try DM points first
3859 if g_Map_GetPointCount(RESPAWNPOINT_DM) > 0 then
3860 Exit(RESPAWNPOINT_DM);
3861 end;
3863 // Командные
3864 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3865 begin
3866 // try team points first
3867 c := RESPAWNPOINT_DM;
3868 if FTeam = TEAM_RED then
3869 c := RESPAWNPOINT_RED
3870 else if FTeam = TEAM_BLUE then
3871 c := RESPAWNPOINT_BLUE;
3872 if g_Map_GetPointCount(c) > 0 then
3873 Exit(c);
3874 end;
3876 // still haven't found a spawnpoint, try random shit
3877 Result := g_Map_GetRandomPointType();
3878 end;
3880 procedure TPlayer.Respawn(Silent: Boolean; Force: Boolean = False);
3881 var
3882 RespawnPoint: TRespawnPoint;
3883 a, b, c: Byte;
3884 begin
3885 FSlopeOld := 0;
3886 FIncCamOld := 0;
3887 FIncCam := 0;
3888 FBFGFireCounter := -1;
3889 FShellTimer := -1;
3890 FPain := 0;
3891 FLastHit := 0;
3892 FSpawnInvul := 0;
3893 FCorpse := -1;
3895 if not g_Game_IsServer then
3896 Exit;
3897 if FDummy then
3898 Exit;
3899 FWantsInGame := True;
3900 FJustTeleported := True;
3901 if Force then
3902 begin
3903 FTime[T_RESPAWN] := 0;
3904 FAlive := False;
3905 end;
3906 FNetTime := 0;
3907 // if server changes MaxLives we gotta be ready
3908 if gGameSettings.MaxLives = 0 then FNoRespawn := False;
3910 // Еще нельзя возродиться:
3911 if FTime[T_RESPAWN] > gTime then
3912 Exit;
3914 // Просрал все жизни:
3915 if FNoRespawn then
3916 begin
3917 if not FSpectator then Spectate(True);
3918 FWantsInGame := True;
3919 Exit;
3920 end;
3922 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.GameMode <> GM_COOP) then
3923 begin // "Своя игра"
3924 // Берсерк не сохраняется между уровнями:
3925 FRulez := FRulez-[R_BERSERK];
3926 end
3927 else // "Одиночная игра"/"Кооп"
3928 begin
3929 // Берсерк и ключи не сохраняются между уровнями:
3930 FRulez := FRulez-[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE, R_BERSERK];
3931 end;
3933 // Получаем точку спауна игрока:
3934 c := GetRespawnPoint();
3936 ReleaseKeys();
3937 SetFlag(FLAG_NONE);
3939 // Воскрешение без оружия:
3940 if not FAlive then
3941 begin
3942 FHealth := Round(PLAYER_HP_SOFT * (FHandicap / 100));
3943 FArmor := 0;
3944 FAlive := True;
3945 FAir := AIR_DEF;
3946 FJetFuel := 0;
3948 for a := WP_FIRST to WP_LAST do
3949 begin
3950 FWeapon[a] := False;
3951 FReloading[a] := 0;
3952 end;
3954 FWeapon[WEAPON_PISTOL] := True;
3955 FWeapon[WEAPON_KASTET] := True;
3956 FCurrWeap := WEAPON_PISTOL;
3957 resetWeaponQueue();
3959 FModel.SetWeapon(FCurrWeap);
3961 for b := A_BULLETS to A_HIGH do
3962 FAmmo[b] := 0;
3964 FAmmo[A_BULLETS] := 50;
3966 FMaxAmmo[A_BULLETS] := AmmoLimits[0, A_BULLETS];
3967 FMaxAmmo[A_SHELLS] := AmmoLimits[0, A_SHELLS];
3968 FMaxAmmo[A_ROCKETS] := AmmoLimits[0, A_SHELLS];
3969 FMaxAmmo[A_CELLS] := AmmoLimits[0, A_CELLS];
3970 FMaxAmmo[A_FUEL] := AmmoLimits[0, A_FUEL];
3972 if (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) and
3973 LongBool(gGameSettings.Options and GAME_OPTION_DMKEYS) then
3974 FRulez := [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE]
3975 else
3976 FRulez := [];
3977 end;
3979 // Получаем координаты точки возрождения:
3980 if not g_Map_GetPoint(c, RespawnPoint) then
3981 begin
3982 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3983 Exit;
3984 end;
3986 // Установка координат и сброс всех параметров:
3987 FObj.X := RespawnPoint.X-PLAYER_RECT.X;
3988 FObj.Y := RespawnPoint.Y-PLAYER_RECT.Y;
3989 FObj.oldX := FObj.X; // don't interpolate after respawn
3990 FObj.oldY := FObj.Y;
3991 FObj.Vel.X := 0;
3992 FObj.Vel.Y := 0;
3993 FObj.Accel.X := 0;
3994 FObj.Accel.Y := 0;
3996 FDirection := RespawnPoint.Direction;
3997 if FDirection = TDirection.D_LEFT then
3998 FAngle := 180
3999 else
4000 FAngle := 0;
4002 SetAction(A_STAND, True);
4003 FModel.Direction := FDirection;
4005 for a := Low(FTime) to High(FTime) do
4006 FTime[a] := 0;
4008 for a := Low(FMegaRulez) to High(FMegaRulez) do
4009 FMegaRulez[a] := 0;
4011 // Respawn invulnerability
4012 if (gGameSettings.GameType <> GT_SINGLE) and (gGameSettings.SpawnInvul > 0) then
4013 begin
4014 FMegaRulez[MR_INVUL] := gTime + gGameSettings.SpawnInvul * 1000;
4015 FSpawnInvul := FMegaRulez[MR_INVUL];
4016 end;
4018 FDamageBuffer := 0;
4019 FJetpack := False;
4020 FCanJetpack := False;
4021 FFlaming := False;
4022 FFireTime := 0;
4023 FFirePainTime := 0;
4024 FFireAttacker := 0;
4026 // Анимация возрождения:
4027 if (not gLoadGameMode) and (not Silent) then
4028 r_GFX_OnceAnim(
4029 R_GFX_TELEPORT_FAST,
4030 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4031 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4032 );
4034 FSpectator := False;
4035 FGhost := False;
4036 FPhysics := True;
4037 FSpectatePlayer := -1;
4038 FSpawned := True;
4040 if (gPlayer1 = nil) and (gSpectLatchPID1 = FUID) then
4041 gPlayer1 := self;
4042 if (gPlayer2 = nil) and (gSpectLatchPID2 = FUID) then
4043 gPlayer2 := self;
4045 if g_Game_IsNet then
4046 begin
4047 MH_SEND_PlayerPos(True, FUID, NET_EVERYONE);
4048 MH_SEND_PlayerStats(FUID, NET_EVERYONE);
4049 if not Silent then
4050 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4051 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32,
4052 0, NET_GFX_TELE);
4053 end;
4054 end;
4056 procedure TPlayer.Spectate(NoMove: Boolean = False);
4057 begin
4058 if FAlive then
4059 Kill(K_EXTRAHARDKILL, FUID, HIT_SOME)
4060 else if (not NoMove) then
4061 begin
4062 GameX := gMapInfo.Width div 2;
4063 GameY := gMapInfo.Height div 2;
4064 end;
4065 FXTo := GameX;
4066 FYTo := GameY;
4068 FAlive := False;
4069 FSpectator := True;
4070 FGhost := True;
4071 FPhysics := False;
4072 FWantsInGame := False;
4073 FSpawned := False;
4074 FCorpse := -1;
4076 if FNoRespawn then
4077 begin
4078 if Self = gPlayer1 then
4079 begin
4080 gSpectLatchPID1 := FUID;
4081 gPlayer1 := nil;
4082 end
4083 else if Self = gPlayer2 then
4084 begin
4085 gSpectLatchPID2 := FUID;
4086 gPlayer2 := nil;
4087 end;
4088 end;
4090 if g_Game_IsNet then
4091 MH_SEND_PlayerStats(FUID);
4092 end;
4094 procedure TPlayer.SwitchNoClip;
4095 begin
4096 if not FAlive then
4097 Exit;
4098 FGhost := not FGhost;
4099 FPhysics := not FGhost;
4100 if FGhost then
4101 begin
4102 FXTo := FObj.X;
4103 FYTo := FObj.Y;
4104 end else
4105 begin
4106 FObj.Accel.X := 0;
4107 FObj.Accel.Y := 0;
4108 end;
4109 end;
4111 procedure TPlayer.Run(Direction: TDirection);
4112 var
4113 a, b: Integer;
4114 begin
4115 if MAX_RUNVEL > 8 then
4116 FlySmoke();
4118 // Бежим:
4119 if Direction = TDirection.D_LEFT then
4120 begin
4121 if FObj.Vel.X > -MAX_RUNVEL then
4122 FObj.Vel.X := FObj.Vel.X - (MAX_RUNVEL shr 3);
4123 end
4124 else
4125 if FObj.Vel.X < MAX_RUNVEL then
4126 FObj.Vel.X := FObj.Vel.X + (MAX_RUNVEL shr 3);
4128 // Возможно, пинаем куски:
4129 if (FObj.Vel.X <> 0) and (gGibs <> nil) then
4130 begin
4131 b := Abs(FObj.Vel.X);
4132 if b > 1 then b := b * (Random(8 div b) + 1);
4133 for a := 0 to High(gGibs) do
4134 begin
4135 if gGibs[a].alive and
4136 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
4137 FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
4138 begin
4139 // Пинаем куски
4140 if FObj.Vel.X < 0 then
4141 begin
4142 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)+120) // налево
4143 end
4144 else
4145 begin
4146 g_Obj_PushA(@gGibs[a].Obj, b, Random(61)); // направо
4147 end;
4148 gGibs[a].positionChanged(); // this updates spatial accelerators
4149 end;
4150 end;
4151 end;
4153 SetAction(A_WALK);
4154 end;
4156 procedure TPlayer.SeeDown();
4157 begin
4158 SetAction(A_SEEDOWN);
4160 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTDOWN else FAngle := ANGLE_RIGHTDOWN;
4162 if FIncCam > -120 then DecMin(FIncCam, 5, -120);
4163 end;
4165 procedure TPlayer.SeeUp();
4166 begin
4167 SetAction(A_SEEUP);
4169 if FDirection = TDirection.D_LEFT then FAngle := ANGLE_LEFTUP else FAngle := ANGLE_RIGHTUP;
4171 if FIncCam < 120 then IncMax(FIncCam, 5, 120);
4172 end;
4174 procedure TPlayer.SetAction(Action: Byte; Force: Boolean = False);
4175 var
4176 Prior: Byte;
4177 begin
4178 case Action of
4179 A_WALK: Prior := 3;
4180 A_DIE1: Prior := 5;
4181 A_DIE2: Prior := 5;
4182 A_ATTACK: Prior := 2;
4183 A_SEEUP: Prior := 1;
4184 A_SEEDOWN: Prior := 1;
4185 A_ATTACKUP: Prior := 2;
4186 A_ATTACKDOWN: Prior := 2;
4187 A_PAIN: Prior := 4;
4188 else Prior := 0;
4189 end;
4191 if (Prior > FActionPrior) or Force then
4192 if not ((Prior = 2) and (FCurrWeap = WEAPON_SAW)) then
4193 begin
4194 FActionPrior := Prior;
4195 FActionAnim := Action;
4196 FActionForce := Force;
4197 FActionChanged := True;
4198 end;
4200 if Action in [A_ATTACK, A_ATTACKUP, A_ATTACKDOWN] then FModel.SetFire(True);
4201 end;
4203 function TPlayer.StayOnStep(XInc, YInc: Integer): Boolean;
4204 begin
4205 Result := not g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height-1,
4206 PLAYER_RECT.Width, 1, PANEL_STEP, False)
4207 and g_Map_CollidePanel(FObj.X+PLAYER_RECT.X, FObj.Y+YInc+PLAYER_RECT.Y+PLAYER_RECT.Height,
4208 PLAYER_RECT.Width, 1, PANEL_STEP, False);
4209 end;
4211 function TPlayer.TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
4212 begin
4213 Result := False;
4215 if g_CollideLevel(X, Y, PLAYER_RECT.Width, PLAYER_RECT.Height) then
4216 begin
4217 g_Sound_PlayExAt('SOUND_GAME_NOTELEPORT', FObj.X, FObj.Y);
4218 if g_Game_IsServer and g_Game_IsNet then
4219 MH_SEND_Sound(FObj.X, FObj.Y, 'SOUND_GAME_NOTELEPORT');
4220 Exit;
4221 end;
4223 FJustTeleported := True;
4225 if not silent then
4226 begin
4227 g_Sound_PlayExAt('SOUND_GAME_TELEPORT', FObj.X, FObj.Y);
4228 r_GFX_OnceAnim(
4229 R_GFX_TELEPORT_FAST,
4230 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4231 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4232 );
4233 if g_Game_IsServer and g_Game_IsNet then
4234 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4235 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 1,
4236 NET_GFX_TELE);
4237 end;
4239 FObj.X := X-PLAYER_RECT.X;
4240 FObj.Y := Y-PLAYER_RECT.Y;
4241 FObj.oldX := FObj.X; // don't interpolate after respawn
4242 FObj.oldY := FObj.Y;
4243 if FAlive and FGhost then
4244 begin
4245 FXTo := FObj.X;
4246 FYTo := FObj.Y;
4247 end;
4249 if not g_Game_IsNet then
4250 begin
4251 if dir = 1 then
4252 begin
4253 SetDirection(TDirection.D_LEFT);
4254 FAngle := 180;
4255 end
4256 else
4257 if dir = 2 then
4258 begin
4259 SetDirection(TDirection.D_RIGHT);
4260 FAngle := 0;
4261 end
4262 else
4263 if dir = 3 then
4264 begin // обратное
4265 if FDirection = TDirection.D_RIGHT then
4266 begin
4267 SetDirection(TDirection.D_LEFT);
4268 FAngle := 180;
4269 end
4270 else
4271 begin
4272 SetDirection(TDirection.D_RIGHT);
4273 FAngle := 0;
4274 end;
4275 end;
4276 end;
4278 if not silent then
4279 begin
4280 r_GFX_OnceAnim(
4281 R_GFX_TELEPORT_FAST,
4282 FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4283 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32
4284 );
4285 if g_Game_IsServer and g_Game_IsNet then
4286 MH_SEND_Effect(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2)-32,
4287 FObj.Y+PLAYER_RECT.Y+(PLAYER_RECT.Height div 2)-32, 0,
4288 NET_GFX_TELE);
4289 end;
4291 Result := True;
4292 end;
4294 function nonz(a: Single): Single;
4295 begin
4296 if a <> 0 then
4297 Result := a
4298 else
4299 Result := 1;
4300 end;
4302 function TPlayer.refreshCorpse(): Boolean;
4303 var
4304 i: Integer;
4305 begin
4306 Result := False;
4307 FCorpse := -1;
4308 if FAlive or FSpectator then
4309 Exit;
4310 if (gCorpses = nil) or (Length(gCorpses) = 0) then
4311 Exit;
4312 for i := 0 to High(gCorpses) do
4313 if gCorpses[i] <> nil then
4314 if gCorpses[i].FPlayerUID = FUID then
4315 begin
4316 Result := True;
4317 FCorpse := i;
4318 break;
4319 end;
4320 end;
4322 function TPlayer.getCameraObj(): TObj;
4323 begin
4324 if (not FAlive) and (not FSpectator) and
4325 (FCorpse >= 0) and (FCorpse < Length(gCorpses)) and
4326 (gCorpses[FCorpse] <> nil) and (gCorpses[FCorpse].FPlayerUID = FUID) then
4327 begin
4328 gCorpses[FCorpse].FObj.slopeUpLeft := FObj.slopeUpLeft;
4329 Result := gCorpses[FCorpse].FObj;
4330 end
4331 else
4332 begin
4333 Result := FObj;
4334 end;
4335 end;
4337 procedure TPlayer.PreUpdate();
4338 begin
4339 FSlopeOld := FObj.slopeUpLeft;
4340 FIncCamOld := FIncCam;
4341 FObj.oldX := FObj.X;
4342 FObj.oldY := FObj.Y;
4343 end;
4345 procedure TPlayer.Update();
4346 var
4347 b: Byte;
4348 i, ii, wx, wy, xd, yd, k: Integer;
4349 blockmon, headwater, dospawn: Boolean;
4350 NetServer: Boolean;
4351 AnyServer: Boolean;
4352 SetSpect: Boolean;
4353 begin
4354 NetServer := g_Game_IsNet and g_Game_IsServer;
4355 AnyServer := g_Game_IsServer;
4357 if g_Game_IsClient and (NetInterpLevel > 0) then
4358 DoLerp(NetInterpLevel + 1)
4359 else
4360 if FGhost then
4361 DoLerp(4);
4363 if NetServer then
4364 if (FClientID >= 0) and (NetClients[FClientID].Peer <> nil) then
4365 begin
4366 FPing := NetClients[FClientID].Peer^.lastRoundTripTime;
4367 if NetClients[FClientID].Peer^.packetsSent > 0 then
4368 FLoss := Round(100*NetClients[FClientID].Peer^.packetsLost/NetClients[FClientID].Peer^.packetsSent)
4369 else
4370 FLoss := 0;
4371 end else
4372 begin
4373 FPing := 0;
4374 FLoss := 0;
4375 end;
4377 if FAlive and (FPunchAnim <> nil) then
4378 FPunchAnim.Update();
4380 if FAlive and (gFly or FJetpack) then
4381 FlySmoke();
4383 if FDirection = TDirection.D_LEFT then
4384 FAngle := 180
4385 else
4386 FAngle := 0;
4388 if FAlive and (not FGhost) then
4389 begin
4390 if FKeys[KEY_UP].Pressed then
4391 SeeUp();
4392 if FKeys[KEY_DOWN].Pressed then
4393 SeeDown();
4394 end;
4396 if (not (FKeys[KEY_UP].Pressed or FKeys[KEY_DOWN].Pressed)) and
4397 (FIncCam <> 0) then
4398 begin
4399 i := g_basic.Sign(FIncCam);
4400 FIncCam := Abs(FIncCam);
4401 DecMin(FIncCam, 5, 0);
4402 FIncCam := FIncCam*i;
4403 end;
4405 if gTime mod (GAME_TICK*2) <> 0 then
4406 begin
4407 if (FObj.Vel.X = 0) and FAlive then
4408 begin
4409 if FKeys[KEY_LEFT].Pressed then
4410 Run(TDirection.D_LEFT);
4411 if FKeys[KEY_RIGHT].Pressed then
4412 Run(TDirection.D_RIGHT);
4413 end;
4415 if FPhysics then
4416 begin
4417 g_Obj_Move(@FObj, True, True, True);
4418 positionChanged(); // this updates spatial accelerators
4419 end;
4421 Exit;
4422 end;
4424 FActionChanged := False;
4426 if FAlive then
4427 begin
4428 // Let alive player do some actions
4429 if FKeys[KEY_LEFT].Pressed then Run(TDirection.D_LEFT);
4430 if FKeys[KEY_RIGHT].Pressed then Run(TDirection.D_RIGHT);
4431 if FKeys[KEY_FIRE].Pressed and AnyServer then Fire()
4432 else
4433 begin
4434 if AnyServer then
4435 begin
4436 FlamerOff;
4437 if NetServer then MH_SEND_PlayerStats(FUID);
4438 end;
4439 end;
4440 if FKeys[KEY_OPEN].Pressed and AnyServer then Use();
4441 if FKeys[KEY_JUMP].Pressed then Jump()
4442 else
4443 begin
4444 if AnyServer and FJetpack then
4445 begin
4446 FJetpack := False;
4447 JetpackOff;
4448 if NetServer then MH_SEND_PlayerStats(FUID);
4449 end;
4450 FCanJetpack := True;
4451 end;
4452 end
4453 else // Dead
4454 begin
4455 dospawn := False;
4456 if not FGhost then
4457 for k := Low(FKeys) to KEY_CHAT-1 do
4458 begin
4459 if FKeys[k].Pressed then
4460 begin
4461 dospawn := True;
4462 break;
4463 end;
4464 end;
4465 if dospawn then
4466 begin
4467 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
4468 Respawn(False)
4469 else // Single
4470 if (FTime[T_RESPAWN] <= gTime) and
4471 gGameOn and (not FAlive) then
4472 begin
4473 if (g_Player_GetCount() > 1) then
4474 Respawn(False)
4475 else
4476 begin
4477 gExit := EXIT_RESTART;
4478 Exit;
4479 end;
4480 end;
4481 end;
4482 // Dead spectator actions
4483 if FGhost then
4484 begin
4485 if FKeys[KEY_OPEN].Pressed and AnyServer then Fire();
4486 if FKeys[KEY_FIRE].Pressed and AnyServer then
4487 begin
4488 if FSpectator then
4489 begin
4490 if (FSpectatePlayer >= High(gPlayers)) then
4491 FSpectatePlayer := -1
4492 else
4493 begin
4494 SetSpect := False;
4495 for I := FSpectatePlayer + 1 to High(gPlayers) do
4496 if gPlayers[I] <> nil then
4497 if gPlayers[I].alive then
4498 if gPlayers[I].UID <> FUID then
4499 begin
4500 FSpectatePlayer := I;
4501 SetSpect := True;
4502 break;
4503 end;
4505 if not SetSpect then FSpectatePlayer := -1;
4506 end;
4508 ReleaseKeys;
4509 end;
4510 end;
4511 end;
4512 end;
4513 // No clipping
4514 if FGhost then
4515 begin
4516 if FKeys[KEY_UP].Pressed or FKeys[KEY_JUMP].Pressed then
4517 begin
4518 FYTo := FObj.Y - 32;
4519 FSpectatePlayer := -1;
4520 end;
4521 if FKeys[KEY_DOWN].Pressed then
4522 begin
4523 FYTo := FObj.Y + 32;
4524 FSpectatePlayer := -1;
4525 end;
4526 if FKeys[KEY_LEFT].Pressed then
4527 begin
4528 FXTo := FObj.X - 32;
4529 FSpectatePlayer := -1;
4530 end;
4531 if FKeys[KEY_RIGHT].Pressed then
4532 begin
4533 FXTo := FObj.X + 32;
4534 FSpectatePlayer := -1;
4535 end;
4537 if (FXTo < -64) then
4538 FXTo := -64
4539 else if (FXTo > gMapInfo.Width + 32) then
4540 FXTo := gMapInfo.Width + 32;
4541 if (FYTo < -72) then
4542 FYTo := -72
4543 else if (FYTo > gMapInfo.Height + 32) then
4544 FYTo := gMapInfo.Height + 32;
4545 end;
4547 if FPhysics then
4548 begin
4549 g_Obj_Move(@FObj, True, True, True);
4550 positionChanged(); // this updates spatial accelerators
4551 end
4552 else
4553 begin
4554 FObj.Vel.X := 0;
4555 FObj.Vel.Y := 0;
4556 if FSpectator then
4557 if (FSpectatePlayer <= High(gPlayers)) and (FSpectatePlayer >= 0) then
4558 if gPlayers[FSpectatePlayer] <> nil then
4559 if gPlayers[FSpectatePlayer].alive then
4560 begin
4561 FXTo := gPlayers[FSpectatePlayer].GameX;
4562 FYTo := gPlayers[FSpectatePlayer].GameY;
4563 end;
4564 end;
4566 blockmon := g_Map_CollidePanel(FObj.X+PLAYER_HEADRECT.X, FObj.Y+PLAYER_HEADRECT.Y,
4567 PLAYER_HEADRECT.Width, PLAYER_HEADRECT.Height,
4568 PANEL_BLOCKMON, True);
4569 headwater := HeadInLiquid(0, 0);
4571 // Сопротивление воздуха:
4572 if (not FAlive) or not (FKeys[KEY_LEFT].Pressed or FKeys[KEY_RIGHT].Pressed) then
4573 if FObj.Vel.X <> 0 then
4574 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
4576 if (FLastHit = HIT_TRAP) and (FPain > 90) then FPain := 90;
4577 DecMin(FPain, 5, 0);
4578 DecMin(FPickup, 1, 0);
4580 if FAlive and (FObj.Y > Integer(gMapInfo.Height)+128) and AnyServer then
4581 begin
4582 // Обнулить действия примочек, чтобы фон пропал
4583 FMegaRulez[MR_SUIT] := 0;
4584 FMegaRulez[MR_INVUL] := 0;
4585 FMegaRulez[MR_INVIS] := 0;
4586 Kill(K_FALLKILL, 0, HIT_FALL);
4587 end;
4589 i := 9;
4591 if FAlive then
4592 begin
4593 if FCurrWeap = WEAPON_SAW then
4594 if not (FSawSound.IsPlaying() or FSawSoundHit.IsPlaying() or
4595 FSawSoundSelect.IsPlaying()) then
4596 FSawSoundIdle.PlayAt(FObj.X, FObj.Y);
4598 if FJetpack then
4599 if (not FJetSoundFly.IsPlaying()) and (not FJetSoundOn.IsPlaying()) and
4600 (not FJetSoundOff.IsPlaying()) then
4601 begin
4602 FJetSoundFly.SetPosition(0);
4603 FJetSoundFly.PlayAt(FObj.X, FObj.Y);
4604 end;
4606 for b := WP_FIRST to WP_LAST do
4607 if FReloading[b] > 0 then
4608 if FNoReload then
4609 FReloading[b] := 0
4610 else
4611 Dec(FReloading[b]);
4613 if FShellTimer > -1 then
4614 if FShellTimer = 0 then
4615 begin
4616 if FShellType = SHELL_SHELL then
4617 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4618 GameVelX, GameVelY-2, SHELL_SHELL)
4619 else if FShellType = SHELL_DBLSHELL then
4620 begin
4621 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4622 GameVelX+1, GameVelY-2, SHELL_SHELL);
4623 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4624 GameVelX-1, GameVelY-2, SHELL_SHELL);
4625 end;
4626 FShellTimer := -1;
4627 end else Dec(FShellTimer);
4629 if (FBFGFireCounter > -1) then
4630 if FBFGFireCounter = 0 then
4631 begin
4632 if AnyServer then
4633 begin
4634 wx := FObj.X+WEAPONPOINT[FDirection].X;
4635 wy := FObj.Y+WEAPONPOINT[FDirection].Y;
4636 xd := wx+IfThen(FDirection = TDirection.D_LEFT, -30, 30);
4637 yd := wy+firediry();
4638 g_Weapon_bfgshot(wx, wy, xd, yd, FUID);
4639 if NetServer then MH_SEND_PlayerFire(FUID, WEAPON_BFG, wx, wy, xd, yd);
4640 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
4641 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
4642 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
4643 end;
4645 FReloading[WEAPON_BFG] := WEAPON_RELOAD[WEAPON_BFG];
4646 FBFGFireCounter := -1;
4647 end else
4648 if FNoReload then
4649 FBFGFireCounter := 0
4650 else
4651 Dec(FBFGFireCounter);
4653 if (FMegaRulez[MR_SUIT] < gTime) and AnyServer then
4654 begin
4655 b := g_GetAcidHit(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width, PLAYER_RECT.Height);
4657 if (b > 0) and (gTime mod (15*GAME_TICK) = 0) then Damage(b, 0, 0, 0, HIT_ACID);
4658 end;
4660 if (headwater or blockmon) then
4661 begin
4662 Dec(FAir);
4664 if FAir < -9 then
4665 begin
4666 if AnyServer then Damage(10, 0, 0, 0, HIT_WATER);
4667 FAir := 0;
4668 end
4669 else if (FAir mod 31 = 0) and not blockmon then
4670 begin
4671 g_GFX_Bubbles(FObj.X+PLAYER_RECT.X+(PLAYER_RECT.Width div 2), FObj.Y+PLAYER_RECT.Y-4, 5+Random(6), 8, 4);
4672 if Random(2) = 0
4673 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
4674 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
4675 end;
4676 end else if FAir < AIR_DEF then
4677 FAir := AIR_DEF;
4679 if FFireTime > 0 then
4680 begin
4681 if BodyInLiquid(0, 0) then
4682 begin
4683 FFireTime := 0;
4684 FFirePainTime := 0;
4685 end
4686 else if FMegaRulez[MR_SUIT] >= gTime then
4687 begin
4688 if FMegaRulez[MR_SUIT] = gTime then
4689 FFireTime := 1;
4690 FFirePainTime := 0;
4691 end
4692 else
4693 begin
4694 OnFireFlame(1);
4695 if FFirePainTime <= 0 then
4696 begin
4697 if g_Game_IsServer then
4698 Damage(2, FFireAttacker, 0, 0, HIT_FLAME);
4699 FFirePainTime := 12 - FFireTime div 12;
4700 end;
4701 FFirePainTime := FFirePainTime - 1;
4702 FFireTime := FFireTime - 1;
4703 if ((FFireTime mod 33) = 0) and (FMegaRulez[MR_INVUL] < gTime) then
4704 FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y);
4705 if (FFireTime = 0) and g_Game_IsNet and g_Game_IsServer then
4706 MH_SEND_PlayerStats(FUID);
4707 end;
4708 end;
4710 if FDamageBuffer > 0 then
4711 begin
4712 if FDamageBuffer >= 9 then
4713 begin
4714 SetAction(A_PAIN);
4716 if FDamageBuffer < 30 then i := 9
4717 else if FDamageBuffer < 100 then i := 18
4718 else i := 27;
4719 end;
4721 ii := Round(FDamageBuffer*FHealth / nonz(FArmor*(3/4)+FHealth));
4722 FArmor := FArmor-(FDamageBuffer-ii);
4723 FHealth := FHealth-ii;
4724 if FArmor < 0 then
4725 begin
4726 FHealth := FHealth+FArmor;
4727 FArmor := 0;
4728 end;
4730 if AnyServer then
4731 if FHealth <= 0 then
4732 if FHealth > -30 then Kill(K_SIMPLEKILL, FLastSpawnerUID, FLastHit)
4733 else if FHealth > -50 then Kill(K_HARDKILL, FLastSpawnerUID, FLastHit)
4734 else Kill(K_EXTRAHARDKILL, FLastSpawnerUID, FLastHit);
4736 if FAlive and ((FLastHit <> HIT_FLAME) or (FFireTime <= 0)) then
4737 begin
4738 if FDamageBuffer <= 20 then FModel.PlaySound(MODELSOUND_PAIN, 1, FObj.X, FObj.Y)
4739 else if FDamageBuffer <= 55 then FModel.PlaySound(MODELSOUND_PAIN, 2, FObj.X, FObj.Y)
4740 else if FDamageBuffer <= 120 then FModel.PlaySound(MODELSOUND_PAIN, 3, FObj.X, FObj.Y)
4741 else FModel.PlaySound(MODELSOUND_PAIN, 4, FObj.X, FObj.Y);
4742 end;
4744 FDamageBuffer := 0;
4745 end;
4747 {CollideItem();}
4748 end; // if FAlive then ...
4750 if (FActionAnim = A_PAIN) and (FModel.Animation <> A_PAIN) then
4751 begin
4752 FModel.ChangeAnimation(FActionAnim, FActionForce);
4753 FModel.AnimState.MinLength := i;
4754 end else FModel.ChangeAnimation(FActionAnim, FActionForce and (FModel.Animation <> A_STAND));
4756 if (FModel.AnimState.Played or ((not FActionChanged) and (FModel.Animation = A_WALK)))
4757 then SetAction(A_STAND, True);
4759 if not ((FModel.Animation = A_WALK) and (Abs(FObj.Vel.X) < 4) and not FModel.GetFire()) then FModel.Update;
4761 for b := Low(FKeys) to High(FKeys) do
4762 if FKeys[b].Time = 0 then FKeys[b].Pressed := False else Dec(FKeys[b].Time);
4763 end;
4766 procedure TPlayer.getMapBox (out x, y, w, h: Integer); inline;
4767 begin
4768 x := FObj.X+PLAYER_RECT.X;
4769 y := FObj.Y+PLAYER_RECT.Y;
4770 w := PLAYER_RECT.Width;
4771 h := PLAYER_RECT.Height;
4772 end;
4775 procedure TPlayer.moveBy (dx, dy: Integer); inline;
4776 begin
4777 if (dx <> 0) or (dy <> 0) then
4778 begin
4779 FObj.X += dx;
4780 FObj.Y += dy;
4781 positionChanged();
4782 end;
4783 end;
4786 function TPlayer.Collide(X, Y: Integer; Width, Height: Word): Boolean;
4787 begin
4788 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4789 FObj.Y+PLAYER_RECT.Y,
4790 PLAYER_RECT.Width,
4791 PLAYER_RECT.Height,
4792 X, Y,
4793 Width, Height);
4794 end;
4796 function TPlayer.Collide(Panel: TPanel): Boolean;
4797 begin
4798 Result := g_Collide(FObj.X+PLAYER_RECT.X,
4799 FObj.Y+PLAYER_RECT.Y,
4800 PLAYER_RECT.Width,
4801 PLAYER_RECT.Height,
4802 Panel.X, Panel.Y,
4803 Panel.Width, Panel.Height);
4804 end;
4806 function TPlayer.Collide(X, Y: Integer): Boolean;
4807 begin
4808 X := X-FObj.X-PLAYER_RECT.X;
4809 Y := Y-FObj.Y-PLAYER_RECT.Y;
4810 Result := (x >= 0) and (x <= PLAYER_RECT.Width) and
4811 (y >= 0) and (y <= PLAYER_RECT.Height);
4812 end;
4814 function g_Player_ValidName(Name: string): Boolean;
4815 var
4816 a: Integer;
4817 begin
4818 Result := True;
4820 if gPlayers = nil then Exit;
4822 for a := 0 to High(gPlayers) do
4823 if gPlayers[a] <> nil then
4824 if LowerCase(Name) = LowerCase(gPlayers[a].FName) then
4825 begin
4826 Result := False;
4827 Exit;
4828 end;
4829 end;
4831 procedure TPlayer.SetDirection(Direction: TDirection);
4832 var
4833 d: TDirection;
4834 begin
4835 d := FModel.Direction;
4837 FModel.Direction := Direction;
4838 if d <> Direction then FModel.ChangeAnimation(FModel.Animation, True);
4840 FDirection := Direction;
4841 end;
4843 function TPlayer.GetKeys(): Byte;
4844 begin
4845 Result := 0;
4847 if R_KEY_RED in FRulez then Result := KEY_RED;
4848 if R_KEY_GREEN in FRulez then Result := Result or KEY_GREEN;
4849 if R_KEY_BLUE in FRulez then Result := Result or KEY_BLUE;
4851 if FTeam = TEAM_RED then Result := Result or KEY_REDTEAM;
4852 if FTeam = TEAM_BLUE then Result := Result or KEY_BLUETEAM;
4853 end;
4855 procedure TPlayer.Use();
4856 var
4857 a: Integer;
4858 begin
4859 if FTime[T_USE] > gTime then Exit;
4861 g_Triggers_PressR(FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y, PLAYER_RECT.Width,
4862 PLAYER_RECT.Height, FUID, ACTIVATE_PLAYERPRESS);
4864 for a := 0 to High(gPlayers) do
4865 if (gPlayers[a] <> nil) and (gPlayers[a] <> Self) and
4866 gPlayers[a].alive and SameTeam(FUID, gPlayers[a].FUID) and
4867 g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4868 FObj.Rect.Width, FObj.Rect.Height, @gPlayers[a].FObj) then
4869 begin
4870 gPlayers[a].Touch();
4871 if g_Game_IsNet and g_Game_IsServer then
4872 MH_SEND_GameEvent(NET_EV_PLAYER_TOUCH, gPlayers[a].FUID);
4873 end;
4875 FTime[T_USE] := gTime+120;
4876 end;
4878 procedure TPlayer.NetFire(Wpn: Byte; X, Y, AX, AY: Integer; WID: Integer = -1);
4879 var
4880 locObj: TObj;
4881 visible: Boolean = True;
4882 WX, WY, XD, YD: Integer;
4883 begin
4884 WX := X;
4885 WY := Y;
4886 XD := AX;
4887 YD := AY;
4889 case FCurrWeap of
4890 WEAPON_KASTET:
4891 begin
4892 visible := False;
4893 DoPunch();
4894 if R_BERSERK in FRulez then
4895 begin
4896 //g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 75, FUID);
4897 locobj.X := FObj.X+FObj.Rect.X;
4898 locobj.Y := FObj.Y+FObj.Rect.Y;
4899 locobj.rect.X := 0;
4900 locobj.rect.Y := 0;
4901 locobj.rect.Width := 39;
4902 locobj.rect.Height := 52;
4903 locobj.Vel.X := (xd-wx) div 2;
4904 locobj.Vel.Y := (yd-wy) div 2;
4905 locobj.Accel.X := xd-wx;
4906 locobj.Accel.y := yd-wy;
4908 if g_Weapon_Hit(@locobj, 50, FUID, HIT_SOME) <> 0 then
4909 g_Sound_PlayExAt('SOUND_WEAPON_HITBERSERK', FObj.X, FObj.Y)
4910 else
4911 g_Sound_PlayExAt('SOUND_WEAPON_MISSBERSERK', FObj.X, FObj.Y);
4913 if gFlash = 1 then
4914 if FPain < 50 then
4915 FPain := min(FPain + 25, 50);
4916 end else
4917 g_Weapon_punch(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, 3, FUID);
4918 end;
4920 WEAPON_SAW:
4921 begin
4922 if g_Weapon_chainsaw(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y,
4923 IfThen(gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF], 9, 3), FUID) <> 0 then
4924 begin
4925 FSawSoundSelect.Stop();
4926 FSawSound.Stop();
4927 FSawSoundHit.PlayAt(FObj.X, FObj.Y);
4928 end
4929 else if not FSawSoundHit.IsPlaying() then
4930 begin
4931 FSawSoundSelect.Stop();
4932 FSawSound.PlayAt(FObj.X, FObj.Y);
4933 end;
4934 end;
4936 WEAPON_PISTOL:
4937 begin
4938 g_Sound_PlayExAt('SOUND_WEAPON_FIREPISTOL', GameX, Gamey);
4939 FFireAngle := FAngle;
4940 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4941 GameVelX, GameVelY-2, SHELL_BULLET);
4942 end;
4944 WEAPON_SHOTGUN1:
4945 begin
4946 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4947 FFireAngle := FAngle;
4948 FShellTimer := 10;
4949 FShellType := SHELL_SHELL;
4950 end;
4952 WEAPON_SHOTGUN2:
4953 begin
4954 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN2', Gamex, Gamey);
4955 FFireAngle := FAngle;
4956 FShellTimer := 13;
4957 FShellType := SHELL_DBLSHELL;
4958 end;
4960 WEAPON_CHAINGUN:
4961 begin
4962 g_Sound_PlayExAt('SOUND_WEAPON_FIRECGUN', Gamex, Gamey);
4963 FFireAngle := FAngle;
4964 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4965 GameVelX, GameVelY-2, SHELL_BULLET);
4966 end;
4968 WEAPON_ROCKETLAUNCHER:
4969 begin
4970 g_Weapon_Rocket(wx, wy, xd, yd, FUID, WID);
4971 FFireAngle := FAngle;
4972 end;
4974 WEAPON_PLASMA:
4975 begin
4976 g_Weapon_Plasma(wx, wy, xd, yd, FUID, WID);
4977 FFireAngle := FAngle;
4978 end;
4980 WEAPON_BFG:
4981 begin
4982 g_Weapon_BFGShot(wx, wy, xd, yd, FUID, WID);
4983 FFireAngle := FAngle;
4984 end;
4986 WEAPON_SUPERPULEMET:
4987 begin
4988 g_Sound_PlayExAt('SOUND_WEAPON_FIRESHOTGUN', Gamex, Gamey);
4989 FFireAngle := FAngle;
4990 g_Player_CreateShell(GameX+PLAYER_RECT_CX, GameY+PLAYER_RECT_CX,
4991 GameVelX, GameVelY-2, SHELL_SHELL);
4992 end;
4994 WEAPON_FLAMETHROWER:
4995 begin
4996 g_Weapon_flame(wx, wy, xd, yd, FUID, WID);
4997 FlamerOn;
4998 FFireAngle := FAngle;
4999 end;
5000 end;
5002 if not visible then Exit;
5004 if (FAngle = 0) or (FAngle = 180) then SetAction(A_ATTACK)
5005 else if (FAngle = ANGLE_LEFTDOWN) or (FAngle = ANGLE_RIGHTDOWN) then SetAction(A_ATTACKDOWN)
5006 else if (FAngle = ANGLE_LEFTUP) or (FAngle = ANGLE_RIGHTUP) then SetAction(A_ATTACKUP);
5007 end;
5009 procedure TPlayer.DoLerp(Level: Integer = 2);
5010 begin
5011 if FObj.X <> FXTo then FObj.X := Lerp(FObj.X, FXTo, Level);
5012 if FObj.Y <> FYTo then FObj.Y := Lerp(FObj.Y, FYTo, Level);
5013 end;
5015 procedure TPlayer.SetLerp(XTo, YTo: Integer);
5016 var
5017 AX, AY: Integer;
5018 begin
5019 FXTo := XTo;
5020 FYTo := YTo;
5021 if FJustTeleported or (NetInterpLevel < 1) then
5022 begin
5023 FObj.X := XTo;
5024 FObj.Y := YTo;
5025 if FJustTeleported then
5026 begin
5027 FObj.oldX := FObj.X;
5028 FObj.oldY := FObj.Y;
5029 end;
5030 end
5031 else
5032 begin
5033 AX := Abs(FXTo - FObj.X);
5034 AY := Abs(FYTo - FObj.Y);
5035 if (AX > 32) or (AX <= NetInterpLevel) then
5036 FObj.X := FXTo;
5037 if (AY > 32) or (AY <= NetInterpLevel) then
5038 FObj.Y := FYTo;
5039 end;
5040 end;
5042 function TPlayer.FullInLift(XInc, YInc: Integer): Integer;
5043 begin
5044 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5045 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5046 PANEL_LIFTUP, False) then Result := -1
5047 else
5048 if g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
5049 PLAYER_RECT.Width, PLAYER_RECT.Height-8,
5050 PANEL_LIFTDOWN, False) then Result := 1
5051 else Result := 0;
5052 end;
5054 function TPlayer.GetFlag(Flag: Byte): Boolean;
5055 var
5056 s, ts: String;
5057 evtype, a: Byte;
5058 begin
5059 Result := False;
5061 if Flag = FLAG_NONE then
5062 Exit;
5064 if not g_Game_IsServer then Exit;
5066 // Принес чужой флаг на свою базу:
5067 if (Flag = FTeam) and
5068 (gFlags[Flag].State = FLAG_STATE_NORMAL) and
5069 (FFlag <> FLAG_NONE) then
5070 begin
5071 if FFlag = FLAG_RED then
5072 s := _lc[I_PLAYER_FLAG_RED]
5073 else
5074 s := _lc[I_PLAYER_FLAG_BLUE];
5076 evtype := FLAG_STATE_SCORED;
5078 ts := Format('%.4d', [gFlags[FFlag].CaptureTime]);
5079 Insert('.', ts, Length(ts) + 1 - 3);
5080 g_Console_Add(Format(_lc[I_PLAYER_FLAG_CAPTURE], [FName, s, ts]), True);
5082 g_Map_ResetFlag(FFlag);
5083 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_CAPTURE], [AnsiUpperCase(s)]), 144);
5085 if ((Self = gPlayer1) or (Self = gPlayer2)
5086 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5087 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5088 a := 0
5089 else
5090 a := 1;
5092 if not sound_cap_flag[a].IsPlaying() then
5093 sound_cap_flag[a].Play();
5095 gTeamStat[FTeam].Score += 1;
5097 Result := True;
5098 if g_Game_IsNet then
5099 begin
5100 MH_SEND_FlagEvent(evtype, FFlag, FUID, False);
5101 MH_SEND_GameStats;
5102 end;
5104 gFlags[FFlag].CaptureTime := 0;
5105 SetFlag(FLAG_NONE);
5106 Exit;
5107 end;
5109 // Подобрал свой флаг - вернул его на базу:
5110 if (Flag = FTeam) and
5111 (gFlags[Flag].State = FLAG_STATE_DROPPED) then
5112 begin
5113 if Flag = FLAG_RED then
5114 s := _lc[I_PLAYER_FLAG_RED]
5115 else
5116 s := _lc[I_PLAYER_FLAG_BLUE];
5118 evtype := FLAG_STATE_RETURNED;
5119 gFlags[Flag].CaptureTime := 0;
5121 g_Console_Add(Format(_lc[I_PLAYER_FLAG_RETURN], [FName, s]), True);
5123 g_Map_ResetFlag(Flag);
5124 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
5126 if ((Self = gPlayer1) or (Self = gPlayer2)
5127 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5128 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5129 a := 0
5130 else
5131 a := 1;
5133 if not sound_ret_flag[a].IsPlaying() then
5134 sound_ret_flag[a].Play();
5136 Result := True;
5137 if g_Game_IsNet then
5138 begin
5139 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5140 MH_SEND_GameStats;
5141 end;
5142 Exit;
5143 end;
5145 // Подобрал чужой флаг:
5146 if (Flag <> FTeam) and (FTime[T_FLAGCAP] <= gTime) then
5147 begin
5148 SetFlag(Flag);
5150 if Flag = FLAG_RED then
5151 s := _lc[I_PLAYER_FLAG_RED]
5152 else
5153 s := _lc[I_PLAYER_FLAG_BLUE];
5155 evtype := FLAG_STATE_CAPTURED;
5157 g_Console_Add(Format(_lc[I_PLAYER_FLAG_GET], [FName, s]), True);
5159 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_GET], [AnsiUpperCase(s)]), 144);
5161 gFlags[Flag].State := FLAG_STATE_CAPTURED;
5163 if ((Self = gPlayer1) or (Self = gPlayer2)
5164 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5165 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5166 a := 0
5167 else
5168 a := 1;
5170 if not sound_get_flag[a].IsPlaying() then
5171 sound_get_flag[a].Play();
5173 Result := True;
5174 if g_Game_IsNet then
5175 begin
5176 MH_SEND_FlagEvent(evtype, Flag, FUID, False);
5177 MH_SEND_GameStats;
5178 end;
5179 end;
5180 end;
5182 procedure TPlayer.SetFlag(Flag: Byte);
5183 begin
5184 FFlag := Flag;
5185 if FModel <> nil then
5186 FModel.SetFlag(FFlag);
5187 end;
5189 function TPlayer.TryDropFlag(): Boolean;
5190 begin
5191 if LongBool(gGameSettings.Options and GAME_OPTION_ALLOWDROPFLAG) then
5192 Result := DropFlag(False, LongBool(gGameSettings.Options and GAME_OPTION_THROWFLAG))
5193 else
5194 Result := False;
5195 end;
5197 function TPlayer.DropFlag(Silent: Boolean = True; DoThrow: Boolean = False): Boolean;
5198 var
5199 s: String;
5200 a: Byte;
5201 xv, yv: Integer;
5202 begin
5203 Result := False;
5204 if (not g_Game_IsServer) or (FFlag = FLAG_NONE) then
5205 Exit;
5206 FTime[T_FLAGCAP] := gTime + 2000;
5207 with gFlags[FFlag] do
5208 begin
5209 Obj.X := FObj.X;
5210 Obj.Y := FObj.Y;
5211 Direction := FDirection;
5212 State := FLAG_STATE_DROPPED;
5213 Count := FLAG_TIME;
5214 if DoThrow then
5215 begin
5216 xv := FObj.Vel.X + IfThen(Direction = TDirection.D_RIGHT, 10, -10);
5217 yv := FObj.Vel.Y - 2;
5218 end
5219 else
5220 begin
5221 xv := (FObj.Vel.X div 2);
5222 yv := (FObj.Vel.Y div 2) - 2;
5223 end;
5224 g_Obj_Push(@Obj, xv, yv);
5226 positionChanged(); // this updates spatial accelerators
5228 if FFlag = FLAG_RED then
5229 s := _lc[I_PLAYER_FLAG_RED]
5230 else
5231 s := _lc[I_PLAYER_FLAG_BLUE];
5233 g_Console_Add(Format(_lc[I_PLAYER_FLAG_DROP], [FName, s]), True);
5234 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_DROP], [AnsiUpperCase(s)]), 144);
5236 if ((Self = gPlayer1) or (Self = gPlayer2)
5237 or ((gPlayer1 <> nil) and (gPlayer1.Team = FTeam))
5238 or ((gPlayer2 <> nil) and (gPlayer2.Team = FTeam))) then
5239 a := 0
5240 else
5241 a := 1;
5243 if (not Silent) and (not sound_lost_flag[a].IsPlaying()) then
5244 sound_lost_flag[a].Play();
5246 if g_Game_IsNet then
5247 MH_SEND_FlagEvent(FLAG_STATE_DROPPED, Flag, FUID, False);
5248 end;
5249 SetFlag(FLAG_NONE);
5250 Result := True;
5251 end;
5253 procedure TPlayer.GetSecret();
5254 begin
5255 if (self = gPlayer1) or (self = gPlayer2) then
5256 begin
5257 g_Console_Add(Format(_lc[I_PLAYER_SECRET], [FName]), True);
5258 g_Sound_PlayEx('SOUND_GAME_SECRET');
5259 end;
5260 Inc(FSecrets);
5261 end;
5263 procedure TPlayer.PressKey(Key: Byte; Time: Word = 1);
5264 begin
5265 Assert(Key <= High(FKeys));
5267 FKeys[Key].Pressed := True;
5268 FKeys[Key].Time := Time;
5269 end;
5271 function TPlayer.IsKeyPressed(K: Byte): Boolean;
5272 begin
5273 Result := FKeys[K].Pressed;
5274 end;
5276 procedure TPlayer.ReleaseKeys();
5277 var
5278 a: Integer;
5279 begin
5280 for a := Low(FKeys) to High(FKeys) do
5281 begin
5282 FKeys[a].Pressed := False;
5283 FKeys[a].Time := 0;
5284 end;
5285 end;
5287 procedure TPlayer.OnDamage(Angle: SmallInt);
5288 begin
5289 end;
5291 function TPlayer.firediry(): Integer;
5292 begin
5293 if FKeys[KEY_UP].Pressed then Result := -42
5294 else if FKeys[KEY_DOWN].Pressed then Result := 19
5295 else Result := 0;
5296 end;
5298 procedure TPlayer.RememberState();
5299 var
5300 i: Integer;
5301 SavedState: TPlayerSavedState;
5302 begin
5303 SavedState.Health := FHealth;
5304 SavedState.Armor := FArmor;
5305 SavedState.Air := FAir;
5306 SavedState.JetFuel := FJetFuel;
5307 SavedState.CurrWeap := FCurrWeap;
5308 SavedState.NextWeap := FNextWeap;
5309 SavedState.NextWeapDelay := FNextWeapDelay;
5310 for i := Low(FWeapon) to High(FWeapon) do
5311 SavedState.Weapon[i] := FWeapon[i];
5312 for i := Low(FAmmo) to High(FAmmo) do
5313 SavedState.Ammo[i] := FAmmo[i];
5314 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5315 SavedState.MaxAmmo[i] := FMaxAmmo[i];
5316 SavedState.Rulez := FRulez - [R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5318 FSavedStateNum := -1;
5319 for i := Low(SavedStates) to High(SavedStates) do
5320 if not SavedStates[i].Used then
5321 begin
5322 FSavedStateNum := i;
5323 break;
5324 end;
5325 if FSavedStateNum < 0 then
5326 begin
5327 SetLength(SavedStates, Length(SavedStates) + 1);
5328 FSavedStateNum := High(SavedStates);
5329 end;
5331 SavedState.Used := True;
5332 SavedStates[FSavedStateNum] := SavedState;
5333 end;
5335 procedure TPlayer.RecallState();
5336 var
5337 i: Integer;
5338 SavedState: TPlayerSavedState;
5339 begin
5340 if(FSavedStateNum < 0) or (FSavedStateNum > High(SavedStates)) then
5341 Exit;
5343 SavedState := SavedStates[FSavedStateNum];
5344 SavedStates[FSavedStateNum].Used := False;
5345 FSavedStateNum := -1;
5347 FHealth := SavedState.Health;
5348 FArmor := SavedState.Armor;
5349 FAir := SavedState.Air;
5350 FJetFuel := SavedState.JetFuel;
5351 FCurrWeap := SavedState.CurrWeap;
5352 FNextWeap := SavedState.NextWeap;
5353 FNextWeapDelay := SavedState.NextWeapDelay;
5354 for i := Low(FWeapon) to High(FWeapon) do
5355 FWeapon[i] := SavedState.Weapon[i];
5356 for i := Low(FAmmo) to High(FAmmo) do
5357 FAmmo[i] := SavedState.Ammo[i];
5358 for i := Low(FMaxAmmo) to High(FMaxAmmo) do
5359 FMaxAmmo[i] := SavedState.MaxAmmo[i];
5360 FRulez := SavedState.Rulez;
5362 if gGameSettings.GameType = GT_SERVER then
5363 MH_SEND_PlayerStats(FUID);
5364 end;
5366 procedure TPlayer.SaveState (st: TStream);
5367 var
5368 i: Integer;
5369 b: Byte;
5370 begin
5371 // Сигнатура игрока
5372 utils.writeSign(st, 'PLYR');
5373 utils.writeInt(st, Byte(PLR_SAVE_VERSION)); // version
5374 // Бот или человек
5375 utils.writeBool(st, FIamBot);
5376 // UID игрока
5377 utils.writeInt(st, Word(FUID));
5378 // Имя игрока
5379 utils.writeStr(st, FName);
5380 // Команда
5381 utils.writeInt(st, Byte(FTeam));
5382 // Жив ли
5383 utils.writeBool(st, FAlive);
5384 // Израсходовал ли все жизни
5385 utils.writeBool(st, FNoRespawn);
5386 // Направление
5387 if FDirection = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
5388 utils.writeInt(st, Byte(b));
5389 // Здоровье
5390 utils.writeInt(st, LongInt(FHealth));
5391 // Коэффициент инвалидности
5392 utils.writeInt(st, LongInt(FHandicap));
5393 // Жизни
5394 utils.writeInt(st, Byte(FLives));
5395 // Броня
5396 utils.writeInt(st, LongInt(FArmor));
5397 // Запас воздуха
5398 utils.writeInt(st, LongInt(FAir));
5399 // Запас горючего
5400 utils.writeInt(st, LongInt(FJetFuel));
5401 // Боль
5402 utils.writeInt(st, LongInt(FPain));
5403 // Убил
5404 utils.writeInt(st, LongInt(FKills));
5405 // Убил монстров
5406 utils.writeInt(st, LongInt(FMonsterKills));
5407 // Фрагов
5408 utils.writeInt(st, LongInt(FFrags));
5409 // Фрагов подряд
5410 utils.writeInt(st, Byte(FFragCombo));
5411 // Время последнего фрага
5412 utils.writeInt(st, LongWord(FLastFrag));
5413 // Смертей
5414 utils.writeInt(st, LongInt(FDeath));
5415 // Какой флаг несет
5416 utils.writeInt(st, Byte(FFlag));
5417 // Нашел секретов
5418 utils.writeInt(st, LongInt(FSecrets));
5419 // Текущее оружие
5420 utils.writeInt(st, Byte(FCurrWeap));
5421 // Желаемое оружие
5422 utils.writeInt(st, Word(FNextWeap));
5423 // ...и пауза
5424 utils.writeInt(st, Byte(FNextWeapDelay));
5425 // Время зарядки BFG
5426 utils.writeInt(st, SmallInt(FBFGFireCounter));
5427 // Буфер урона
5428 utils.writeInt(st, LongInt(FDamageBuffer));
5429 // Последний ударивший
5430 utils.writeInt(st, Word(FLastSpawnerUID));
5431 // Тип последнего полученного урона
5432 utils.writeInt(st, Byte(FLastHit));
5433 // Объект игрока
5434 Obj_SaveState(st, @FObj);
5435 // Текущее количество патронов
5436 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FAmmo[i]));
5437 // Максимальное количество патронов
5438 for i := A_BULLETS to A_HIGH do utils.writeInt(st, Word(FMaxAmmo[i]));
5439 // Наличие оружия
5440 for i := WP_FIRST to WP_LAST do utils.writeBool(st, FWeapon[i]);
5441 // Время перезарядки оружия
5442 for i := WP_FIRST to WP_LAST do utils.writeInt(st, Word(FReloading[i]));
5443 // Наличие рюкзака
5444 utils.writeBool(st, (R_ITEM_BACKPACK in FRulez));
5445 // Наличие красного ключа
5446 utils.writeBool(st, (R_KEY_RED in FRulez));
5447 // Наличие зеленого ключа
5448 utils.writeBool(st, (R_KEY_GREEN in FRulez));
5449 // Наличие синего ключа
5450 utils.writeBool(st, (R_KEY_BLUE in FRulez));
5451 // Наличие берсерка
5452 utils.writeBool(st, (R_BERSERK in FRulez));
5453 // Время действия специальных предметов
5454 for i := MR_SUIT to MR_MAX do utils.writeInt(st, LongWord(FMegaRulez[i]));
5455 // Время до повторного респауна, смены оружия, исользования, захвата флага
5456 for i := T_RESPAWN to T_FLAGCAP do utils.writeInt(st, LongWord(FTime[i]));
5457 // Название модели
5458 utils.writeStr(st, FModel.GetName());
5459 // Цвет модели
5460 utils.writeInt(st, Byte(FColor.R));
5461 utils.writeInt(st, Byte(FColor.G));
5462 utils.writeInt(st, Byte(FColor.B));
5463 end;
5466 procedure TPlayer.LoadState (st: TStream);
5467 var
5468 i: Integer;
5469 str: String;
5470 b: Byte;
5471 begin
5472 assert(st <> nil);
5474 // Сигнатура игрока
5475 if not utils.checkSign(st, 'PLYR') then raise XStreamError.Create('invalid player signature');
5476 if (utils.readByte(st) <> PLR_SAVE_VERSION) then raise XStreamError.Create('invalid player version');
5477 // Бот или человек:
5478 FIamBot := utils.readBool(st);
5479 // UID игрока
5480 FUID := utils.readWord(st);
5481 // Имя игрока
5482 str := utils.readStr(st);
5483 if (self <> gPlayer1) and (self <> gPlayer2) then FName := str;
5484 // Команда
5485 FTeam := utils.readByte(st);
5486 // Жив ли
5487 FAlive := utils.readBool(st);
5488 // Израсходовал ли все жизни
5489 FNoRespawn := utils.readBool(st);
5490 // Направление
5491 b := utils.readByte(st);
5492 if b = 1 then FDirection := TDirection.D_LEFT else FDirection := TDirection.D_RIGHT; // b = 2
5493 // Здоровье
5494 FHealth := utils.readLongInt(st);
5495 // Коэффициент инвалидности
5496 FHandicap := utils.readLongInt(st);
5497 // Жизни
5498 FLives := utils.readByte(st);
5499 // Броня
5500 FArmor := utils.readLongInt(st);
5501 // Запас воздуха
5502 FAir := utils.readLongInt(st);
5503 // Запас горючего
5504 FJetFuel := utils.readLongInt(st);
5505 // Боль
5506 FPain := utils.readLongInt(st);
5507 // Убил
5508 FKills := utils.readLongInt(st);
5509 // Убил монстров
5510 FMonsterKills := utils.readLongInt(st);
5511 // Фрагов
5512 FFrags := utils.readLongInt(st);
5513 // Фрагов подряд
5514 FFragCombo := utils.readByte(st);
5515 // Время последнего фрага
5516 FLastFrag := utils.readLongWord(st);
5517 // Смертей
5518 FDeath := utils.readLongInt(st);
5519 // Какой флаг несет
5520 FFlag := utils.readByte(st);
5521 // Нашел секретов
5522 FSecrets := utils.readLongInt(st);
5523 // Текущее оружие
5524 FCurrWeap := utils.readByte(st);
5525 // Желаемое оружие
5526 FNextWeap := utils.readWord(st);
5527 // ...и пауза
5528 FNextWeapDelay := utils.readByte(st);
5529 // Время зарядки BFG
5530 FBFGFireCounter := utils.readSmallInt(st);
5531 // Буфер урона
5532 FDamageBuffer := utils.readLongInt(st);
5533 // Последний ударивший
5534 FLastSpawnerUID := utils.readWord(st);
5535 // Тип последнего полученного урона
5536 FLastHit := utils.readByte(st);
5537 // Объект игрока
5538 Obj_LoadState(@FObj, st);
5539 // Текущее количество патронов
5540 for i := A_BULLETS to A_HIGH do FAmmo[i] := utils.readWord(st);
5541 // Максимальное количество патронов
5542 for i := A_BULLETS to A_HIGH do FMaxAmmo[i] := utils.readWord(st);
5543 // Наличие оружия
5544 for i := WP_FIRST to WP_LAST do FWeapon[i] := utils.readBool(st);
5545 // Время перезарядки оружия
5546 for i := WP_FIRST to WP_LAST do FReloading[i] := utils.readWord(st);
5547 // Наличие рюкзака
5548 if utils.readBool(st) then Include(FRulez, R_ITEM_BACKPACK);
5549 // Наличие красного ключа
5550 if utils.readBool(st) then Include(FRulez, R_KEY_RED);
5551 // Наличие зеленого ключа
5552 if utils.readBool(st) then Include(FRulez, R_KEY_GREEN);
5553 // Наличие синего ключа
5554 if utils.readBool(st) then Include(FRulez, R_KEY_BLUE);
5555 // Наличие берсерка
5556 if utils.readBool(st) then Include(FRulez, R_BERSERK);
5557 // Время действия специальных предметов
5558 for i := MR_SUIT to MR_MAX do FMegaRulez[i] := utils.readLongWord(st);
5559 // Время до повторного респауна, смены оружия, исользования, захвата флага
5560 for i := T_RESPAWN to T_FLAGCAP do FTime[i] := utils.readLongWord(st);
5561 // Название модели
5562 str := utils.readStr(st);
5563 // Цвет модели
5564 FColor.R := utils.readByte(st);
5565 FColor.G := utils.readByte(st);
5566 FColor.B := utils.readByte(st);
5567 if (self = gPlayer1) then
5568 begin
5569 str := gPlayer1Settings.Model;
5570 FColor := gPlayer1Settings.Color;
5571 end
5572 else if (self = gPlayer2) then
5573 begin
5574 str := gPlayer2Settings.Model;
5575 FColor := gPlayer2Settings.Color;
5576 end;
5577 // Обновляем модель игрока
5578 SetModel(str);
5579 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
5580 FModel.Color := TEAMCOLOR[FTeam]
5581 else
5582 FModel.Color := FColor;
5583 end;
5586 procedure TPlayer.AllRulez(Health: Boolean);
5587 var
5588 a: Integer;
5589 begin
5590 if Health then
5591 begin
5592 FHealth := PLAYER_HP_LIMIT;
5593 FArmor := PLAYER_AP_LIMIT;
5594 Exit;
5595 end;
5597 for a := WP_FIRST to WP_LAST do FWeapon[a] := True;
5598 for a := A_BULLETS to A_HIGH do FAmmo[a] := 30000;
5599 FRulez := FRulez+[R_KEY_RED, R_KEY_GREEN, R_KEY_BLUE];
5600 end;
5602 procedure TPlayer.RestoreHealthArmor();
5603 begin
5604 FHealth := PLAYER_HP_LIMIT;
5605 FArmor := PLAYER_AP_LIMIT;
5606 end;
5608 procedure TPlayer.FragCombo();
5609 var
5610 Param: Integer;
5611 begin
5612 if (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) or g_Game_IsClient then
5613 Exit;
5614 if gTime - FLastFrag < FRAG_COMBO_TIME then
5615 begin
5616 if FFragCombo < 5 then
5617 Inc(FFragCombo);
5618 Param := FUID or (FFragCombo shl 16);
5619 if (FComboEvnt >= Low(gDelayedEvents)) and
5620 (FComboEvnt <= High(gDelayedEvents)) and
5621 gDelayedEvents[FComboEvnt].Pending and
5622 (gDelayedEvents[FComboEvnt].DEType = DE_KILLCOMBO) and
5623 (gDelayedEvents[FComboEvnt].DENum and $FFFF = FUID) then
5624 begin
5625 gDelayedEvents[FComboEvnt].Time := gTime + 500;
5626 gDelayedEvents[FComboEvnt].DENum := Param;
5627 end
5628 else
5629 FComboEvnt := g_Game_DelayEvent(DE_KILLCOMBO, 500, Param);
5630 end
5631 else
5632 FFragCombo := 1;
5634 FLastFrag := gTime;
5635 end;
5637 procedure TPlayer.GiveItem(ItemType: Byte);
5638 begin
5639 case ItemType of
5640 ITEM_SUIT:
5641 if FMegaRulez[MR_SUIT] < gTime+PLAYER_SUIT_TIME then
5642 begin
5643 FMegaRulez[MR_SUIT] := gTime+PLAYER_SUIT_TIME;
5644 end;
5646 ITEM_OXYGEN:
5647 if FAir < AIR_MAX then
5648 begin
5649 FAir := AIR_MAX;
5650 end;
5652 ITEM_MEDKIT_BLACK:
5653 begin
5654 if not (R_BERSERK in FRulez) then
5655 begin
5656 Include(FRulez, R_BERSERK);
5657 if FBFGFireCounter < 1 then
5658 begin
5659 FCurrWeap := WEAPON_KASTET;
5660 resetWeaponQueue();
5661 FModel.SetWeapon(WEAPON_KASTET);
5662 end;
5663 if gFlash <> 0 then
5664 Inc(FPain, 100);
5665 FBerserk := gTime+30000;
5666 end;
5667 if FHealth < PLAYER_HP_SOFT then
5668 begin
5669 FHealth := PLAYER_HP_SOFT;
5670 FBerserk := gTime+30000;
5671 end;
5672 end;
5674 ITEM_INVUL:
5675 if FMegaRulez[MR_INVUL] < gTime+PLAYER_INVUL_TIME then
5676 begin
5677 FMegaRulez[MR_INVUL] := gTime+PLAYER_INVUL_TIME;
5678 FSpawnInvul := 0;
5679 end;
5681 ITEM_INVIS:
5682 if FMegaRulez[MR_INVIS] < gTime+PLAYER_INVIS_TIME then
5683 begin
5684 FMegaRulez[MR_INVIS] := gTime+PLAYER_INVIS_TIME;
5685 end;
5687 ITEM_JETPACK:
5688 if FJetFuel < JET_MAX then
5689 begin
5690 FJetFuel := JET_MAX;
5691 end;
5693 ITEM_MEDKIT_SMALL: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 10, PLAYER_HP_SOFT);
5694 ITEM_MEDKIT_LARGE: if FHealth < PLAYER_HP_SOFT then IncMax(FHealth, 25, PLAYER_HP_SOFT);
5696 ITEM_ARMOR_GREEN: if FArmor < PLAYER_AP_SOFT then FArmor := PLAYER_AP_SOFT;
5697 ITEM_ARMOR_BLUE: if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5699 ITEM_SPHERE_BLUE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 100, PLAYER_HP_LIMIT);
5700 ITEM_SPHERE_WHITE:
5701 if (FHealth < PLAYER_HP_LIMIT) or (FArmor < PLAYER_AP_LIMIT) then
5702 begin
5703 if FHealth < PLAYER_HP_LIMIT then FHealth := PLAYER_HP_LIMIT;
5704 if FArmor < PLAYER_AP_LIMIT then FArmor := PLAYER_AP_LIMIT;
5705 end;
5707 ITEM_WEAPON_SAW: FWeapon[WEAPON_SAW] := True;
5708 ITEM_WEAPON_SHOTGUN1: FWeapon[WEAPON_SHOTGUN1] := True;
5709 ITEM_WEAPON_SHOTGUN2: FWeapon[WEAPON_SHOTGUN2] := True;
5710 ITEM_WEAPON_CHAINGUN: FWeapon[WEAPON_CHAINGUN] := True;
5711 ITEM_WEAPON_ROCKETLAUNCHER: FWeapon[WEAPON_ROCKETLAUNCHER] := True;
5712 ITEM_WEAPON_PLASMA: FWeapon[WEAPON_PLASMA] := True;
5713 ITEM_WEAPON_BFG: FWeapon[WEAPON_BFG] := True;
5714 ITEM_WEAPON_SUPERPULEMET: FWeapon[WEAPON_SUPERPULEMET] := True;
5715 ITEM_WEAPON_FLAMETHROWER: FWeapon[WEAPON_FLAMETHROWER] := True;
5717 ITEM_AMMO_BULLETS: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5718 ITEM_AMMO_BULLETS_BOX: if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 50, FMaxAmmo[A_BULLETS]);
5719 ITEM_AMMO_SHELLS: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5720 ITEM_AMMO_SHELLS_BOX: if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 25, FMaxAmmo[A_SHELLS]);
5721 ITEM_AMMO_ROCKET: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5722 ITEM_AMMO_ROCKET_BOX: if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 5, FMaxAmmo[A_ROCKETS]);
5723 ITEM_AMMO_CELL: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5724 ITEM_AMMO_CELL_BIG: if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 100, FMaxAmmo[A_CELLS]);
5725 ITEM_AMMO_FUELCAN: if FAmmo[A_FUEL] < FMaxAmmo[A_FUEL] then IncMax(FAmmo[A_FUEL], 100, FMaxAmmo[A_FUEL]);
5727 ITEM_AMMO_BACKPACK:
5728 if (FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS]) or
5729 (FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS]) or
5730 (FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS]) or
5731 (FAmmo[A_CELLS] < FMaxAmmo[A_CELLS]) or
5732 (FMaxAmmo[A_FUEL] < AmmoLimits[1, A_FUEL]) then
5733 begin
5734 FMaxAmmo[A_BULLETS] := AmmoLimits[1, A_BULLETS];
5735 FMaxAmmo[A_SHELLS] := AmmoLimits[1, A_SHELLS];
5736 FMaxAmmo[A_ROCKETS] := AmmoLimits[1, A_ROCKETS];
5737 FMaxAmmo[A_CELLS] := AmmoLimits[1, A_CELLS];
5738 FMaxAmmo[A_FUEL] := AmmoLimits[1, A_FUEL];
5740 if FAmmo[A_BULLETS] < FMaxAmmo[A_BULLETS] then IncMax(FAmmo[A_BULLETS], 10, FMaxAmmo[A_BULLETS]);
5741 if FAmmo[A_SHELLS] < FMaxAmmo[A_SHELLS] then IncMax(FAmmo[A_SHELLS], 4, FMaxAmmo[A_SHELLS]);
5742 if FAmmo[A_ROCKETS] < FMaxAmmo[A_ROCKETS] then IncMax(FAmmo[A_ROCKETS], 1, FMaxAmmo[A_ROCKETS]);
5743 if FAmmo[A_CELLS] < FMaxAmmo[A_CELLS] then IncMax(FAmmo[A_CELLS], 40, FMaxAmmo[A_CELLS]);
5745 FRulez := FRulez + [R_ITEM_BACKPACK];
5746 end;
5748 ITEM_KEY_RED: if not (R_KEY_RED in FRulez) then Include(FRulez, R_KEY_RED);
5749 ITEM_KEY_GREEN: if not (R_KEY_GREEN in FRulez) then Include(FRulez, R_KEY_GREEN);
5750 ITEM_KEY_BLUE: if not (R_KEY_BLUE in FRulez) then Include(FRulez, R_KEY_BLUE);
5752 ITEM_BOTTLE: if FHealth < PLAYER_HP_LIMIT then IncMax(FHealth, 4, PLAYER_HP_LIMIT);
5753 ITEM_HELMET: if FArmor < PLAYER_AP_LIMIT then IncMax(FArmor, 5, PLAYER_AP_LIMIT);
5755 else
5756 Exit;
5757 end;
5758 if g_Game_IsNet and g_Game_IsServer then
5759 MH_SEND_PlayerStats(FUID);
5760 end;
5762 procedure TPlayer.FlySmoke(Times: DWORD = 1);
5763 var i: DWORD;
5764 begin
5765 if (Random(5) = 1) and (Times = 1) then
5766 Exit;
5768 if BodyInLiquid(0, 0) then
5769 begin
5770 g_GFX_Bubbles(Obj.X+Obj.Rect.X+(Obj.Rect.Width div 2)+Random(3)-1,
5771 Obj.Y+Obj.Rect.Height+8, 1, 8, 4);
5772 if Random(2) = 0
5773 then g_Sound_PlayExAt('SOUND_GAME_BUBBLE1', FObj.X, FObj.Y)
5774 else g_Sound_PlayExAt('SOUND_GAME_BUBBLE2', FObj.X, FObj.Y);
5775 Exit;
5776 end;
5778 for i := 1 to Times do
5779 begin
5780 r_GFX_OnceAnim(
5781 R_GFX_SMOKE_TRANS,
5782 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_SMOKE_WIDTH div 2),
5783 Obj.Y+Obj.Rect.Height-4+Random(8+Times*2)
5784 );
5785 end;
5786 end;
5788 procedure TPlayer.OnFireFlame(Times: DWORD = 1);
5789 var i: DWORD;
5790 begin
5791 if (Random(10) = 1) and (Times = 1) then
5792 Exit;
5794 for i := 1 to Times do
5795 begin
5796 r_GFX_OnceAnim(
5797 R_GFX_FLAME,
5798 Obj.X+Obj.Rect.X+Random(Obj.Rect.Width+Times*2)-(R_GFX_FLAME_WIDTH div 2),
5799 Obj.Y+8+Random(8+Times*2)
5800 );
5801 end;
5802 end;
5804 procedure TPlayer.PauseSounds(Enable: Boolean);
5805 begin
5806 FSawSound.Pause(Enable);
5807 FSawSoundIdle.Pause(Enable);
5808 FSawSoundHit.Pause(Enable);
5809 FSawSoundSelect.Pause(Enable);
5810 FFlameSoundOn.Pause(Enable);
5811 FFlameSoundOff.Pause(Enable);
5812 FFlameSoundWork.Pause(Enable);
5813 FJetSoundFly.Pause(Enable);
5814 FJetSoundOn.Pause(Enable);
5815 FJetSoundOff.Pause(Enable);
5816 end;
5818 { T C o r p s e : }
5820 constructor TCorpse.Create(X, Y: Integer; ModelName: String; aMess: Boolean);
5821 begin
5822 g_Obj_Init(@FObj);
5823 FObj.X := X;
5824 FObj.Y := Y;
5825 FObj.Rect := PLAYER_CORPSERECT;
5826 FModelName := ModelName;
5827 FMess := aMess;
5829 if FMess then
5830 begin
5831 FState := CORPSE_STATE_MESS;
5832 g_PlayerModel_GetAnim(ModelName, A_DIE2, FAnimation, FAnimationMask);
5833 end
5834 else
5835 begin
5836 FState := CORPSE_STATE_NORMAL;
5837 g_PlayerModel_GetAnim(ModelName, A_DIE1, FAnimation, FAnimationMask);
5838 end;
5839 end;
5841 destructor TCorpse.Destroy();
5842 begin
5843 FAnimation.Free();
5845 inherited;
5846 end;
5848 function TCorpse.ObjPtr (): PObj; inline; begin result := @FObj; end;
5850 procedure TCorpse.positionChanged (); inline; begin end;
5852 procedure TCorpse.moveBy (dx, dy: Integer); inline;
5853 begin
5854 if (dx <> 0) or (dy <> 0) then
5855 begin
5856 FObj.X += dx;
5857 FObj.Y += dy;
5858 positionChanged();
5859 end;
5860 end;
5863 procedure TCorpse.getMapBox (out x, y, w, h: Integer); inline;
5864 begin
5865 x := FObj.X+PLAYER_CORPSERECT.X;
5866 y := FObj.Y+PLAYER_CORPSERECT.Y;
5867 w := PLAYER_CORPSERECT.Width;
5868 h := PLAYER_CORPSERECT.Height;
5869 end;
5872 procedure TCorpse.Damage(Value: Word; SpawnerUID: Word; vx, vy: Integer);
5873 var
5874 pm: TPlayerModel;
5875 Blood: TModelBlood;
5876 begin
5877 if FState = CORPSE_STATE_REMOVEME then
5878 Exit;
5880 FDamage := FDamage + Value;
5882 if FDamage > 150 then
5883 begin
5884 if FAnimation <> nil then
5885 begin
5886 FAnimation.Free();
5887 FAnimation := nil;
5889 FState := CORPSE_STATE_REMOVEME;
5891 g_Player_CreateGibs(FObj.X+FObj.Rect.X+(FObj.Rect.Width div 2),
5892 FObj.Y+FObj.Rect.Y+(FObj.Rect.Height div 2),
5893 FModelName, FColor);
5894 // Звук мяса от трупа:
5895 pm := g_PlayerModel_Get(FModelName);
5896 pm.PlaySound(MODELSOUND_DIE, 5, FObj.X, FObj.Y);
5897 pm.Free;
5899 // Зловещий смех:
5900 if (gBodyKillEvent <> -1)
5901 and gDelayedEvents[gBodyKillEvent].Pending then
5902 gDelayedEvents[gBodyKillEvent].Pending := False;
5903 gBodyKillEvent := g_Game_DelayEvent(DE_BODYKILL, 1050, SpawnerUID);
5904 end;
5905 end
5906 else
5907 begin
5908 Blood := g_PlayerModel_GetBlood(FModelName);
5909 FObj.Vel.X := FObj.Vel.X + vx;
5910 FObj.Vel.Y := FObj.Vel.Y + vy;
5911 g_GFX_Blood(FObj.X+PLAYER_CORPSERECT.X+(PLAYER_CORPSERECT.Width div 2),
5912 FObj.Y+PLAYER_CORPSERECT.Y+(PLAYER_CORPSERECT.Height div 2),
5913 Value, vx, vy, 16, (PLAYER_CORPSERECT.Height*2) div 3,
5914 Blood.R, Blood.G, Blood.B, Blood.Kind);
5915 end;
5916 end;
5918 procedure TCorpse.Update();
5919 var
5920 st: Word;
5921 begin
5922 if FState = CORPSE_STATE_REMOVEME then
5923 Exit;
5925 FObj.oldX := FObj.X;
5926 FObj.oldY := FObj.Y;
5928 if gTime mod (GAME_TICK*2) <> 0 then
5929 begin
5930 g_Obj_Move(@FObj, True, True, True);
5931 positionChanged(); // this updates spatial accelerators
5932 Exit;
5933 end;
5935 // Сопротивление воздуха для трупа:
5936 FObj.Vel.X := z_dec(FObj.Vel.X, 1);
5938 st := g_Obj_Move(@FObj, True, True, True);
5939 positionChanged(); // this updates spatial accelerators
5941 if WordBool(st and MOVE_FALLOUT) then
5942 begin
5943 FState := CORPSE_STATE_REMOVEME;
5944 Exit;
5945 end;
5947 if FAnimation <> nil then
5948 FAnimation.Update();
5949 if FAnimationMask <> nil then
5950 FAnimationMask.Update();
5951 end;
5954 procedure TCorpse.SaveState (st: TStream);
5955 var
5956 anim: Boolean;
5957 begin
5958 assert(st <> nil);
5960 // Сигнатура трупа
5961 utils.writeSign(st, 'CORP');
5962 utils.writeInt(st, Byte(0));
5963 // Состояние
5964 utils.writeInt(st, Byte(FState));
5965 // Накопленный урон
5966 utils.writeInt(st, Byte(FDamage));
5967 // Цвет
5968 utils.writeInt(st, Byte(FColor.R));
5969 utils.writeInt(st, Byte(FColor.G));
5970 utils.writeInt(st, Byte(FColor.B));
5971 // Объект трупа
5972 Obj_SaveState(st, @FObj);
5973 utils.writeInt(st, Word(FPlayerUID));
5974 // Есть ли анимация
5975 anim := (FAnimation <> nil);
5976 utils.writeBool(st, anim);
5977 // Если есть - сохраняем
5978 if anim then FAnimation.SaveState(st);
5979 // Есть ли маска анимации
5980 anim := (FAnimationMask <> nil);
5981 utils.writeBool(st, anim);
5982 // Если есть - сохраняем
5983 if anim then FAnimationMask.SaveState(st);
5984 end;
5987 procedure TCorpse.LoadState (st: TStream);
5988 var
5989 anim: Boolean;
5990 begin
5991 assert(st <> nil);
5993 // Сигнатура трупа
5994 if not utils.checkSign(st, 'CORP') then raise XStreamError.Create('invalid corpse signature');
5995 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid corpse version');
5996 // Состояние
5997 FState := utils.readByte(st);
5998 // Накопленный урон
5999 FDamage := utils.readByte(st);
6000 // Цвет
6001 FColor.R := utils.readByte(st);
6002 FColor.G := utils.readByte(st);
6003 FColor.B := utils.readByte(st);
6004 // Объект трупа
6005 Obj_LoadState(@FObj, st);
6006 FPlayerUID := utils.readWord(st);
6007 // Есть ли анимация
6008 anim := utils.readBool(st);
6009 // Если есть - загружаем
6010 if anim then
6011 begin
6012 Assert(FAnimation <> nil, 'TCorpse.LoadState: no FAnimation');
6013 FAnimation.LoadState(st);
6014 end;
6015 // Есть ли маска анимации
6016 anim := utils.readBool(st);
6017 // Если есть - загружаем
6018 if anim then
6019 begin
6020 Assert(FAnimationMask <> nil, 'TCorpse.LoadState: no FAnimationMask');
6021 FAnimationMask.LoadState(st);
6022 end;
6023 end;
6025 { T B o t : }
6027 constructor TBot.Create();
6028 var
6029 a: Integer;
6030 begin
6031 inherited Create();
6033 FPhysics := True;
6034 FSpectator := False;
6035 FGhost := False;
6037 FIamBot := True;
6039 Inc(gNumBots);
6041 for a := WP_FIRST to WP_LAST do
6042 begin
6043 FDifficult.WeaponPrior[a] := WEAPON_PRIOR1[a];
6044 FDifficult.CloseWeaponPrior[a] := WEAPON_PRIOR2[a];
6045 //FDifficult.SafeWeaponPrior[a] := WEAPON_PRIOR3[a];
6046 end;
6047 end;
6049 destructor TBot.Destroy();
6050 begin
6051 Dec(gNumBots);
6052 inherited Destroy();
6053 end;
6055 procedure TBot.Respawn(Silent: Boolean; Force: Boolean = False);
6056 begin
6057 inherited Respawn(Silent, Force);
6059 FAIFlags := nil;
6060 FSelectedWeapon := FCurrWeap;
6061 resetWeaponQueue();
6062 FTargetUID := 0;
6063 end;
6065 procedure TBot.UpdateCombat();
6066 type
6067 TTarget = record
6068 UID: Word;
6069 X, Y: Integer;
6070 Rect: TRectWH;
6071 cX, cY: Integer;
6072 Dist: Word;
6073 Line: Boolean;
6074 Visible: Boolean;
6075 IsPlayer: Boolean;
6076 end;
6078 TTargetRecord = array of TTarget;
6080 function Compare(a, b: TTarget): Integer;
6081 begin
6082 if a.Line and not b.Line then // A на линии огня
6083 Result := -1
6084 else
6085 if not a.Line and b.Line then // B на линии огня
6086 Result := 1
6087 else // И A, и B на линии или не на линии огня
6088 if (a.Line and b.Line) or ((not a.Line) and (not b.Line)) then
6089 begin
6090 if a.Dist > b.Dist then // B ближе
6091 Result := 1
6092 else // A ближе или равноудаленно с B
6093 Result := -1;
6094 end
6095 else // Странно -> A
6096 Result := -1;
6097 end;
6099 var
6100 a, x1, y1, x2, y2: Integer;
6101 targets: TTargetRecord;
6102 ammo: Word;
6103 Target, BestTarget: TTarget;
6104 firew, fireh: Integer;
6105 angle: SmallInt;
6106 mon: TMonster;
6107 pla, tpla: TPlayer;
6108 vsPlayer, vsMonster, ok: Boolean;
6111 function monsUpdate (mon: TMonster): Boolean;
6112 begin
6113 result := false; // don't stop
6114 if mon.alive and (mon.MonsterType <> MONSTER_BARREL) then
6115 begin
6116 if not TargetOnScreen(mon.Obj.X+mon.Obj.Rect.X, mon.Obj.Y+mon.Obj.Rect.Y) then exit;
6118 x2 := mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2);
6119 y2 := mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2);
6121 // Если монстр на экране и не прикрыт стеной
6122 if g_TraceVector(x1, y1, x2, y2) then
6123 begin
6124 // Добавляем к списку возможных целей
6125 SetLength(targets, Length(targets)+1);
6126 with targets[High(targets)] do
6127 begin
6128 UID := mon.UID;
6129 X := mon.Obj.X;
6130 Y := mon.Obj.Y;
6131 cX := x2;
6132 cY := y2;
6133 Rect := mon.Obj.Rect;
6134 Dist := g_PatchLength(x1, y1, x2, y2);
6135 Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6136 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6137 Visible := True;
6138 IsPlayer := False;
6139 end;
6140 end;
6141 end;
6142 end;
6144 begin
6145 vsPlayer := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER);
6146 vsMonster := LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER);
6148 // Если текущее оружие не то, что нужно, то меняем:
6149 if FCurrWeap <> FSelectedWeapon then
6150 NextWeapon();
6152 // Если нужно стрелять и нужное оружие, то нажать "Стрелять":
6153 if (GetAIFlag('NEEDFIRE') <> '') and (FCurrWeap = FSelectedWeapon) then
6154 begin
6155 RemoveAIFlag('NEEDFIRE');
6157 case FCurrWeap of
6158 WEAPON_PLASMA, WEAPON_SUPERPULEMET, WEAPON_CHAINGUN: PressKey(KEY_FIRE, 20);
6159 WEAPON_SAW, WEAPON_KASTET, WEAPON_FLAMETHROWER: PressKey(KEY_FIRE, 40);
6160 else PressKey(KEY_FIRE);
6161 end;
6162 end;
6164 // Координаты ствола:
6165 x1 := FObj.X + WEAPONPOINT[FDirection].X;
6166 y1 := FObj.Y + WEAPONPOINT[FDirection].Y;
6168 Target.UID := FTargetUID;
6170 ok := False;
6171 if Target.UID <> 0 then
6172 begin // Цель есть - настраиваем
6173 if (g_GetUIDType(Target.UID) = UID_PLAYER) and
6174 vsPlayer then
6175 begin // Игрок
6176 tpla := g_Player_Get(Target.UID);
6177 if tpla <> nil then
6178 with tpla do
6179 begin
6180 if (@FObj) <> nil then
6181 begin
6182 Target.X := FObj.X;
6183 Target.Y := FObj.Y;
6184 end;
6185 end;
6187 Target.cX := Target.X + PLAYER_RECT_CX;
6188 Target.cY := Target.Y + PLAYER_RECT_CY;
6189 Target.Rect := PLAYER_RECT;
6190 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6191 Target.Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6192 (y1-4 > Target.Y+PLAYER_RECT.Y);
6193 Target.IsPlayer := True;
6194 ok := True;
6195 end
6196 else
6197 if (g_GetUIDType(Target.UID) = UID_MONSTER) and
6198 vsMonster then
6199 begin // Монстр
6200 mon := g_Monsters_ByUID(Target.UID);
6201 if mon <> nil then
6202 begin
6203 Target.X := mon.Obj.X;
6204 Target.Y := mon.Obj.Y;
6206 Target.cX := Target.X + mon.Obj.Rect.X + (mon.Obj.Rect.Width div 2);
6207 Target.cY := Target.Y + mon.Obj.Rect.Y + (mon.Obj.Rect.Height div 2);
6208 Target.Rect := mon.Obj.Rect;
6209 Target.Visible := g_TraceVector(x1, y1, Target.cX, Target.cY);
6210 Target.Line := (y1+4 < Target.Y + mon.Obj.Rect.Y + mon.Obj.Rect.Height) and
6211 (y1-4 > Target.Y + mon.Obj.Rect.Y);
6212 Target.IsPlayer := False;
6213 ok := True;
6214 end;
6215 end;
6216 end;
6218 if not ok then
6219 begin // Цели нет - обнуляем
6220 Target.X := 0;
6221 Target.Y := 0;
6222 Target.cX := 0;
6223 Target.cY := 0;
6224 Target.Visible := False;
6225 Target.Line := False;
6226 Target.IsPlayer := False;
6227 end;
6229 targets := nil;
6231 // Если цель не видима или не на линии огня, то ищем все возможные цели:
6232 if (not Target.Line) or (not Target.Visible) then
6233 begin
6234 // Игроки:
6235 if vsPlayer then
6236 for a := 0 to High(gPlayers) do
6237 if (gPlayers[a] <> nil) and (gPlayers[a].alive) and
6238 (gPlayers[a].FUID <> FUID) and
6239 (not SameTeam(FUID, gPlayers[a].FUID)) and
6240 (not gPlayers[a].NoTarget) and
6241 (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
6242 begin
6243 if not TargetOnScreen(gPlayers[a].FObj.X + PLAYER_RECT.X,
6244 gPlayers[a].FObj.Y + PLAYER_RECT.Y) then
6245 Continue;
6247 x2 := gPlayers[a].FObj.X + PLAYER_RECT_CX;
6248 y2 := gPlayers[a].FObj.Y + PLAYER_RECT_CY;
6250 // Если игрок на экране и не прикрыт стеной:
6251 if g_TraceVector(x1, y1, x2, y2) then
6252 begin
6253 // Добавляем к списку возможных целей:
6254 SetLength(targets, Length(targets)+1);
6255 with targets[High(targets)] do
6256 begin
6257 UID := gPlayers[a].FUID;
6258 X := gPlayers[a].FObj.X;
6259 Y := gPlayers[a].FObj.Y;
6260 cX := x2;
6261 cY := y2;
6262 Rect := PLAYER_RECT;
6263 Dist := g_PatchLength(x1, y1, x2, y2);
6264 Line := (y1+4 < Target.Y+PLAYER_RECT.Y+PLAYER_RECT.Height) and
6265 (y1-4 > Target.Y+PLAYER_RECT.Y);
6266 Visible := True;
6267 IsPlayer := True;
6268 end;
6269 end;
6270 end;
6272 // Монстры:
6273 if vsMonster then g_Mons_ForEach(monsUpdate);
6274 end;
6276 // Если есть возможные цели:
6277 // (Выбираем лучшую, меняем оружие и бежим к ней/от нее)
6278 if targets <> nil then
6279 begin
6280 // Выбираем наилучшую цель:
6281 BestTarget := targets[0];
6282 if Length(targets) > 1 then
6283 for a := 1 to High(targets) do
6284 if Compare(BestTarget, targets[a]) = 1 then
6285 BestTarget := targets[a];
6287 // Если лучшая цель "виднее" текущей, то текущая := лучшая:
6288 if ((not Target.Visible) and BestTarget.Visible and (Target.UID <> BestTarget.UID)) or
6289 ((not Target.Line) and BestTarget.Line and BestTarget.Visible) then
6290 begin
6291 Target := BestTarget;
6293 if (Healthy() = 3) or ((Healthy() = 2)) then
6294 begin // Если здоровы - догоняем
6295 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6296 SetAIFlag('GORIGHT', '1');
6297 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6298 SetAIFlag('GOLEFT', '1');
6299 end
6300 else
6301 begin // Если побиты - убегаем
6302 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6303 SetAIFlag('GORIGHT', '1');
6304 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6305 SetAIFlag('GOLEFT', '1');
6306 end;
6308 // Выбираем оружие на основе расстояния и приоритетов:
6309 SelectWeapon(Abs(x1-Target.cX));
6310 end;
6311 end;
6313 // Если есть цель:
6314 // (Догоняем/убегаем, стреляем по направлению к цели)
6315 // (Если цель далеко, то хватит следить за ней)
6316 if Target.UID <> 0 then
6317 begin
6318 if not TargetOnScreen(Target.X + Target.Rect.X,
6319 Target.Y + Target.Rect.Y) then
6320 begin // Цель сбежала с "экрана"
6321 if (Healthy() = 3) or ((Healthy() = 2)) then
6322 begin // Если здоровы - догоняем
6323 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6324 SetAIFlag('GORIGHT', '1');
6325 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6326 SetAIFlag('GOLEFT', '1');
6327 end
6328 else
6329 begin // Если побиты - забываем о цели и убегаем
6330 Target.UID := 0;
6331 if ((RunDirection() = TDirection.D_LEFT) and (Target.X < FObj.X)) then
6332 SetAIFlag('GORIGHT', '1');
6333 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6334 SetAIFlag('GOLEFT', '1');
6335 end;
6336 end
6337 else
6338 begin // Цель пока на "экране"
6339 // Если цель не загорожена стеной, то отмечаем, когда ее видели:
6340 if g_TraceVector(x1, y1, Target.cX, Target.cY) then
6341 FLastVisible := gTime;
6342 // Если разница высот не велика, то догоняем:
6343 if (Abs(FObj.Y-Target.Y) <= 128) then
6344 begin
6345 if ((RunDirection() = TDirection.D_LEFT) and (Target.X > FObj.X)) then
6346 SetAIFlag('GORIGHT', '1');
6347 if ((RunDirection() = TDirection.D_RIGHT) and (Target.X < FObj.X)) then
6348 SetAIFlag('GOLEFT', '1');
6349 end;
6350 end;
6352 // Выбираем угол вверх:
6353 if FDirection = TDirection.D_LEFT then
6354 angle := ANGLE_LEFTUP
6355 else
6356 angle := ANGLE_RIGHTUP;
6358 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6359 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6361 // Если при угле вверх можно попасть в приблизительное положение цели:
6362 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6363 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128), //96
6364 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6365 Target.Rect.Width, Target.Rect.Height) and
6366 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6367 begin // то нужно стрелять вверх
6368 SetAIFlag('NEEDFIRE', '1');
6369 SetAIFlag('NEEDSEEUP', '1');
6370 end;
6372 // Выбираем угол вниз:
6373 if FDirection = TDirection.D_LEFT then
6374 angle := ANGLE_LEFTDOWN
6375 else
6376 angle := ANGLE_RIGHTDOWN;
6378 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6379 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6381 // Если при угле вниз можно попасть в приблизительное положение цели:
6382 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6383 Target.X+Target.Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6384 Target.Y+Target.Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6385 Target.Rect.Width, Target.Rect.Height) and
6386 g_TraceVector(x1, y1, Target.cX, Target.cY) then
6387 begin // то нужно стрелять вниз
6388 SetAIFlag('NEEDFIRE', '1');
6389 SetAIFlag('NEEDSEEDOWN', '1');
6390 end;
6392 // Если цель видно и она на такой же высоте:
6393 if Target.Visible and
6394 (y1+4 < Target.Y+Target.Rect.Y+Target.Rect.Height) and
6395 (y1-4 > Target.Y+Target.Rect.Y) then
6396 begin
6397 // Если идем в сторону цели, то надо стрелять:
6398 if ((FDirection = TDirection.D_LEFT) and (Target.X < FObj.X)) or
6399 ((FDirection = TDirection.D_RIGHT) and (Target.X > FObj.X)) then
6400 begin // то нужно стрелять вперед
6401 SetAIFlag('NEEDFIRE', '1');
6402 SetAIFlag('NEEDSEEDOWN', '');
6403 SetAIFlag('NEEDSEEUP', '');
6404 end;
6405 // Если цель в пределах "экрана" и сложность позволяет прыжки сближения:
6406 if Abs(FObj.X-Target.X) < Trunc(gPlayerScreenSize.X*0.75) then
6407 if GetRnd(FDifficult.CloseJump) then
6408 begin // то если повезет - прыгаем (особенно, если близко)
6409 if Abs(FObj.X-Target.X) < 128 then
6410 a := 4
6411 else
6412 a := 30;
6413 if Random(a) = 0 then
6414 SetAIFlag('NEEDJUMP', '1');
6415 end;
6416 end;
6418 // Если цель все еще есть:
6419 if Target.UID <> 0 then
6420 if gTime-FLastVisible > 2000 then // Если видели давно
6421 Target.UID := 0 // то забыть цель
6422 else // Если видели недавно
6423 begin // но цель убили
6424 if Target.IsPlayer then
6425 begin // Цель - игрок
6426 pla := g_Player_Get(Target.UID);
6427 if (pla = nil) or (not pla.alive) or pla.NoTarget or
6428 (pla.FMegaRulez[MR_INVIS] >= gTime) then
6429 Target.UID := 0; // то забыть цель
6430 end
6431 else
6432 begin // Цель - монстр
6433 mon := g_Monsters_ByUID(Target.UID);
6434 if (mon = nil) or (not mon.alive) then
6435 Target.UID := 0; // то забыть цель
6436 end;
6437 end;
6438 end; // if Target.UID <> 0
6440 FTargetUID := Target.UID;
6442 // Если возможных целей нет:
6443 // (Атака чего-нибудь слева или справа)
6444 if targets = nil then
6445 if GetAIFlag('ATTACKLEFT') <> '' then
6446 begin // Если нужно атаковать налево
6447 RemoveAIFlag('ATTACKLEFT');
6449 SetAIFlag('NEEDJUMP', '1');
6451 if RunDirection() = TDirection.D_RIGHT then
6452 begin // Идем не в ту сторону
6453 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6454 begin // Если здоровы, то, возможно, стреляем бежим влево и стреляем
6455 SetAIFlag('NEEDFIRE', '1');
6456 SetAIFlag('GOLEFT', '1');
6457 end;
6458 end
6459 else
6460 begin // Идем в нужную сторону
6461 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6462 SetAIFlag('NEEDFIRE', '1');
6463 if Healthy() <= 1 then // Побиты - убегаем
6464 SetAIFlag('GORIGHT', '1');
6465 end;
6466 end
6467 else
6468 if GetAIFlag('ATTACKRIGHT') <> '' then
6469 begin // Если нужно атаковать направо
6470 RemoveAIFlag('ATTACKRIGHT');
6472 SetAIFlag('NEEDJUMP', '1');
6474 if RunDirection() = TDirection.D_LEFT then
6475 begin // Идем не в ту сторону
6476 if (Healthy() > 1) and GetRnd(FDifficult.InvisFire) then
6477 begin // Если здоровы, то, возможно, бежим вправо и стреляем
6478 SetAIFlag('NEEDFIRE', '1');
6479 SetAIFlag('GORIGHT', '1');
6480 end;
6481 end
6482 else
6483 begin
6484 if GetRnd(FDifficult.InvisFire) then // Возможно, стреляем вслепую
6485 SetAIFlag('NEEDFIRE', '1');
6486 if Healthy() <= 1 then // Побиты - убегаем
6487 SetAIFlag('GOLEFT', '1');
6488 end;
6489 end;
6491 //HACK! (does it belongs there?)
6492 RealizeCurrentWeapon();
6494 // Если есть возможные цели:
6495 // (Стреляем по направлению к целям)
6496 if (targets <> nil) and (GetAIFlag('NEEDFIRE') <> '') then
6497 for a := 0 to High(targets) do
6498 begin
6499 // Если можем стрелять по диагонали:
6500 if GetRnd(FDifficult.DiagFire) then
6501 begin
6502 // Ищем цель сверху и стреляем, если есть:
6503 if FDirection = TDirection.D_LEFT then
6504 angle := ANGLE_LEFTUP
6505 else
6506 angle := ANGLE_RIGHTUP;
6508 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6509 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6511 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6512 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6513 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6514 targets[a].Rect.Width, targets[a].Rect.Height) and
6515 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6516 begin
6517 SetAIFlag('NEEDFIRE', '1');
6518 SetAIFlag('NEEDSEEUP', '1');
6519 end;
6521 // Ищем цель снизу и стреляем, если есть:
6522 if FDirection = TDirection.D_LEFT then
6523 angle := ANGLE_LEFTDOWN
6524 else
6525 angle := ANGLE_RIGHTDOWN;
6527 firew := Trunc(Cos(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6528 fireh := Trunc(Sin(DegToRad(-angle))*gPlayerScreenSize.X*0.6);
6530 if g_CollideLine(x1, y1, x1+firew, y1+fireh,
6531 targets[a].X+targets[a].Rect.X+GetInterval(FDifficult.DiagPrecision, 128),
6532 targets[a].Y+targets[a].Rect.Y+GetInterval(FDifficult.DiagPrecision, 128),
6533 targets[a].Rect.Width, targets[a].Rect.Height) and
6534 g_TraceVector(x1, y1, targets[a].cX, targets[a].cY) then
6535 begin
6536 SetAIFlag('NEEDFIRE', '1');
6537 SetAIFlag('NEEDSEEDOWN', '1');
6538 end;
6539 end;
6541 // Если цель "перед носом", то стреляем:
6542 if targets[a].Line and targets[a].Visible and
6543 (((FDirection = TDirection.D_LEFT) and (targets[a].X < FObj.X)) or
6544 ((FDirection = TDirection.D_RIGHT) and (targets[a].X > FObj.X))) then
6545 begin
6546 SetAIFlag('NEEDFIRE', '1');
6547 Break;
6548 end;
6549 end;
6551 // Если летит пуля, то, возможно, подпрыгиваем:
6552 if g_Weapon_Danger(FUID, FObj.X+PLAYER_RECT.X, FObj.Y+PLAYER_RECT.Y,
6553 PLAYER_RECT.Width, PLAYER_RECT.Height,
6554 40+GetInterval(FDifficult.Cover, 40)) then
6555 SetAIFlag('NEEDJUMP', '1');
6557 // Если кончились паторны, то нужно сменить оружие:
6558 ammo := GetAmmoByWeapon(FCurrWeap);
6559 if ((FCurrWeap = WEAPON_SHOTGUN2) and (ammo < 2)) or
6560 ((FCurrWeap = WEAPON_BFG) and (ammo < 40)) or
6561 (ammo = 0) then
6562 SetAIFlag('SELECTWEAPON', '1');
6564 // Если нужно сменить оружие, то выбираем нужное:
6565 if GetAIFlag('SELECTWEAPON') = '1' then
6566 begin
6567 SelectWeapon(-1);
6568 RemoveAIFlag('SELECTWEAPON');
6569 end;
6570 end;
6572 procedure TBot.Update();
6573 var
6574 EnableAI: Boolean;
6575 begin
6576 if not FAlive then
6577 begin // Respawn
6578 ReleaseKeys();
6579 PressKey(KEY_UP);
6580 end
6581 else
6582 begin
6583 EnableAI := True;
6585 // Проверяем, отключён ли AI ботов
6586 if (g_debug_BotAIOff = 1) and (Team = TEAM_RED) then
6587 EnableAI := False;
6588 if (g_debug_BotAIOff = 2) and (Team = TEAM_BLUE) then
6589 EnableAI := False;
6590 if g_debug_BotAIOff = 3 then
6591 EnableAI := False;
6593 if EnableAI then
6594 begin
6595 UpdateMove();
6596 UpdateCombat();
6597 end
6598 else
6599 begin
6600 RealizeCurrentWeapon();
6601 end;
6602 end;
6604 inherited Update();
6605 end;
6607 procedure TBot.ReleaseKey(Key: Byte);
6608 begin
6609 with FKeys[Key] do
6610 begin
6611 Pressed := False;
6612 Time := 0;
6613 end;
6614 end;
6616 function TBot.KeyPressed(Key: Word): Boolean;
6617 begin
6618 Result := FKeys[Key].Pressed;
6619 end;
6621 function TBot.GetAIFlag(aName: String20): String20;
6622 var
6623 a: Integer;
6624 begin
6625 Result := '';
6627 aName := LowerCase(aName);
6629 if FAIFlags <> nil then
6630 for a := 0 to High(FAIFlags) do
6631 if LowerCase(FAIFlags[a].Name) = aName then
6632 begin
6633 Result := FAIFlags[a].Value;
6634 Break;
6635 end;
6636 end;
6638 procedure TBot.RemoveAIFlag(aName: String20);
6639 var
6640 a, b: Integer;
6641 begin
6642 if FAIFlags = nil then Exit;
6644 aName := LowerCase(aName);
6646 for a := 0 to High(FAIFlags) do
6647 if LowerCase(FAIFlags[a].Name) = aName then
6648 begin
6649 if a <> High(FAIFlags) then
6650 for b := a to High(FAIFlags)-1 do
6651 FAIFlags[b] := FAIFlags[b+1];
6653 SetLength(FAIFlags, Length(FAIFlags)-1);
6654 Break;
6655 end;
6656 end;
6658 procedure TBot.SetAIFlag(aName, fValue: String20);
6659 var
6660 a: Integer;
6661 ok: Boolean;
6662 begin
6663 a := 0;
6664 ok := False;
6666 aName := LowerCase(aName);
6668 if FAIFlags <> nil then
6669 for a := 0 to High(FAIFlags) do
6670 if LowerCase(FAIFlags[a].Name) = aName then
6671 begin
6672 ok := True;
6673 Break;
6674 end;
6676 if ok then FAIFlags[a].Value := fValue
6677 else
6678 begin
6679 SetLength(FAIFlags, Length(FAIFlags)+1);
6680 with FAIFlags[High(FAIFlags)] do
6681 begin
6682 Name := aName;
6683 Value := fValue;
6684 end;
6685 end;
6686 end;
6688 procedure TBot.UpdateMove;
6690 procedure GoLeft(Time: Word = 1);
6691 begin
6692 ReleaseKey(KEY_LEFT);
6693 ReleaseKey(KEY_RIGHT);
6694 PressKey(KEY_LEFT, Time);
6695 SetDirection(TDirection.D_LEFT);
6696 end;
6698 procedure GoRight(Time: Word = 1);
6699 begin
6700 ReleaseKey(KEY_LEFT);
6701 ReleaseKey(KEY_RIGHT);
6702 PressKey(KEY_RIGHT, Time);
6703 SetDirection(TDirection.D_RIGHT);
6704 end;
6706 function Rnd(a: Word): Boolean;
6707 begin
6708 Result := Random(a) = 0;
6709 end;
6711 procedure Turn(Time: Word = 1200);
6712 begin
6713 if RunDirection() = TDirection.D_LEFT then GoRight(Time) else GoLeft(Time);
6714 end;
6716 procedure Stop();
6717 begin
6718 ReleaseKey(KEY_LEFT);
6719 ReleaseKey(KEY_RIGHT);
6720 end;
6722 function CanRunLeft(): Boolean;
6723 begin
6724 Result := not CollideLevel(-1, 0);
6725 end;
6727 function CanRunRight(): Boolean;
6728 begin
6729 Result := not CollideLevel(1, 0);
6730 end;
6732 function CanRun(): Boolean;
6733 begin
6734 if RunDirection() = TDirection.D_LEFT then Result := CanRunLeft() else Result := CanRunRight();
6735 end;
6737 procedure Jump(Time: Word = 30);
6738 begin
6739 PressKey(KEY_JUMP, Time);
6740 end;
6742 function NearHole(): Boolean;
6743 var
6744 x, sx: Integer;
6745 begin
6746 { TODO 5 : Лестницы }
6747 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6748 for x := 1 to PLAYER_RECT.Width do
6749 if (not StayOnStep(x*sx, 0)) and
6750 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6751 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6752 begin
6753 Result := True;
6754 Exit;
6755 end;
6757 Result := False;
6758 end;
6760 function BorderHole(): Boolean;
6761 var
6762 x, sx, xx: Integer;
6763 begin
6764 { TODO 5 : Лестницы }
6765 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6766 for x := 1 to PLAYER_RECT.Width do
6767 if (not StayOnStep(x*sx, 0)) and
6768 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6769 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6770 begin
6771 for xx := x to x+32 do
6772 if CollideLevel(xx*sx, PLAYER_RECT.Height) then
6773 begin
6774 Result := True;
6775 Exit;
6776 end;
6777 end;
6779 Result := False;
6780 end;
6782 function NearDeepHole(): Boolean;
6783 var
6784 x, sx, y: Integer;
6785 begin
6786 Result := False;
6788 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6789 y := 3;
6791 for x := 1 to PLAYER_RECT.Width do
6792 if (not StayOnStep(x*sx, 0)) and
6793 (not CollideLevel(x*sx, PLAYER_RECT.Height)) and
6794 (not CollideLevel(x*sx, PLAYER_RECT.Height*2)) then
6795 begin
6796 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6797 begin
6798 if CollideLevel(x*sx, PLAYER_RECT.Height*y) then Exit;
6799 y := y+1;
6800 end;
6802 Result := True;
6803 end else Result := False;
6804 end;
6806 function OverDeepHole(): Boolean;
6807 var
6808 y: Integer;
6809 begin
6810 Result := False;
6812 y := 1;
6813 while FObj.Y+y*PLAYER_RECT.Height < gMapInfo.Height do
6814 begin
6815 if CollideLevel(0, PLAYER_RECT.Height*y) then Exit;
6816 y := y+1;
6817 end;
6819 Result := True;
6820 end;
6822 function OnGround(): Boolean;
6823 begin
6824 Result := StayOnStep(0, 0) or CollideLevel(0, 1);
6825 end;
6827 function OnLadder(): Boolean;
6828 begin
6829 Result := FullInStep(0, 0);
6830 end;
6832 function BelowLadder(): Boolean;
6833 begin
6834 Result := (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) and
6835 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6836 (FullInStep(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) and
6837 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6838 end;
6840 function BelowLiftUp(): Boolean;
6841 begin
6842 Result := ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height) = -1) and
6843 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -PLAYER_RECT.Height)) or
6844 ((FullInLift(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP) = -1) and
6845 not CollideLevel(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*(PLAYER_RECT.Width div 2), -BOT_MAXJUMP));
6846 end;
6848 function OnTopLift(): Boolean;
6849 begin
6850 Result := (FullInLift(0, 0) = -1) and (FullInLift(0, -32) = 0);
6851 end;
6853 function CanJumpOver(): Boolean;
6854 var
6855 sx, y: Integer;
6856 begin
6857 sx := IfThen(RunDirection() = TDirection.D_LEFT, -1, 1);
6859 Result := False;
6861 if not CollideLevel(sx, 0) then Exit;
6863 for y := 1 to BOT_MAXJUMP do
6864 if CollideLevel(0, -y) then Exit else
6865 if not CollideLevel(sx, -y) then
6866 begin
6867 Result := True;
6868 Exit;
6869 end;
6870 end;
6872 function CanJumpUp(Dist: ShortInt): Boolean;
6873 var
6874 y, yy: Integer;
6875 c: Boolean;
6876 begin
6877 Result := False;
6879 if CollideLevel(Dist, 0) then Exit;
6881 c := False;
6882 for y := 0 to BOT_MAXJUMP do
6883 if CollideLevel(Dist, -y) then
6884 begin
6885 c := True;
6886 Break;
6887 end;
6889 if not c then Exit;
6891 c := False;
6892 for yy := y+1 to BOT_MAXJUMP do
6893 if not CollideLevel(Dist, -yy) then
6894 begin
6895 c := True;
6896 Break;
6897 end;
6899 if not c then Exit;
6901 c := False;
6902 for y := 0 to BOT_MAXJUMP do
6903 if CollideLevel(0, -y) then
6904 begin
6905 c := True;
6906 Break;
6907 end;
6909 if c then Exit;
6911 if y < yy then Exit;
6913 Result := True;
6914 end;
6916 function IsSafeTrigger(): Boolean;
6917 var
6918 a: Integer;
6919 begin
6920 Result := True;
6921 if gTriggers = nil then
6922 Exit;
6923 for a := 0 to High(gTriggers) do
6924 if Collide(gTriggers[a].X,
6925 gTriggers[a].Y,
6926 gTriggers[a].Width,
6927 gTriggers[a].Height) and
6928 (gTriggers[a].TriggerType in [TRIGGER_EXIT, TRIGGER_CLOSEDOOR,
6929 TRIGGER_CLOSETRAP, TRIGGER_TRAP,
6930 TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF,
6931 TRIGGER_ONOFF, TRIGGER_SPAWNMONSTER,
6932 TRIGGER_DAMAGE, TRIGGER_SHOT]) then
6933 Result := False;
6934 end;
6936 begin
6937 // Возможно, нажимаем кнопку:
6938 if Rnd(16) and IsSafeTrigger() then
6939 PressKey(KEY_OPEN);
6941 // Если под лифтом или ступеньками, то, возможно, прыгаем:
6942 if OnLadder() or ((BelowLadder() or BelowLiftUp()) and Rnd(8)) then
6943 begin
6944 ReleaseKey(KEY_LEFT);
6945 ReleaseKey(KEY_RIGHT);
6946 Jump();
6947 end;
6949 // Идем влево, если надо было:
6950 if GetAIFlag('GOLEFT') <> '' then
6951 begin
6952 RemoveAIFlag('GOLEFT');
6953 if CanRunLeft() then
6954 GoLeft(360);
6955 end;
6957 // Идем вправо, если надо было:
6958 if GetAIFlag('GORIGHT') <> '' then
6959 begin
6960 RemoveAIFlag('GORIGHT');
6961 if CanRunRight() then
6962 GoRight(360);
6963 end;
6965 // Если вылетели за карту, то пробуем вернуться:
6966 if FObj.X < -32 then
6967 GoRight(360)
6968 else
6969 if FObj.X+32 > gMapInfo.Width then
6970 GoLeft(360);
6972 // Прыгаем, если надо было:
6973 if GetAIFlag('NEEDJUMP') <> '' then
6974 begin
6975 Jump(0);
6976 RemoveAIFlag('NEEDJUMP');
6977 end;
6979 // Смотрим вверх, если надо было:
6980 if GetAIFlag('NEEDSEEUP') <> '' then
6981 begin
6982 ReleaseKey(KEY_UP);
6983 ReleaseKey(KEY_DOWN);
6984 PressKey(KEY_UP, 20);
6985 RemoveAIFlag('NEEDSEEUP');
6986 end;
6988 // Смотрим вниз, если надо было:
6989 if GetAIFlag('NEEDSEEDOWN') <> '' then
6990 begin
6991 ReleaseKey(KEY_UP);
6992 ReleaseKey(KEY_DOWN);
6993 PressKey(KEY_DOWN, 20);
6994 RemoveAIFlag('NEEDSEEDOWN');
6995 end;
6997 // Если нужно было в дыру и мы не на земле, то покорно летим:
6998 if GetAIFlag('GOINHOLE') <> '' then
6999 if not OnGround() then
7000 begin
7001 ReleaseKey(KEY_LEFT);
7002 ReleaseKey(KEY_RIGHT);
7003 RemoveAIFlag('GOINHOLE');
7004 SetAIFlag('FALLINHOLE', '1');
7005 end;
7007 // Если падали и достигли земли, то хватит падать:
7008 if GetAIFlag('FALLINHOLE') <> '' then
7009 if OnGround() then
7010 RemoveAIFlag('FALLINHOLE');
7012 // Если летели прямо и сейчас не на лестнице или на вершине лифта, то отходим в сторону:
7013 if not (KeyPressed(KEY_LEFT) or KeyPressed(KEY_RIGHT)) then
7014 if GetAIFlag('FALLINHOLE') = '' then
7015 if (not OnLadder()) or (FObj.Vel.Y >= 0) or (OnTopLift()) then
7016 if Rnd(2) then
7017 GoLeft(360)
7018 else
7019 GoRight(360);
7021 // Если на земле и можно подпрыгнуть, то, возможно, прыгаем:
7022 if OnGround() and
7023 CanJumpUp(IfThen(RunDirection() = TDirection.D_LEFT, -1, 1)*32) and
7024 Rnd(8) then
7025 Jump();
7027 // Если на земле и возле дыры (глубина > 2 ростов игрока):
7028 if OnGround() and NearHole() then
7029 if NearDeepHole() then // Если это бездна
7030 case Random(6) of
7031 0..3: Turn(); // Бежим обратно
7032 4: Jump(); // Прыгаем
7033 5: begin // Прыгаем обратно
7034 Turn();
7035 Jump();
7036 end;
7037 end
7038 else // Это не бездна и мы еще не летим туда
7039 if GetAIFlag('GOINHOLE') = '' then
7040 case Random(6) of
7041 0: Turn(); // Не нужно туда
7042 1: Jump(); // Вдруг повезет - прыгаем
7043 else // Если яма с границей, то при случае можно туда прыгнуть
7044 if BorderHole() then
7045 SetAIFlag('GOINHOLE', '1');
7046 end;
7048 // Если на земле, но некуда идти:
7049 if (not CanRun()) and OnGround() then
7050 begin
7051 // Если мы на лестнице или можно перепрыгнуть, то прыгаем:
7052 if CanJumpOver() or OnLadder() then
7053 Jump()
7054 else // иначе попытаемся в другую сторону
7055 if Random(2) = 0 then
7056 begin
7057 if IsSafeTrigger() then
7058 PressKey(KEY_OPEN);
7059 end else
7060 Turn();
7061 end;
7063 // Осталось мало воздуха:
7064 if FAir < 36 * 2 then
7065 Jump(20);
7067 // Выбираемся из кислоты, если нет костюма, обожглись, или мало здоровья:
7068 if (FMegaRulez[MR_SUIT] < gTime) and ((FLastHit = HIT_ACID) or (Healthy() <= 1)) then
7069 if BodyInAcid(0, 0) then
7070 Jump();
7071 end;
7073 function TBot.FullInStep(XInc, YInc: Integer): Boolean;
7074 begin
7075 Result := g_Map_CollidePanel(FObj.X+PLAYER_RECT.X+XInc, FObj.Y+PLAYER_RECT.Y+YInc,
7076 PLAYER_RECT.Width, PLAYER_RECT.Height, PANEL_STEP, False);
7077 end;
7079 {function TBot.NeedItem(Item: Byte): Byte;
7080 begin
7081 Result := 4;
7082 end;}
7084 procedure TBot.SelectWeapon(Dist: Integer);
7085 var
7086 a: Integer;
7088 function HaveAmmo(weapon: Byte): Boolean;
7089 begin
7090 case weapon of
7091 WEAPON_PISTOL: Result := FAmmo[A_BULLETS] >= 1;
7092 WEAPON_SHOTGUN1: Result := FAmmo[A_SHELLS] >= 1;
7093 WEAPON_SHOTGUN2: Result := FAmmo[A_SHELLS] >= 2;
7094 WEAPON_CHAINGUN: Result := FAmmo[A_BULLETS] >= 10;
7095 WEAPON_ROCKETLAUNCHER: Result := FAmmo[A_ROCKETS] >= 1;
7096 WEAPON_PLASMA: Result := FAmmo[A_CELLS] >= 10;
7097 WEAPON_BFG: Result := FAmmo[A_CELLS] >= 40;
7098 WEAPON_SUPERPULEMET: Result := FAmmo[A_SHELLS] >= 1;
7099 WEAPON_FLAMETHROWER: Result := FAmmo[A_FUEL] >= 1;
7100 else Result := True;
7101 end;
7102 end;
7104 begin
7105 if Dist = -1 then Dist := BOT_LONGDIST;
7107 if Dist > BOT_LONGDIST then
7108 begin // Дальний бой
7109 for a := 0 to 9 do
7110 if FWeapon[FDifficult.WeaponPrior[a]] and HaveAmmo(FDifficult.WeaponPrior[a]) then
7111 begin
7112 FSelectedWeapon := FDifficult.WeaponPrior[a];
7113 Break;
7114 end;
7115 end
7116 else //if Dist > BOT_UNSAFEDIST then
7117 begin // Ближний бой
7118 for a := 0 to 9 do
7119 if FWeapon[FDifficult.CloseWeaponPrior[a]] and HaveAmmo(FDifficult.CloseWeaponPrior[a]) then
7120 begin
7121 FSelectedWeapon := FDifficult.CloseWeaponPrior[a];
7122 Break;
7123 end;
7124 end;
7125 { else
7126 begin
7127 for a := 0 to 9 do
7128 if FWeapon[FDifficult.SafeWeaponPrior[a]] and HaveAmmo(FDifficult.SafeWeaponPrior[a]) then
7129 begin
7130 FSelectedWeapon := FDifficult.SafeWeaponPrior[a];
7131 Break;
7132 end;
7133 end;}
7134 end;
7136 function TBot.PickItem(ItemType: Byte; force: Boolean; var remove: Boolean): Boolean;
7137 begin
7138 Result := inherited PickItem(ItemType, force, remove);
7140 if Result then SetAIFlag('SELECTWEAPON', '1');
7141 end;
7143 function TBot.Heal(value: Word; Soft: Boolean): Boolean;
7144 begin
7145 Result := inherited Heal(value, Soft);
7146 end;
7148 function TBot.Healthy(): Byte;
7149 begin
7150 if FMegaRulez[MR_INVUL] >= gTime then Result := 3
7151 else if (FHealth > 80) or ((FHealth > 50) and (FArmor > 20)) then Result := 3
7152 else if (FHealth > 50) then Result := 2
7153 else if (FHealth > 20) then Result := 1
7154 else Result := 0;
7155 end;
7157 function TBot.TargetOnScreen(TX, TY: Integer): Boolean;
7158 begin
7159 Result := (Abs(FObj.X-TX) <= Trunc(gPlayerScreenSize.X*0.6)) and
7160 (Abs(FObj.Y-TY) <= Trunc(gPlayerScreenSize.Y*0.6));
7161 end;
7163 procedure TBot.OnDamage(Angle: SmallInt);
7164 var
7165 pla: TPlayer;
7166 mon: TMonster;
7167 ok: Boolean;
7168 begin
7169 inherited;
7171 if (Angle = 0) or (Angle = 180) then
7172 begin
7173 ok := False;
7174 if (g_GetUIDType(FLastSpawnerUID) = UID_PLAYER) and
7175 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSPLAYER) then
7176 begin // Игрок
7177 pla := g_Player_Get(FLastSpawnerUID);
7178 ok := not TargetOnScreen(pla.FObj.X + PLAYER_RECT.X,
7179 pla.FObj.Y + PLAYER_RECT.Y);
7180 end
7181 else
7182 if (g_GetUIDType(FLastSpawnerUID) = UID_MONSTER) and
7183 LongBool(gGameSettings.Options and GAME_OPTION_BOTVSMONSTER) then
7184 begin // Монстр
7185 mon := g_Monsters_ByUID(FLastSpawnerUID);
7186 ok := not TargetOnScreen(mon.Obj.X + mon.Obj.Rect.X,
7187 mon.Obj.Y + mon.Obj.Rect.Y);
7188 end;
7190 if ok then
7191 if Angle = 0 then
7192 SetAIFlag('ATTACKLEFT', '1')
7193 else
7194 SetAIFlag('ATTACKRIGHT', '1');
7195 end;
7196 end;
7198 function TBot.RunDirection(): TDirection;
7199 begin
7200 if Abs(Vel.X) >= 1 then
7201 begin
7202 if Vel.X > 0 then Result := TDirection.D_RIGHT else Result := TDirection.D_LEFT;
7203 end else
7204 Result := FDirection;
7205 end;
7207 function TBot.GetRnd(a: Byte): Boolean;
7208 begin
7209 if a = 0 then Result := False
7210 else if a = 255 then Result := True
7211 else Result := Random(256) > 255-a;
7212 end;
7214 function TBot.GetInterval(a: Byte; radius: SmallInt): SmallInt;
7215 begin
7216 Result := Round((255-a)/255*radius*(Random(2)-1));
7217 end;
7220 procedure TDifficult.save (st: TStream);
7221 begin
7222 utils.writeInt(st, Byte(DiagFire));
7223 utils.writeInt(st, Byte(InvisFire));
7224 utils.writeInt(st, Byte(DiagPrecision));
7225 utils.writeInt(st, Byte(FlyPrecision));
7226 utils.writeInt(st, Byte(Cover));
7227 utils.writeInt(st, Byte(CloseJump));
7228 st.WriteBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7229 st.WriteBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7230 end;
7232 procedure TDifficult.load (st: TStream);
7233 begin
7234 DiagFire := utils.readByte(st);
7235 InvisFire := utils.readByte(st);
7236 DiagPrecision := utils.readByte(st);
7237 FlyPrecision := utils.readByte(st);
7238 Cover := utils.readByte(st);
7239 CloseJump := utils.readByte(st);
7240 st.ReadBuffer(WeaponPrior[Low(WeaponPrior)], sizeof(WeaponPrior));
7241 st.ReadBuffer(CloseWeaponPrior[Low(CloseWeaponPrior)], sizeof(CloseWeaponPrior));
7242 end;
7245 procedure TBot.SaveState (st: TStream);
7246 var
7247 i: Integer;
7248 dw: Integer;
7249 begin
7250 inherited SaveState(st);
7251 utils.writeSign(st, 'BOT0');
7252 // Выбранное оружие
7253 utils.writeInt(st, Byte(FSelectedWeapon));
7254 // UID цели
7255 utils.writeInt(st, Word(FTargetUID));
7256 // Время потери цели
7257 utils.writeInt(st, LongWord(FLastVisible));
7258 // Количество флагов ИИ
7259 dw := Length(FAIFlags);
7260 utils.writeInt(st, LongInt(dw));
7261 // Флаги ИИ
7262 for i := 0 to dw-1 do
7263 begin
7264 utils.writeStr(st, FAIFlags[i].Name, 20);
7265 utils.writeStr(st, FAIFlags[i].Value, 20);
7266 end;
7267 // Настройки сложности
7268 FDifficult.save(st);
7269 end;
7272 procedure TBot.LoadState (st: TStream);
7273 var
7274 i: Integer;
7275 dw: Integer;
7276 begin
7277 inherited LoadState(st);
7278 if not utils.checkSign(st, 'BOT0') then raise XStreamError.Create('invalid bot signature');
7279 // Выбранное оружие
7280 FSelectedWeapon := utils.readByte(st);
7281 // UID цели
7282 FTargetUID := utils.readWord(st);
7283 // Время потери цели
7284 FLastVisible := utils.readLongWord(st);
7285 // Количество флагов ИИ
7286 dw := utils.readLongInt(st);
7287 if (dw < 0) or (dw > 16384) then raise XStreamError.Create('invalid number of bot AI flags');
7288 SetLength(FAIFlags, dw);
7289 // Флаги ИИ
7290 for i := 0 to dw-1 do
7291 begin
7292 FAIFlags[i].Name := utils.readStr(st, 20);
7293 FAIFlags[i].Value := utils.readStr(st, 20);
7294 end;
7295 // Настройки сложности
7296 FDifficult.load(st);
7297 end;
7300 begin
7301 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');
7302 conRegVar('player_indicator_style', @gPlayerIndicatorStyle, 'Visual appearance of indicator', 'Visual appearance of indicator');
7303 end.