Skip to content

Instantly share code, notes, and snippets.

@samuelsimoes
Created December 13, 2022 15:28
Show Gist options
  • Save samuelsimoes/18acc24211250251bd2d357a4a52372a to your computer and use it in GitHub Desktop.
Save samuelsimoes/18acc24211250251bd2d357a4a52372a to your computer and use it in GitHub Desktop.
const Random = require('random-js')
const random = new Random(Random.engines.mt19937().autoSeed())
const SocketIO = require('socket.io-client')
const diffApplier = require('../frontEnd/js/diffApplier')
require('../backEnd/database')
const ModelMTTPlayer = require('../backEnd/models/mtt/player')
// const HOST = 'https://localhost:3000'
const HOST = 'https://game:3000'
const TOURNAMENT_ID = 'DfZft'
class Player {
constructor (secret = random.string(10), name = random.string(10)) {
this.playerID = secret
this.secret = secret
this.name = name
}
onReceiveLastState = (state) => {
this.state = state
this.afterUpdateState()
}
afterUpdateState = () => {
if (this.state.cPI === this.playerID) {
setTimeout(() => {
if (this.state.gT[1] === 0) {
if (this.state.bigBlind === this.state.tB[this.playerID]) {
this.socket.emit('action', { type: 'PLAYER_CHECK' })
} else {
this.socket.emit('action', { type: 'PLAYER_CALL' })
}
} else {
this.socket.emit('action', { type: 'PLAYER_CHECK' })
}
}, random.integer(1, 3) * 1000)
}
}
onGameChange = (patch) => {
if (!this.state) { return }
if (!patch.r && patch.pre !== this.state.now) {
return this.socket.emit('action', { type: 'RUP' })
}
let newState
if (patch.r) {
newState = patch
} else {
newState = diffApplier(this.state, patch)
}
this.state = newState
this.afterUpdateState()
}
connectSocket = (gameID) => {
return new Promise((resolve, reject) => {
this.gameID = gameID
this.socket = SocketIO(HOST, {
transports: ['websocket'],
rejectUnauthorized: false,
query: { gameID, ut: this.secret }
})
this.socket.on('rup', this.onReceiveLastState)
this.socket.on('gC', this.onGameChange)
this.socket.on('disconnected', async (payload) => {
console.log('discone')
})
this.socket.on('registered', async (payload) => {
console.log('registered')
this.onReceiveLastState(payload.gameState)
resolve()
})
})
}
}
async function main () {
const mTTPlayers = await ModelMTTPlayer.query().where({ tournament_id: TOURNAMENT_ID })
console.log(mTTPlayers.length)
for (let i = 0; i < mTTPlayers.length; i++) {
const mTTPlayer = mTTPlayers[i]
const player = new Player(mTTPlayer.name)
console.log(`Connected Player ${mTTPlayer.id}`)
await player.connectSocket(mTTPlayer.currentGameId)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment