File size: 1,634 Bytes
1446538
805e540
f676ff2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// const SERVER_URL = import.meta.env.VITE_SERVER_URL || window.location.origin;
const socket = io();
let myId = null;
let serverState = {
  players: [],
  pickups: [],
  orbitClock: 0,
};
let statusCallback = null;
let connected = false;
let pendingJoinName = null;

function updateStatus(text) {
  if (typeof statusCallback === 'function') {
    statusCallback(text);
  }
}

let gameOverCallback = null;

socket.on('connect', () => {
  connected = true;
  updateStatus('Kết nối tới server');
  if (pendingJoinName) {
    socket.emit('join', pendingJoinName);
  }
});

socket.on('connect_error', () => {
  updateStatus('Không thể kết nối server');
});

socket.on('disconnect', () => {
  updateStatus('Đã ngắt kết nối');
});

socket.on('joined', (data) => {
  myId = data.id;
  updateStatus('Đã vào game');
});

socket.on('hit', (payload) => {
  if (payload && typeof payload === 'object') {
    serverState.lastHit = payload;
  }
});

socket.on('state', (state) => {
  serverState = state;
});

socket.on('gameOver', (data) => {
  if (typeof gameOverCallback === 'function') {
    gameOverCallback(data);
  }
});

export function initSocket(statusFn) {
  statusCallback = statusFn;
  return {
    joinGame: (name) => {
      pendingJoinName = name;
      if (connected) {
        socket.emit('join', pendingJoinName);
      }
    },
    emitInput: ({ x, y, boost }) => {
      if (!myId) return;
      socket.emit('input', { x, y, boost });
    },
    getState: () => serverState,
    getMyId: () => myId,
    isConnected: () => connected,
    onGameOver: (cb) => {
      gameOverCallback = cb;
    },
  };
}