Compare commits

...

19 Commits

Author SHA1 Message Date
fc55bd2830 check for bank before raise 2023-07-18 16:31:52 +02:00
69f925e0f6 change odds 2023-07-16 19:10:57 +02:00
2cec666f76 readme schmeadme 2023-07-15 07:00:02 +02:00
4cbdf71f0a remove dependency 2023-07-15 06:57:19 +02:00
e5ca195346 verbose & debug in console or chat 2023-07-15 06:56:45 +02:00
bc47818a9d debug verbose level (without trigger lol) 2023-07-15 06:56:15 +02:00
a3be1cb8f1 Merge pull request 'uff' (#1) from uff into master
Reviewed-on: #1
2023-07-13 22:07:21 +00:00
890e0ab580 handranker 2023-07-14 00:06:15 +02:00
6fe4171c00 blah 2023-07-13 19:07:52 +02:00
f234fe0a08 uff 2023-07-12 18:38:42 +02:00
efd32e69e7 debug shmebug 2023-07-12 16:49:29 +02:00
20c07af542 .pj: activates autojoin; .pl deactivates autojoin 2023-07-12 15:47:16 +02:00
999c2960fd muh 2023-07-12 14:51:39 +02:00
82230c7dbf handle splitpot 2023-07-12 08:23:45 +02:00
a9710113d4 helper class, config management 2023-07-12 08:11:27 +02:00
5f0cea9cf1 update readme 2023-07-12 03:45:06 +02:00
9be66d6cc0 provide sample config 2023-07-12 03:34:42 +02:00
f0e5b965bf refactoring 2023-07-12 03:10:13 +02:00
b2980e01b5 implement cactus kev's poker hand evaluator 2023-07-11 18:39:38 +02:00
9 changed files with 1832 additions and 123 deletions

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
node_modules
config.json
config.json
data/HandRanks.dat

View File

@ -1,2 +1,12 @@
# schmirc
A poker bot for the hirc poker bot by nilscc: https://github.com/nilscc/hirc
## Installation & Usage
npm i
cp config.example.json config.json
edit config.json
npm start

26
config.example.json Normal file
View File

@ -0,0 +1,26 @@
{
"bot": {
"autojoin": false,
"debug": false,
"verbose": 3,
"pokerbot": "hirc",
"channel": "#poker"
},
"clients": [{
"type": "irc",
"enabled": true,
"network": "n0xy",
"host": "",
"port": 6697,
"ssl": true,
"selfSigned": false,
"sasl": false,
"nickname": "schmirc",
"username": "schmirc",
"password": "",
"realname": "schmirc",
"channels": [
"#poker"
]
}]
}

9
package-lock.json generated
View File

@ -7,17 +7,14 @@
"": {
"name": "schmirc",
"version": "1.0.0",
"cpu": [
"x64"
],
"license": "ISC",
"dependencies": {
"@xpressit/winning-poker-hand-rank": "^0.1.6",
"cuffeo": "^1.2.2"
}
},
"node_modules/@xpressit/winning-poker-hand-rank": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@xpressit/winning-poker-hand-rank/-/winning-poker-hand-rank-0.1.6.tgz",
"integrity": "sha512-l7b8GAKOT6k79qKF/SesCgQLvCjHZkhihf5QhgcL9w3hiya2JeCVyg07TVayoyO8PzDq56MH+yKk5rcbDMYScw=="
},
"node_modules/cuffeo": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cuffeo/-/cuffeo-1.2.2.tgz",

View File

@ -2,14 +2,16 @@
"name": "schmirc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"main": "index.mjs",
"cpu": [
"x64"
],
"scripts": {
"start": "node ./src/index.mjs"
},
"author": "Flummi",
"license": "ISC",
"dependencies": {
"@xpressit/winning-poker-hand-rank": "^0.1.6",
"cuffeo": "^1.2.2"
}
}

