dao-game / react-multiplayer / files / src / game / remote-game.ts
Branch react-multiplayer · default branch · all branches
remote-game.ts
c3c52daf 2022-03-18 Pavel Safronov | 1 | import Peer, { PeerJSOption } from 'peerjs'; |
1e41e9b4 2022-03-18 Pavel Safronov | 2 | import { LocalGame } from './local-game'; |
38c7e27c 2022-03-22 Pavel Safronov | 3 | import { showModal } from '../utils/modal'; |
| 4 | import { useSessionStorage } from '../utils/storage'; | |
| 5 | import { showSnackbar } from "../utils/snackbar"; | |
| 6 | import { Move, MoveResult } from './game'; | |
| 7 | import { Coord } from './coord'; | |
| 8 | import { generateHash } from '../utils/hashing'; | |
| 9 | import { delay } from '../utils/delay'; | |
| 10 | import { copyToClipboard } from '../utils/clipboard'; | |
db09721d 2022-03-22 Pavel Safronov | 11 | import { detect } from 'detect-browser'; |
1e41e9b4 2022-03-18 Pavel Safronov | 12 | |
| 13 | interface LocalData { | |
417dc266 2022-03-23 Pavel Safronov | 14 | id?: string; |
| 15 | peerId?: string; | |
1e41e9b4 2022-03-18 Pavel Safronov | 16 | } |
7e7f0490 2022-03-18 Pavel Safronov | 17 | interface Pos { |
f2c94061 2022-03-21 Pavel Safronov | 18 | x: number; |
| 19 | y: number; | |
7e7f0490 2022-03-18 Pavel Safronov | 20 | } |
| 21 | interface PeerData { | |
f2c94061 2022-03-21 Pavel Safronov | 22 | mousePos?: Pos; |
| 23 | move?: Move; | |
7e7f0490 2022-03-18 Pavel Safronov | 24 | } |
5805825c 2022-03-21 Pavel Safronov | 25 | const peerOptions: PeerJSOption = { debug: 0 }; |
47dfe48a 2022-03-20 Pavel Safronov | 26 | const { getter: getData, setter: setData } = useSessionStorage<LocalData>('dao-game', { id: undefined, peerId: undefined }); |
417dc266 2022-03-23 Pavel Safronov | 27 | const otherMouseElement = document.getElementById('other-mouse')!; |
| 28 | const shareContainer = document.getElementById('share-container')!; | |
| 29 | const shareLinkButton = document.getElementById('share-link')!; | |
47dfe48a 2022-03-20 Pavel Safronov | 30 | const minString = (a: string, b: string): string => (a < b ? a : b); |
| 31 | const maxString = (a: string, b: string): string => (a > b ? a : b); | |
| 32 | const getFirstPlayerId = (playerId1: string, playerId2: string) => { | |
f2c94061 2022-03-21 Pavel Safronov | 33 | const hash1 = generateHash(playerId1); |
| 34 | const hash2 = generateHash(playerId2); | |
| 35 | const prod = hash1 * hash2; | |
| 36 | const isEven = prod % 2 == 0; | |
| 37 | const id = isEven ? minString(playerId1, playerId2) : maxString(playerId1, playerId2); | |
| 38 | return id; | |
47dfe48a 2022-03-20 Pavel Safronov | 39 | }; |
5805825c 2022-03-21 Pavel Safronov | 40 | const dropFileExtension = (path: string) => { |
| 41 | const lastSlashIndex = path.lastIndexOf('/'); | |
| 42 | const dirName = path.substring(0, lastSlashIndex); | |
| 43 | return dirName; | |
| 44 | } | |
417dc266 2022-03-23 Pavel Safronov | 45 | const showMessageAndLeave = async (title: string, text: string) => { |
db09721d 2022-03-22 Pavel Safronov | 46 | await showModal({ title, text, willBackgroundCancel: false }); |
| 47 | sessionStorage.clear(); | |
| 48 | const { protocol, host, pathname } = location; | |
| 49 | const dir = dropFileExtension(pathname); | |
| 50 | const newUrl = `${protocol}//${host}${dir}` | |
| 51 | document.location = newUrl; | |
| 52 | } | |
1e41e9b4 2022-03-18 Pavel Safronov | 53 | |
| 54 | export class PeerGame extends LocalGame { | |
f2c94061 2022-03-21 Pavel Safronov | 55 | public conn: Peer.DataConnection; |
| 56 | public selfId: string; | |
5805825c 2022-03-21 Pavel Safronov | 57 | public constructor(player1Id: string, player1Name: string, player2Id: string, player2Name: string, selfId: string, conn: Peer.DataConnection) { |
| 58 | super(player1Id, player1Name, player2Id, player2Name); | |
f2c94061 2022-03-21 Pavel Safronov | 59 | this.selfId = selfId; |
| 60 | this.conn = conn; | |
47dfe48a 2022-03-20 Pavel Safronov | 61 | } |
f2c94061 2022-03-21 Pavel Safronov | 62 | public override setActiveUi(): void { |
| 63 | const { currentPlayerId, selfId } = this; | |
| 64 | ||
| 65 | const isLocalTurn = currentPlayerId === selfId; | |
| 66 | if (isLocalTurn) { | |
| 67 | super.setActiveUi(); | |
47dfe48a 2022-03-20 Pavel Safronov | 68 | } |
f2c94061 2022-03-21 Pavel Safronov | 69 | } |
| 70 | public override makeMove(source: Coord, dest: Coord): Promise<MoveResult> { | |
| 71 | const result = super.makeMove(source, dest); | |
| 72 | const peerData: PeerData = { move: { source, dest, playerId: this.currentPlayerId } }; | |
| 73 | this.conn.send(JSON.stringify(peerData)); | |
| 74 | return result; | |
| 75 | } | |
5805825c 2022-03-21 Pavel Safronov | 76 | public override async handleMoveResult(result: MoveResult): Promise<void> { |
b3c7b964 2022-03-22 Pavel Safronov | 77 | const { isTerminal, message } = result; |
db09721d 2022-03-22 Pavel Safronov | 78 | if (isTerminal) { |
417dc266 2022-03-23 Pavel Safronov | 79 | await showMessageAndLeave('Game Over', message!); |
5805825c 2022-03-21 Pavel Safronov | 80 | } else { |
| 81 | this.resetUi(); | |
| 82 | this.setActiveUi(); | |
| 83 | } | |
| 84 | } | |
47dfe48a 2022-03-20 Pavel Safronov | 85 | |
f2c94061 2022-03-21 Pavel Safronov | 86 | public static async createPeerGame(): Promise<PeerGame> { |
| 87 | let { id, peerId } = getData(); | |
| 88 | const main = document.getElementsByTagName('main')[0]; | |
417dc266 2022-03-23 Pavel Safronov | 89 | let game: PeerGame | undefined = undefined; |
f2c94061 2022-03-21 Pavel Safronov | 90 | |
c1cd0c65 2022-03-22 Pavel Safronov | 91 | const handleConn = async (conn: Peer.DataConnection) => { |
b3c7b964 2022-03-22 Pavel Safronov | 92 | shareContainer.classList.add('invisible'); |
5805825c 2022-03-21 Pavel Safronov | 93 | |
c1cd0c65 2022-03-22 Pavel Safronov | 94 | await new Promise<void>((resolve) => { |
| 95 | conn.on('open', () => resolve()); | |
| 96 | }); | |
| 97 | ||
f2c94061 2022-03-21 Pavel Safronov | 98 | id = peer.id; |
| 99 | peerId = conn.peer; | |
| 100 | setData({ id, peerId }); | |
| 101 | ||
| 102 | const isLocalP1 = getFirstPlayerId(id, peerId) === id; | |
5805825c 2022-03-21 Pavel Safronov | 103 | game = isLocalP1 ? |
| 104 | new PeerGame(id, "Local", peerId, "Remote", id, conn) : | |
| 105 | new PeerGame(peerId, "Remote", id, "Local", id, conn); | |
f2c94061 2022-03-21 Pavel Safronov | 106 | game.resetUi(); |
| 107 | game.setActiveUi(); | |
| 108 | main.classList.remove('invisible'); | |
| 109 | ||
417dc266 2022-03-23 Pavel Safronov | 110 | const table = document.getElementById('table')!; |
5805825c 2022-03-21 Pavel Safronov | 111 | table.addEventListener('mousemove', (ev: MouseEvent) => { |
| 112 | const xTable = ev.clientX - table.offsetLeft; | |
| 113 | const yTable = ev.clientY - table.offsetTop; | |
| 114 | const xRatio = xTable / table.clientWidth; | |
| 115 | const yRatio = yTable / table.clientHeight; | |
| 116 | const peerData: PeerData = { mousePos: { x: xRatio, y: yRatio } }; | |
| 117 | conn.send(JSON.stringify(peerData)); | |
| 118 | }); | |
| 119 | table.addEventListener('mouseleave', () => { | |
| 120 | const peerData: PeerData = { mousePos: { x: -1, y: -1 } }; | |
f2c94061 2022-03-21 Pavel Safronov | 121 | conn.send(JSON.stringify(peerData)); |
| 122 | }); | |
| 123 | ||
417dc266 2022-03-23 Pavel Safronov | 124 | let lastTimerId: NodeJS.Timeout | undefined = undefined; |
f2c94061 2022-03-21 Pavel Safronov | 125 | conn.on('data', (data: string) => { |
417dc266 2022-03-23 Pavel Safronov | 126 | if (!game) return; |
| 127 | ||
f2c94061 2022-03-21 Pavel Safronov | 128 | const peerData = JSON.parse(data) as PeerData; |
| 129 | const { mousePos, move } = peerData; | |
| 130 | ||
| 131 | if (mousePos) { | |
5805825c 2022-03-21 Pavel Safronov | 132 | const isValidPos = mousePos.x !== -1 && mousePos.y !== -1; |
| 133 | if (isValidPos) { | |
| 134 | const xRatio = mousePos.x; | |
| 135 | const yRatio = mousePos.y; | |
| 136 | const xTable = xRatio * table.clientWidth; | |
| 137 | const yTable = yRatio * table.clientHeight; | |
| 138 | const x = table.offsetLeft + xTable; | |
| 139 | const y = table.offsetTop + yTable; | |
| 140 | const style = `left:${x - otherMouseElement.clientWidth / 2}px;top:${y}px;display:block;`; | |
| 141 | otherMouseElement.setAttribute('style', style); | |
| 142 | if (lastTimerId !== undefined) { | |
| 143 | clearTimeout(lastTimerId); | |
| 144 | } | |
| 145 | lastTimerId = setTimeout(() => { | |
| 146 | otherMouseElement.setAttribute('style', ''); | |
| 147 | lastTimerId = undefined; | |
| 148 | }, 3000); | |
| 149 | } else if (lastTimerId !== undefined) { | |
| 150 | otherMouseElement.setAttribute('style', ''); | |
| 151 | } | |
f2c94061 2022-03-21 Pavel Safronov | 152 | } |
| 153 | ||
| 154 | const isWaitingForRemoteMove = peerId === game.currentPlayerId; | |
| 155 | if (isWaitingForRemoteMove && move) { | |
| 156 | const isMoveLegal = game.getPiece(move.source) === game.currentPlayerId && game.getPiece(move.dest) === null; | |
| 157 | if (isMoveLegal) { | |
| 158 | game.makeMove(move.source, move.dest); | |
| 159 | } else { | |
| 160 | console.log({ isMoveLegal, move }); | |
| 161 | } | |
| 162 | } | |
| 163 | }); | |
db09721d 2022-03-22 Pavel Safronov | 164 | conn.on('error', (err) => { |
| 165 | showMessageAndLeave(`Connection error`, err); | |
| 166 | }); | |
| 167 | conn.on('close', () => { | |
| 168 | showMessageAndLeave(`Connection closed`, 'Connection closed for some reason') | |
| 169 | }); | |
f2c94061 2022-03-21 Pavel Safronov | 170 | }; |
| 171 | ||
| 172 | const { host, protocol, pathname, search } = location; | |
| 173 | const queryParams = new URLSearchParams(search); | |
| 174 | ||
| 175 | const peer = id === undefined ? new Peer(peerOptions) : new Peer(id, peerOptions); | |
| 176 | window.onunload = () => peer.destroy(); | |
| 177 | peer.on('connection', (conn) => handleConn(conn)); | |
e46456c2 2022-03-22 Pavel Safronov | 178 | peer.on('error', async (err) => { |
db09721d 2022-03-22 Pavel Safronov | 179 | await showMessageAndLeave('Peer error encountered', err); |
e46456c2 2022-03-22 Pavel Safronov | 180 | }); |
f2c94061 2022-03-21 Pavel Safronov | 181 | peer.on('open', (trueId) => { |
| 182 | id = trueId; | |
| 183 | peerId = queryParams.get('peerId') ?? peerId; | |
| 184 | setData({ id, peerId }); | |
| 185 | ||
| 186 | if (peerId) { | |
| 187 | console.log(`${id} connecting to peer "${peerId}"`); | |
| 188 | const conn = peer.connect(peerId); | |
| 189 | handleConn(conn); | |
| 190 | } else { | |
| 191 | queryParams.set('peerId', id); | |
| 192 | const newSearch = queryParams.toString(); | |
b3c7b964 2022-03-22 Pavel Safronov | 193 | const newUrl = `${protocol}//${host}${pathname}?${newSearch}`; |
| 194 | shareLinkButton.onclick = () => { | |
| 195 | showSnackbar('Url copied to clipboard'); | |
e46456c2 2022-03-22 Pavel Safronov | 196 | copyToClipboard(newUrl); |
b3c7b964 2022-03-22 Pavel Safronov | 197 | }; |
| 198 | shareContainer.classList.remove('invisible'); | |
f2c94061 2022-03-21 Pavel Safronov | 199 | } |
| 200 | }); | |
db09721d 2022-03-22 Pavel Safronov | 201 | peer.on('disconnected', async () => { |
| 202 | await showMessageAndLeave('Peer disconnected', 'For some reason') | |
| 203 | }); | |
f2c94061 2022-03-21 Pavel Safronov | 204 | while (game === undefined) { |
| 205 | console.log('Waiting to connect to peer'); | |
| 206 | await delay(500); | |
1e41e9b4 2022-03-18 Pavel Safronov | 207 | } |
f2c94061 2022-03-21 Pavel Safronov | 208 | return game; |
47dfe48a 2022-03-20 Pavel Safronov | 209 | } |
7e7f0490 2022-03-18 Pavel Safronov | 210 | } |
| 211 | ||
db09721d 2022-03-22 Pavel Safronov | 212 | const isBrowserSupported = () => { |
| 213 | const browser = detect(); | |
| 214 | switch (browser && browser.name) { | |
| 215 | case 'chrome': | |
| 216 | case 'firefox': | |
| 217 | return true; | |
| 218 | default: | |
| 219 | return false; | |
| 220 | } | |
| 221 | } | |
47dfe48a 2022-03-20 Pavel Safronov | 222 | export const playGame = async () => { |
db09721d 2022-03-22 Pavel Safronov | 223 | if (isBrowserSupported()) { |
| 224 | await PeerGame.createPeerGame(); | |
| 225 | } else { | |
| 226 | showMessageAndLeave( | |
| 227 | 'Unsupported browser', | |
| 228 | '<p>Your current browser is not yet supported.</p>' + | |
| 229 | '<p>This PeerJs issue is tracking support in Microsoft Edge and Safari: </p>' + | |
| 230 | '<p><a href="https://github.com/peers/peerjs/issues/899" target="_blank">https://github.com/peers/peerjs/issues/899</a></p>') | |
| 231 | } | |
c3c52daf 2022-03-18 Pavel Safronov | 232 | }; |