DEADSOFTWARE

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