1410
src/inc/constants.mjs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,84 @@
import constants from './constants.mjs';
export default new class handranker {
constructor() {
return this;
rankHands(board, hand) {
let bestHand = this.calcBestHand([...board, ...hand].map(c => this.toCard(c)));
if(bestHand > 6000) bestHand += 2000;
return {
rank: bestHand,
percentage: (9999 - bestHand) / 100,
combination: this.toCombination(bestHand)
};
};
toCombination(r) {
if(r > 6185) return 'HighCard';
if(r > 3325) return 'Pair';
if(r > 2467) return 'TwoPairs';
if(r > 1609) return 'ThreeOfAKind';
if(r > 1599) return 'Straight';
if(r > 322) return 'Flush';
if(r > 166) return 'FullHouse';
if(r > 10) return 'FourOfAKind';
return 'StraightFlush';
};
cactusFastRankHand(hand) {
const [c0, c1, c2, c3, c4] = hand;
if((c0 & c1 & c2 & c3 & c4 & 0xf000) !== 0)
return constants.fastFlushes[(c0 | c1 | c2 | c3 | c4) >>> 16];
const r = constants.fastUnique5[(c0 | c1 | c2 | c3 | c4) >>> 16];
if(r)
return r;
let u = 0xe91aaa35 + (((c0 & 0xff) * (c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff)) | 0);
u = u ^ (u >>> 16);
u += u << 8;
u ^= u >>> 4;
return constants.hash[((u + (u << 2)) >>> 19) ^ (constants.hashAdjust[(u >>> 8) & 0x1ff] | 0)];
};
calcBestHand(hand) {
if(hand.length === 5)
return this.cactusFastRankHand([hand[0], hand[1], hand[2], hand[3], hand[4]])
if(hand.length === 6) {
const possibleHands = [
[hand[0], hand[1], hand[2], hand[3], hand[4]],
[hand[0], hand[1], hand[2], hand[3], hand[5]],
[hand[0], hand[1], hand[2], hand[4], hand[5]],
[hand[0], hand[1], hand[3], hand[4], hand[5]],
[hand[0], hand[2], hand[3], hand[4], hand[5]],
[hand[1], hand[2], hand[3], hand[4], hand[5]],
];
const sortedHands = possibleHands.map(h => this.cactusFastRankHand(h)).sort();
return sortedHands[0];
}
if(hand.length === 7) {
let r = 0;
let rank = 9999;
for(let i = 0; i < 21; i++) {
const inputHand = [
hand[constants.t7c5[i][0]],
hand[constants.t7c5[i][1]],
hand[constants.t7c5[i][2]],
hand[constants.t7c5[i][3]],
hand[constants.t7c5[i][4]],
];
r = this.cactusFastRankHand(inputHand);
if(r < rank)
rank = r;
}
return rank;
}
throw `Hand ranker doesn't support ${hand.length} cards`;
};
toCard(playingCard) {
const rank = constants.runeToRank[playingCard[0]];
const suit = constants.runeToSuit[playingCard[1]];
if(!suit || rank === undefined)
throw `Invalid playing card: ${playingCard}`;
return ((1 << rank) << 16) | (suit << 12) | (rank << 8) | constants.PRIMES[rank];
};
};

60
src/inc/helper.mjs Normal file
View File

@ -0,0 +1,60 @@
import fs from 'node:fs/promises';
import { bot } from '../index.mjs';
let _config;
try {
_config = JSON.parse(await fs.readFile('config.json'));
} catch(err) {
throw err;
}
export default new class {
suits = { "♠": "S", "♣": "C", "♦": "D", "♥": "H" };
stripColors = msg => msg.replace(/\x03\d{0,2}(,\d{0,2}|\x02\x02)?/g, '');
rand = (max = 1) => ~~(Math.random() * (max - 1) + 1);
config = {
get(k) {
return _config.bot[k];
},
async set(k, v) {
_config.bot[k] = v;
await this.writeConfig();
return this.get(k);
},
getFull() {
return _config;
},
async writeConfig() {
try {
await fs.writeFile('config.json', JSON.stringify(_config, null, 2));
return true;
} catch(err) {
throw err;
}
}
};
debug(msg, level = 2) {
const verbose = this.config.get('verbose');
if(level < verbose)
return;
switch(this.config.get('debug')) {
case 'chat': this.sendMsg(msg); break;
case true:
case 'console': console.log(msg); break;
default: return;
}
};
parseCards(msg, output = []) {
for(const c of this.stripColors(msg).match(/(\w+)([♠♣️♦♥️️])/g))
output.push(c.length === 3 ? `T${this.suits[c[2]]}` : `${c[0]}${this.suits[c[1]]}`);
return output;
};
async sendMsg(msg) {
return (await bot.clients.filter(async c => (await c).name == this.config.getFull().clients[0].network)[0])
.client.sendmsg("normal", this.config.get('channel'), msg);
};
};

View File

@ -1,46 +1,99 @@
import cuffeo from 'cuffeo';
import { rankHands } from '@xpressit/winning-poker-hand-rank';
import handranker from './inc/handranker.mjs';
import cfg from '../config.json' assert { type: 'json' };
import helper from './inc/helper.mjs';
const bot = await new cuffeo(cfg.clients);
const cfg = helper.config;
export const bot = await new cuffeo(cfg.getFull().clients);
const suits = { "♠": "S", "♣": "C", "♦": "D", "♥": "H" };
const stripColors = msg => msg.replace(/\x03\d{0,2}(,\d{0,2}|\x02\x02)?/g, '');
const parseCards = msg => {
const output = [];
for(const c of stripColors(msg).match(/(\w+)([♠♣️♦♥️️])/g)) {
if(c.length === 3)
output.push(`T${suits[c[2]]}`);
else
output.push(`${c[0]}${suits[c[1]]}`);
}
return output;
};
const env = {
export const env = {
gamestate: 'not started, ' + (cfg.get('autojoin') ? 'autojoin' : 'no autojoin'),
hand: false,
board: false,
winchance: false,
called: false,
odds: false,
joined: false,
callamount: 0,
pot: 0,
bank: 0
bank: 0,
lastaction: false // debug purpose
};
bot.on("message", e => {
bot.on("notice", msg => {
if(msg.match(/^Your hand/)) {
env.hand = helper.parseCards(msg);
helper.debug('hand: ' + env.hand.join(', '));
}
});
bot.on("message", async e => {
if(e.channel !== cfg.get('channel'))
return;
if(e.message.startsWith('.cards ')) {
let cards = [];
try {
cards = JSON.parse(e.message.slice(7));
} catch(err) {
return e.reply('That is not an array.');
}
const hand = cards.slice(0, 2);
const board = cards.slice(2);
let rank;
try {
rank = handranker.rankHands(board, hand);
} catch(err) {
return e.reply(err);
}
e.reply(JSON.stringify(rank));
return;
}
if(e.message === `.${e.self.me.nickname} help`) {
await e.write(`PRIVMSG ${e.user.nick} I always say hirc schmirc, available commands are:`);
const commands = [
' .pj -- poker join (activates autojoin)',
' .pl -- poker leave (deactivates autojoin)',
' .bb -- bank balance',
' .bl -- bank loan',
' .d -- deal',
' .deb -- toggle debug',
' .aj -- toggle autojoin',
'While playing:',
' .s -- stack',
' .f -- fold',
];
for(const command of commands) {
await e.write(`PRIVMSG ${e.user.nick} ${command}`);
}
}
if(e.message.match(new RegExp(`^${e.self.me.nickname}: Your bank account`))) {
env.bank = +e.message.match(/is: (\d+) \(/)[1];
}
if(e.message === ".pj" || e.message === "pj" && !env.hand && !env.joined) {
if(e.message.startsWith(".debug")) {
const tmp = e.message.match(/\.debug (\w+)/)?.[1];
if(!tmp)
return e.reply(`debug mode ${await cfg.set('debug', !cfg.get('debug')) ? '[color=green]enabled[/color]' : '[color=red]disabled[/color]'}`);
if(!['console', 'chat'].includes(tmp))
return e.reply(`debug mode ${await cfg.set('debug', false) ? '[color=green]enabled[/color]' : '[color=red]disabled[/color]'}`);
return e.reply(`debug mode [color=green]enabled[/color] (${await cfg.set('debug', tmp)})`);
}
if(e.message === ".aj" || e.message === ".autojoin") {
const tmp = await cfg.set('autojoin', !cfg.get('autojoin'));
return e.reply(`autojoin ${tmp ? '[color=green]enabled[/color]' : '[color=red]disabled[/color]'}`);
}
if(e.message === ".pj" || (e.message === "pj" && cfg.get('autojoin')) && !env.hand && !env.joined) {
env.joined = true;
return e.reply("bb\npj");
await cfg.set('autojoin', true);
//return e.reply("pj");
return e.reply(["bb", "pj"]);
}
if(e.message === ".pl" && !env.hand) {
env.joined = false;
await cfg.set('autojoin', false);
return e.reply("pl");
}
if(e.message === ".bb" && !env.hand)
@ -53,108 +106,180 @@ bot.on("message", e => {
return e.reply("f");
if(e.message === ".d" && !env.hand)
return e.reply("d");
if(e.message === ".env") {
return helper.debug(env, 5);
}
if(e.user.nick !== 'hirc' || !env.hand)
if(e.user.nick !== cfg.get('pokerbot') || !env.hand)
return;
if(e.message.match(/(small|big) blind/)) {
env.callamount = +e.message.match(/pays (\d+) \(/)[1];
// tracker
if(e.message.includes('raises the pot')) {
env.callamount = +e.message.match(/raises the pot by (\d+)/)[1];
env.pot += env.callamount;
if(e.message.includes(e.self.me.nickname)) {
env.bank -= +e.message.match(/pays (\d+) \(/)[1];
env.bank -= env.callamount;
helper.debug(`bank: ${env.bank}`);
}
console.log(`callamount: ${env.callamount}; potsize: ${env.pot}; winchance: ${env.winchance}`);
return;
}
if(e.message.includes('raises the pot')) {
env.callamount = +e.message.match(/pot by (\d+)/)[1];
env.pot += env.callamount;
console.log(`callamount: ${env.callamount}; potsize: ${env.pot}; winchance: ${env.winchance}`);
}
if(e.message.match(/calls \d+\./)) {
if(e.message.includes('calls')) {
env.callamount = +e.message.match(/calls (\d+)\./)[1];
env.pot += env.callamount;
console.log(`callamount: ${env.callamount}; potsize: ${env.pot}; winchance: ${env.winchance}`);
}
if(e.message.includes('check')) {
console.log(`callamount: ${env.callamount}; potsize: ${env.pot}; winchance: ${env.winchance}`);
}
if(e.message.match(new RegExp(`^Current player: ${e.self.me.nickname}( |$)`)) && env.hand) {
if(!env.winchance) { // preflop
const callby = +e.message.match(/\((\d+) to call\)/)?.[1] || 0;
if(callby > 0) {
env.bank -= callby;
}
return e.reply('c');
}
if(env.winchance >= 55 && env.callamount) {
if(~~(Math.random() * 2) === 1) {
const raiseby = env.callamount + (~~(Math.random() * 2 + 2) * 10);
env.bank -= raiseby;
return e.reply(`r ${raiseby}`);
}
else {
return e.reply('c');
}
if(e.message.includes(e.self.me.nickname)) {
env.bank -= env.callamount;
helper.debug(`bank: ${env.bank}`);
}
return;
}
if(e.message.endsWith('blind).')) { // blinds
env.callamount = +e.message.match(/pays (\d+) \(/)[1];
env.pot += env.callamount;
if(e.message.includes('to call')) {
if(env.winchance >= 30) {
if(env.called) {
env.bank -= env.callamount;
return e.reply('c');
}
else {
env.called = true;
if((~~(Math.random() * 2)) === 1) {
env.bank -= env.callamount;
return e.reply('c');
}
else {
return e.reply('f');
}
}
}
else {
if((~~Math.random() * 5) === 1) {
return e.reply('f');
}
else {
env.bank -= env.callamount;
return e.reply('c');
}
}
}
const oldstate = env.gamestate;
env.gamestate = 'preflop';
if(oldstate !== env.gamestate)
helper.debug(`${oldstate} -> ${env.gamestate}`);
env.bank -= env.callamount;
return e.reply('c');
}
if(e.message.includes('Game ended') || e.message.includes('wins the pot')) {
//e.reply(`my hand: ${hand.join(', ')} (${winchance}%)`);
e.reply('my bank balance: ' + env.bank);
env.hand = false;
env.board = false;
env.winchance = false;
env.called = false;
env.joined = false;
env.pot = 0;
if(e.message.includes(e.self.me.nickname)) {
env.bank -= env.callamount;
helper.debug(`bank: ${env.bank}`);
}
return;
}
if(e.message.match(/^(Flop|Turn|River)/) && e.user.nick === 'hirc') {
env.board = parseCards(e.message);
// bot is broke :(
if(e.message.includes('You don\'t have enough money')) {
e.reply(['fugggggg', 'f']);
if(env.bank < 100) {
e.reply('bank loan');
}
return;
}
// bot's turn
if(e.message.match(new RegExp(`Current player: ${e.self.me.nickname}( |$)`))) {
let action = 'c'; // default
let debug = false;
if(env.gamestate === 'preflop' || !env.odds) { // preflop
env.lastaction = action;
helper.debug('preflop, (checkcall) :(', 3);
return e.reply(action); // checkcall
}
console.log(env.board, env.hand);
if(e.message.includes('to call')) { // callphase
env.callamount = +e.message.match(/\((\d+) to call\)/)[1];
const rank = rankHands('texas', env.board, [env.hand])[0];
env.winchance = (9999 - rank.rank) / 100;
}
});
bot.on("notice", msg => {
if(msg.match(/^Your hand/)) {
env.hand = parseCards(msg);
if(env.callamount > env.bank) // not enough money lol
return e.reply(['huan!', 'f']);
if(env.odds <= 40) {
if(helper.rand(20) === 1 && env.callamount < (helper.rand(2, 6) * 10)) { // bad hand, call anyway
action = 'call';
debug = `bad hand, call anyway (${env.odds}, callphase, 5%)`;
}
else { // bad hand, fold
action = 'fold';
debug = `bad hand (${env.odds}, callphase, 95%)`;
}
}
else if(env.odds > 40 && env.odds <= 50) { // decent hand, raise
if(helper.rand(10) === 1) { // 10%
const toRaise = env.callamount + helper.rand(5) * 10;
if(toRaise > env.bank) {
action = 'raise ' + toRaise.toString();
debug = `decent hand (${env.odds}, callphase, 10%)`;
}
}
}
else if(env.odds > 50 && env.odds <= 70) { // good hand lol
if(helper.rand(3) === 1) { // 33%
const toRaise = env.callamount + helper.rand(6) * 10;
if(toRaise > env.bank) {
action = 'raise ' + toRaise.toString();
debug = `good hand lol (${env.odds}, callphase, 33%)`;
}
}
}
else if(env.odds > 70) { // fuck them all
const toRaise = env.callamount + helper.rand(7) * 10;
if(toRaise > env.bank) {
action = 'raise ' + toRaise.toString();
debug = `fuck them all (${env.odds}, callphase)`;
}
}
}
else { // checkphase
if(env.odds > 55 && env.odds <= 70) { // decend hand, raise
if(helper.rand(5) === 1) { // 20%
const toRaise = env.callamount + helper.rand(5) * 10;
if(toRaise > env.bank) {
action = 'raise ' + toRaise.toString();
debug = `decent hand (${env.odds}, checkphase, 20%)`;
}
}
}
else if(env.odds > 70 && env.odds <= 85) { // good hand lol
if(helper.rand(2) === 1) { // 50%
const toRaise = env.callamount + helper.rand(6) * 10;
if(toRaise > env.bank) {
action = 'raise ' + toRaise.toString();
debug = `good hand lol (${env.odds}, callphase, 50%)`;
}
}
}
else if(env.odds > 85) { // fuck them all
const toRaise = env.callamount + helper.rand(7) * 10;
if(toRaise > env.bank) {
action = 'raise ' + toRaise.toString();
debug = `fuck them all (${env.odds}, callphase)`;
}
}
}
if(action) {
env.lastaction = action;
helper.debug(debug ? debug : 'check lol', 3);
return e.reply(action);
}
}
// gamestate & board changes
if(e.message.match(/^(Flop|Turn|River)/)) {
env.board = helper.parseCards(e.message);
const oldstate = env.gamestate;
env.gamestate = e.message.match(/(\w+): /)[1].toLowerCase();
helper.debug(`${oldstate} -> ${env.gamestate}`, 2);
const rank = handranker.rankHands(env.board, env.hand);
env.odds = rank.percentage;
}
// end of game
if(e.message.includes('wins the pot') || e.message.includes('Split pot')) {
if(e.message.includes(e.self.me.nickname)) {
if(e.message.includes('Split pot')) {
const tmp = e.message.match(/size (\d+) .*: (.*) \(/);
env.bank += ~~(tmp[1] / tmp[2].split(', ').length);
}
else {
env.bank += +e.message.match(/pot(: | of size )(\d+)/)[2];
}
helper.debug(`bank: ${env.bank}`);
}
const oldstate = env.gamestate;
env.gamestate = 'not started, ' + (cfg.get('autojoin') ? 'autojoin' : 'no autojoin');
helper.debug(`${oldstate} -> ${env.gamestate}`, 2);
env.hand = false;
env.board = false;
env.odds = false;
env.joined = false;
env.pot = 0;
env.lastaction = false;
return;
}
});