Skip to content

Instantly share code, notes, and snippets.

@labohkip81
Created January 11, 2022 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save labohkip81/c9f46f434d4dc9cefe5186b49bc24bab to your computer and use it in GitHub Desktop.
Save labohkip81/c9f46f434d4dc9cefe5186b49bc24bab to your computer and use it in GitHub Desktop.
Cheza
const axios = require('axios').default;
const { GAME_CONFIG } = require('./Config');
const { ACCOUNT_INFO, ROOM_HAVE_BOT } = require('./Config');
const { BOT_STATE } = require('./Bot');
const Bot = require('./Bot');
var usersAtRooms = Bot.usersAtRooms;
var gameConfig = null;
const fs = require('fs');
//--------------------------------------------------------------------------------------------
//1.get game config
//--------------------------------------------------------------------------------------------
function getGameConfig() {
axios.get(GAME_CONFIG.CONFIG_URL)
.then(function (response) {
gameConfig = response.data;
//console.log(gameConfig);
for (let i = 0; i < gameConfig.Tables.length; i++) {
usersAtRooms.push(0);
}
for (let i = 0; i < ACCOUNT_INFO.length; i++) {
initBot(i);
}
isForceStopAllBot = false;
})
.catch(function (error) {
// handle error
//console.log(error);
})
.then(function () {
// always executed
});
}
getGameConfig();
//--------------------------------------------------------------------------------------------
//2. init bot, login, connect rpc, get account info, open table and listen player to join here
//--------------------------------------------------------------------------------------------
//let currentUserId = 0;
function initBot(idx) {
if (idx < 0 || idx >= ACCOUNT_INFO.length) {
isForceStopAllBot =false;
return;//done
}
let info = ACCOUNT_INFO[idx];
let botId = Bot.CreateBot(info.phone, info.pass, info.table); //[step]1. init nakama
//console.log(botId);
Bot.bots[botId].gameConfig = gameConfig;
Bot.bots[botId].authenticateEmail().then((session) => {//[step]2. authen
Bot.bots[botId].session = session;
Bot.bots[botId].state = BOT_STATE.HAD_LOGIN;
info.playerId = session.user_id;//store user_id
//currentUserId++;
console.info(">>> Authenticated successfully. User id:", session.user_id);
Bot.bots[botId].bot_id = session.user_id;
Bot.bots[botId].connect(session).then((result) => {//[step]3. connect socket
Bot.bots[botId].session = result;
//--set online (ping lai server 1 lan nua)
Bot.bots[botId].online(); //[step]4. set online
let TIMEOUT111 = setTimeout(()=>{
clearTimeout(TIMEOUT111);
Bot.bots[botId].client.getAccount(result).then((account) => { //[step]5. get account
Bot.bots[botId].account = account;
Bot.bots[botId].wallet.Coins = JSON.parse(account.wallet).Coins;
//console.log(`>>>getAccount: ${JSON.stringify(account)}`);
let TIMEOUT222 = setTimeout(()=>{
clearTimeout(TIMEOUT222);
Bot.bots[botId].updateToken().then(() => { //[step]6. update token
let TIMEOUT333 = setTimeout(()=>{
clearTimeout(TIMEOUT333);
Bot.bots[botId].getLobbyId().then((message) => {//[step]7. get lobby id
Bot.bots[botId].lobby_id = message.rpc.payload
//console.log(">>> Connecting to lobby:" + Bot.bots[botId].lobby_id);
//initBot(currentUserId);
}).catch((err) => {
console.log(">>> Unable to get lobby id " + err);
});
},300);
}).catch((err) => {
console.log(">>> updateToken error " + err);
});
},300);
}).catch((error) => {
console.log("Can't get user account", error)
});
},300);
}).catch((err) => {
console.log("Can't connect", err)
});
}).catch((error) => {
console.log(`initBot: error: ${error}`);
});
}
function BotLoginToLobby(botId, roomIndex) {
Bot.bots[botId].disconnect();
Bot.bots[botId].authenticateEmail().then((session) => {//[step]2. authen
Bot.bots[botId].session = session;
console.info(">>> relogin Authenticated successfully. User id:", session.user_id);
Bot.bots[botId].bot_id = session.user_id;
Bot.bots[botId].connect(session).then((result) => {//[step]3. connect socket
Bot.bots[botId].session = result;
//--set online (ping lai server 1 lan nua)
Bot.bots[botId].online(); //[step]4. set online
let TIMEOUT111 = setTimeout(()=>{
clearTimeout(TIMEOUT111);
Bot.bots[botId].client.getAccount(result).then((account) => { //[step]5. get account
Bot.bots[botId].account = account;
Bot.bots[botId].wallet.Coins = JSON.parse(account.wallet).Coins;
//console.log(`>>>getAccount: ${JSON.stringify(account)}`);
let TIMEOUT222 = setTimeout(()=>{
clearTimeout(TIMEOUT222);
Bot.bots[botId].updateToken().then(() => { //[step]6. update token
let TIMEOUT333 = setTimeout(()=>{
clearTimeout(TIMEOUT333);
Bot.bots[botId].getLobbyId().then((message) => {//[step]7. get lobby id
Bot.bots[botId].lobby_id = message.rpc.payload
//console.log(">>> Connecting to lobby:" + Bot.bots[botId].lobby_id);
Bot.bots[botId].joinTo().then((msg) => {//[step]8. join to lobby
console.log(`***[bot] add bot to room ${roomIndex}: ${Bot.bots[botId].phone}`);
}).catch(e=>{
console.log(`Bot.bots[botId].joinTo() error ${e}`);
});
}).catch((err) => {
console.log(">>> Unable to get lobby id " + err);
});
},300);
}).catch((err) => {
console.log(">>> updateToken error " + err);
});
},300);
}).catch((error) => {
console.log("Can't get user account", error)
});
},300);
}).catch((err) => {
console.log("Can't connect", err)
});
}).catch((error) => {
console.log(`initBot: error: ${error}`);
});
}
//--readjson file local api
const express = require('express');
const cors = require('cors');
const app = express()
const port = 3000
var isForceStopAllBot = true;
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.post('/getbotinfo', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true);
let d = new Date();
let date = `${d.getFullYear()}_${d.getMonth()}_${d.getDate()}`;
if (req.body && req.body != null && req.body.date != null) {
date = req.body.date;
}
fs.readFile(`./save_data/${date}.json`, "utf8", (err, jsonString) => {
if (err) {
//console.log("File read failed:", err);
res.end('[]');
return;
}
//console.log("File data:", "");
res.end(jsonString);
});
});
app.post('/getbotstatus', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true);
let arrRes = [];
for(let obj of Bot.bots){
let roomval = -1;
if(obj.selectedGame!=null){
roomval = obj.selectedGame.BuyIn;
}
if(obj && obj.account && obj.account.user && obj.account.user.username){
let temp = {userName:obj.account.user.username,displayName:obj.account.user.display_name,coin:obj.wallet.Coins,state:obj.state,room:roomval};
arrRes.push(temp);
}
}
res.end(JSON.stringify(arrRes));
});
app.post('/forceStopAllBot', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true);
let forceStop = false;
if (req.body && req.body != null && req.body.forceStop != null) {
forceStop = req.body.forceStop;
}
isForceStopAllBot = forceStop;
//console.log("Stop All Bot Success!!!");
res.end(JSON.stringify({ success: true }));
Bot.stopAllBot();
Bot.bots = [];
if(isForceStopAllBot==false){
usersAtRooms = [];
//currentUserId = 0;
getGameConfig();
}
});
app.post('/sendtoken', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true);
let forceStop = false;
if (req.body && req.body != null && req.body.forceStop != null) {
forceStop = req.body.forceStop;
}
isForceStopAllBot = forceStop;
//console.log("Stop All Bot Success!!!");
res.end(JSON.stringify({ success: true }));
Bot.stopAllBot();
Bot.bots = [];
if(isForceStopAllBot==false){
usersAtRooms = [];
//currentUserId = 0;
getGameConfig();
}
});
app.listen(port, () => {
//console.log(`app listening at http://localhost:${port}`)
});
//console.log('RESTful API server started on: ' + port)
//999. gameloop deliver bot into room-----------------------------------
setInterval(function () {
if (isForceStopAllBot) {
return;
}
for (let i = 0; i < ROOM_HAVE_BOT.length; i++) {
if (ROOM_HAVE_BOT[i]) {//room have bot
let botsPlaying = [];
let botsWaiting = [];
let botsHadLogin = [];
for (let j = 0; j < Bot.bots.length; j++) {//group bot
let obj = Bot.bots[j];
// obj.ping().then(()=>{}).catch(e=>{
// console.log(`ping error ${e}`)
// });
if (obj.assignTable == i) {
if (obj.state == BOT_STATE.PLAYING) {
botsPlaying.push(j);
}
else if (obj.state == BOT_STATE.JOIN_LOBBY) {
Bot.bots[j].waitTimeInLobby++;
Bot.bots[j].selectedGame = null;
if (Bot.bots[j].waitTimeInLobby < 600)
botsWaiting.push(j);
else
Bot.bots[j].leaveLobby();
}
else {
if (obj.state == BOT_STATE.HAD_LOGIN) {
if (i == 0 && obj.wallet.Coins < 50) {
continue;
} else if (i == 1 && obj.wallet.Coins < 100) {
continue;
} else if (i == 2 && obj.wallet.Coins < 200) {
continue;
} else if (i == 3 && obj.wallet.Coins < 500) {
continue;
}
botsHadLogin.push(j);
}
else
{
console.log(`bot state unknow`);
}
}
}
}
//--
if (botsWaiting.length <= 0) {//find bot assign to this room
if (botsHadLogin.length > 0) {
let botId = botsHadLogin[0];
Bot.bots[botId].selectedGame = null;
Bot.bots[botId].state = BOT_STATE.JOIN_LOBBY;
Bot.bots[botId].waitTimeInLobby = 0;
BotLoginToLobby(botId, i);
//console.log(`bot join >> ${Bot.bots[botId].phone}`);
}
} else /*if(botsWaiting.length > 1)*/ {
for (let k = 0; k < botsWaiting.length-1; k++) {
Bot.bots[botsWaiting[k]].leaveLobby();
}
}
}
}
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment