class GamepadController {
  constructor(config = {}) {
    this.config  = {
      buttonMapping: {},
      axisMapping: {},
      ...config 
    };
    this.gamepad  = null;
    this.listeners  = {};
 
    // 初始化默认按键映射 
    Object.assign(this.config.buttonMapping,  {
      0: 'A',
      1: 'B',
      2: 'X',
      3: 'Y',
      // 其他默认映射 
    });
 
    // 初始化默认摇杆映射 
    Object.assign(this.config.axisMapping,  {
      0: 'leftX',
      1: 'leftY',
      2: 'rightX',
      3: 'rightY',
      // 其他默认映射 
    });
  }
 
  connect() {
    window.addEventListener('gamepadconnected',  (e) => {
      this.gamepad  = navigator.getGamepads()[e.gamepad.index]; 
      this.triggerEvent('connected'); 
    });
  }
 
  disconnect() {
    window.removeEventListener('gamepadconnected',  this.handleConnect); 
    this.gamepad  = null;
    this.triggerEvent('disconnected'); 
  }
 
  // 手动获取手柄数据的方法 
  pollGamepad() {
    if (!this.gamepad)  return;
 
    // 处理摇杆数据 
    const axesData = this.gamepad.axes; 
    const axisEvents = {};
    Object.entries(this.config.axisMapping).forEach(([index,  name]) => {
      axisEvents[name] = axesData[index];
    });
    this.triggerEvent('axisChange',  axisEvents);
 
    // 处理按键事件 
    const buttons = this.gamepad.buttons; 
    buttons.forEach((btn,  index) => {
      if (btn.value  === 1 && this.config.buttonMapping[index])  {
        const keyName = this.config.buttonMapping[index]; 
        this.triggerEvent('buttonPress',  { keyName, index });
      }
    });
  }
 
  addEventListener(type, callback) {
    if (!this.listeners[type])  this.listeners[type]  = [];
    this.listeners[type].push(callback); 
  }
 
  triggerEvent(type, data = {}) {
    if (this.listeners[type])  {
      this.listeners[type].forEach(callback  => callback(data));
    }
  }
}
 
// 导出模块 
if (typeof module !== 'undefined' && module.exports)  {
  module.exports  = GamepadController;
} else if (typeof define === 'function' && define.amd)  {
  define([], () => GamepadController);
} else {
  window.GamepadController = GamepadController;
}