1+ /**
2+ * @license MIT
3+ * @author JaylyMC
4+ */
5+ import { EntityHealthComponent , world , Player } from "mojang-minecraft" ;
6+
7+ /**
8+ * Contains information related to an player death.
9+ */
10+ export class PlayerDeathEvent {
11+ /**
12+ * @param {Player } player
13+ */
14+ constructor ( player ) {
15+ this . player = player ;
16+ } ;
17+ } ;
18+
19+ /**
20+ * Manages callbacks that are connected to when an player dies.
21+ */
22+ export class PlayerDeathEventSignal {
23+ /**
24+ * Subscribe
25+ * @param {(arg: PlayerDeathEvent) => void } arg
26+ * @return {(arg: PlayerDeathEvent) => void }
27+ */
28+ subscribe ( arg ) {
29+ arg [ "playerDeath" ] = true ;
30+ /**
31+ * @type {Player[] }
32+ */
33+ const deadPlayers = [ ] ;
34+ let callback = world . events . tick . subscribe ( ( ) => {
35+ for ( let player of world . getPlayers ( ) ) {
36+ if ( ! player . hasComponent ( "health" ) ) return ;
37+ /**
38+ * @type {EntityHealthComponent }
39+ */
40+ // @ts -ignore
41+ let health = player . getComponent ( "health" ) ;
42+ if ( health . current === 0 && arg [ "playerDeath" ] === true ) {
43+ const playerIndex = deadPlayers . findIndex ( pl => pl . name === player . name ) ;
44+ if ( playerIndex < 0 ) {
45+ arg ( new PlayerDeathEvent ( player ) ) ;
46+ deadPlayers . push ( player ) ;
47+ let playerDeathCallback = world . events . tick . subscribe ( ( ) => {
48+ if ( health . current > 0 ) {
49+ deadPlayers . splice ( playerIndex , 1 ) ;
50+ world . events . tick . unsubscribe ( playerDeathCallback ) ;
51+ } ;
52+ } ) ;
53+ }
54+ } else if ( arg [ "playerDeath" ] === false ) {
55+ world . events . tick . unsubscribe ( callback ) ;
56+ } ;
57+ }
58+ } ) ;
59+
60+ return arg ;
61+ } ;
62+
63+ /**
64+ * Unsubscribe
65+ * @param {(arg: PlayerDeathEvent) => void } arg
66+ * @return {void }
67+ */
68+ unsubscribe ( arg ) {
69+ arg [ "playerDeath" ] = false ;
70+ } ;
71+ } ;
0 commit comments