单位源码

// 定义游戏单位状态
enum UnitStatus {
US_1 = 1 << 1,
US_2 = 1 << 2,
US_3 = 1 << 3,
US_4 = 1 << 4,
}

/**
* 单位类
*
* @class Unit
*/
class Unit {
unitFlag: number = 0; // 当前单位的状态标识

/**
* 设置当前状态位
*
* @param {UnitStatus} flag
* @memberof Unit
*/
setFlag(flag: UnitStatus) {
this.unitFlag = this.unitFlag | flag;
}

/**
* 是否有当前状态位
*
* @param {UnitStatus} flag
* @returns {boolean}
* @memberof Unit
*/
hasFlag(flag: UnitStatus) : boolean {
return !!(this.unitFlag & flag);
}

/**
* 清除当前状态位
*
* @param {UnitStatus} flag
* @memberof Unit
*/
clearFlag(flag: UnitStatus) {
this.unitFlag = this.unitFlag & (~flag);
}

/**
* 重置当前状态位
*
* @memberof Unit
*/
resetFlag() {
this.unitFlag = 0;
}
}

测试

let unit = new Unit();
console.log('add UnitStatus.US_1 UnitStatus.US_2');
unit.setFlag(UnitStatus.US_1 | UnitStatus.US_2);
console.log('unit has UnitStatus.US_1?', unit.hasFlag(UnitStatus.US_1));
console.log('unit has UnitStatus.US_2?', unit.hasFlag(UnitStatus.US_2));
console.log('unit has UnitStatus.US_3?', unit.hasFlag(UnitStatus.US_3));
console.log('unit has UnitStatus.US_4?', unit.hasFlag(UnitStatus.US_4));
console.log('remove UnitStatus.US_1');
unit.clearFlag(UnitStatus.US_1);
console.log('unit has UnitStatus.US_1?', unit.hasFlag(UnitStatus.US_1));
console.log('unit has UnitStatus.US_2?', unit.hasFlag(UnitStatus.US_2));
console.log('unit has UnitStatus.US_3?', unit.hasFlag(UnitStatus.US_3));
console.log('unit has UnitStatus.US_4?', unit.hasFlag(UnitStatus.US_4));
console.log('reset unit status');
unit.resetFlag();
console.log('unit has UnitStatus.US_1?', unit.hasFlag(UnitStatus.US_1));
console.log('unit has UnitStatus.US_2?', unit.hasFlag(UnitStatus.US_2));
console.log('unit has UnitStatus.US_3?', unit.hasFlag(UnitStatus.US_3));
console.log('unit has UnitStatus.US_4?', unit.hasFlag(UnitStatus.US_4));

输出结果

add UnitStatus.US_1 UnitStatus.US_2
unit has UnitStatus.US_1? true
unit has UnitStatus.US_2? true
unit has UnitStatus.US_3? false
unit has UnitStatus.US_4? false
remove UnitStatus.US_1
unit has UnitStatus.US_1? false
unit has UnitStatus.US_2? true
unit has UnitStatus.US_3? false
unit has UnitStatus.US_4? false
reset unit status
unit has UnitStatus.US_1? false
unit has UnitStatus.US_2? false
unit has UnitStatus.US_3? false
unit has UnitStatus.US_4? false