Limnoria/plugins/Holdem.py

555 lines
20 KiB
Python
Raw Normal View History

2004-10-15 05:35:06 +02:00
###
# Copyright (c) 2004, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
"""
Turns the bot into a poker dealer.
"""
import supybot
__revision__ = "$Id$"
__author__ = supybot.authors.jemfinch
__contributors__ = {}
###
# TODO:
#
# Betting timeouts.
# Change the "bet" command to allow saying a specific amount to bet to.
# Change the stack command to see another person's stack.
# Keep a bankroll in the users registry.
# Allow the "sit" command to have specified a stack size, subtracting it from
2004-10-15 19:10:14 +02:00
# the bankroll.
# Write a command to allow Owner users to give a person money.
2004-10-15 18:39:36 +02:00
# Re-expand the commands using forwarder so they can have better help.
2004-10-15 19:10:14 +02:00
# Have tables in each channel be entirely persistently configurable.
2004-10-15 18:39:36 +02:00
# Have the bot automatically start the next hand if people are seated.
# Have a slight pause before sending the "foo, it's your turn to bet" message,
2004-10-15 19:10:14 +02:00
# and if the user replies before then, don't send it.
# ??? Should we allow "to" in a raise command? raise to 100?
###
2004-10-15 17:53:50 +02:00
import sets
2004-10-15 05:35:06 +02:00
import random
2004-10-15 17:53:50 +02:00
import operator
2004-10-15 05:35:06 +02:00
import itertools
2004-10-15 17:53:50 +02:00
import poker
2004-10-15 05:35:06 +02:00
import supybot.conf as conf
import supybot.utils as utils
import supybot.ircdb as ircdb
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.callbacks as callbacks
def configure(advanced):
# This will be called by setup.py to configure this module. Advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Holdem', True)
class PokerError(ValueError):
pass
Holdem = conf.registerPlugin('Holdem')
conf.registerChannelValue(Holdem, 'blind',
2004-10-15 17:53:50 +02:00
registry.PositiveInteger(10, """Determines what the small blind is.
The big blind will be twice this."""))
2004-10-15 05:35:06 +02:00
conf.registerChannelValue(Holdem, 'color',
registry.Boolean(True, """Determines whether the bot will use color to
distinguish between consecutive hands."""))
users = {}
class Player(object):
def __init__(self, user, stack):
self.user = user
self.stack = stack
def __hash__(self):
return hash(self.user)
def nick(self):
return users[self.user]
class Table(object):
def __init__(self, channel):
self.irc = None
self.button = 0
self.players = []
self.channel = channel
self.waitingToJoin = []
self.waitingToLeave = []
2004-10-15 17:53:50 +02:00
self.colors = itertools.cycle(['red', 'orange', 'yellow',
'green', 'light blue', 'blue',
'purple'])
2004-10-15 05:35:06 +02:00
def _color(self, s):
if conf.get(conf.supybot.plugins.Holdem.color, self.channel):
s = ircutils.mircColor(s, self.color)
2004-10-15 17:53:50 +02:00
s = ircutils.bold(s)
2004-10-15 05:35:06 +02:00
return s
2004-10-15 17:53:50 +02:00
def public(self, s, noColor=False):
if not noColor:
s = self._color(s)
2004-10-15 05:35:06 +02:00
self.irc.reply(s, to=self.channel)
def private(self, player, s, noColor=False):
if not noColor:
s = self._color(s)
self.irc.reply(s, to=users[player.user], private=True)
def error(self, s):
s = self._color('%s: %s' % (self.irc.msg.nick, s))
self.irc.reply(s, to=self.channel)
2004-10-15 05:35:06 +02:00
def sit(self, player):
if player in self.players:
self.error('You\'re already seated.')
2004-10-15 05:35:06 +02:00
return
self.waitingToJoin.append(player)
2004-10-15 17:53:50 +02:00
self.irc.reply('You will be dealt in when the next hand begins.')
2004-10-15 05:35:06 +02:00
def stand(self, player):
if player in self.players:
self.waitingToLeave.append(player)
2004-10-15 17:53:50 +02:00
self.irc.reply('You will leave this table when this hand ends.')
2004-10-15 05:35:06 +02:00
elif player in self.waitingToJoin:
self.waitingToJoin.remove(player)
2004-10-15 19:52:59 +02:00
self.irc.reply('You are no longer waiting to join this table.')
2004-10-15 05:35:06 +02:00
else:
self.error('You aren\'t currently seated.')
2004-10-15 05:35:06 +02:00
2004-10-15 17:53:50 +02:00
def deal(self, startingPlayer):
2004-10-15 05:35:06 +02:00
# Ignore player.
self.color = self.colors.next()
2004-10-15 17:53:50 +02:00
self.blind = conf.get(conf.supybot.plugins.Holdem.blind, self.channel)
2004-10-15 05:35:06 +02:00
if self.waitingToJoin:
self.players.extend(self.waitingToJoin)
self.waitingToJoin = []
while self.waitingToLeave:
playa = self.waitingToLeave.pop()
self.players.remove(playa)
2004-10-15 17:53:50 +02:00
for player in self.players[:]:
if player.stack < 2*self.blind:
self.public('%s doesn\'t have enough money to play this hand.'
% player.nick())
self.players.remove(player)
2004-10-15 05:35:06 +02:00
if len(self.players) < 2:
2004-10-15 17:53:50 +02:00
self.public('I can\'t deal a new game with fewer than 2 people.')
2004-10-15 05:35:06 +02:00
return
2004-10-15 17:53:50 +02:00
2004-10-15 05:35:06 +02:00
self.hands = {}
self.buckets = {}
for player in self.players:
self.buckets[player] = 0
self.foldedBuckets = []
self.tableCards = []
self.button += 1
self.button %= len(self.players)
2004-10-15 17:53:50 +02:00
self._waitingOn = self.button
self.deck = poker.deck[:]
2004-10-15 05:35:06 +02:00
random.shuffle(self.deck)
for player in self.players:
self.hands[player] = [self.deck.pop()]
for player in self.players:
self.hands[player].append(self.deck.pop())
2004-10-15 17:53:50 +02:00
self.hand(player)
2004-10-15 05:35:06 +02:00
self.public('The cards are dealt.')
2004-10-15 17:53:50 +02:00
self.startRound()
# Blinds.
smallBlind = self.nextPlayer()
smallBlind.stack -= self.blind
self.buckets[smallBlind] += self.blind
self.currentBets[smallBlind] = self.blind
self.public('%s places small blind of %s.' %
(smallBlind.nick(), self.blind))
bigBlind = self.nextPlayer()
bigBlind.stack -= 2*self.blind
self.buckets[bigBlind] += 2*self.blind
self.currentBets[bigBlind] = 2*self.blind
self.public('%s places big blind of %s.' %
(bigBlind.nick(), 2*self.blind))
self.currentBet = 2*self.blind
2004-10-15 05:35:06 +02:00
self.startBettingRound()
2004-10-15 17:53:50 +02:00
def startRound(self):
self.couldBet = {}
2004-10-15 05:35:06 +02:00
self.currentBet = 0
self.currentBets = {}
2004-10-15 17:53:50 +02:00
self._waitingOn = self.button
for player in self.hands:
2004-10-15 05:35:06 +02:00
self.currentBets[player] = 0
2004-10-15 17:53:50 +02:00
def nextRound(self):
self.startRound()
2004-10-15 05:35:06 +02:00
self.deck.pop() # Burn a card.
if len(self.tableCards) == 0:
2004-10-15 17:53:50 +02:00
self.tableCards.append(self.deck.pop())
self.tableCards.append(self.deck.pop())
self.tableCards.append(self.deck.pop())
self.public('Flop dealt, table shows %s.' % self.tableCards)
self.startBettingRound()
elif len(self.tableCards) == 3:
self.tableCards.append(self.deck.pop())
self.public('Turn dealt, table shows %s.' % self.tableCards)
self.startBettingRound()
elif len(self.tableCards) == 4:
self.tableCards.append(self.deck.pop())
self.public('River dealt, table shows %s.' % self.tableCards)
2004-10-15 05:35:06 +02:00
self.startBettingRound()
else:
2004-10-15 17:53:50 +02:00
self.finishGame()
def finishGame(self):
try:
if len(self.buckets) == 1:
total = self.pot()
player = self.buckets.keys()[0]
player.stack += total
self.public('%s wins the hand for %s.' % (player.nick(), total))
return
assert len(self.hands) == len(self.buckets)
hands = [(player, poker.score(hand + self.tableCards))
for (player, hand) in self.hands.iteritems()]
utils.sortBy(operator.itemgetter(1), hands)
hands.reverse()
buckets = self.buckets.values() + self.foldedBuckets
for (player, (kind, hand)) in hands:
amountBet = self.buckets[player]
totalReceived = 0
for (i, bucket) in enumerate(buckets):
received = min(bucket, amountBet)
totalReceived += received
buckets[i] -= received
player.stack += totalReceived
self.public('%s wins %s with a %s, %s' %
(player.nick(), totalReceived, kind[2:], hand))
buckets = filter(None, buckets)
if not buckets:
break
finally:
self.public('This hand is finished, prepare for the next hand.')
2004-10-15 05:35:06 +02:00
def waitingOn(self):
2004-10-15 17:53:50 +02:00
self._waitingOn %= len(self.players)
2004-10-15 05:35:06 +02:00
return self.players[self._waitingOn]
2004-10-15 17:53:50 +02:00
def pot(self):
return sum(self.buckets.values()) + sum(self.foldedBuckets)
2004-10-15 05:35:06 +02:00
2004-10-15 19:10:14 +02:00
def possibleBettors(self):
L = []
for player in self.hands:
if player.stack > 0:
L.append(player)
return L
2004-10-15 17:53:50 +02:00
def startBettingRound(self):
player = self.nextPlayer()
2004-10-15 19:10:14 +02:00
if player is None or len(self.possibleBettors()) <= 1:
2004-10-15 17:53:50 +02:00
self.nextRound()
return
s = 'Betting begins with %s.' % self.waitingOn().nick()
s = 'The pot is currently at %s. %s' % (self.pot(), s)
self.public(s)
def checkWrongPlayer(self, player):
2004-10-15 05:35:06 +02:00
if player != self.waitingOn():
self.public('It\'s not your turn, %s.' % player.nick())
return True
return False
def nextPlayer(self):
2004-10-15 17:53:50 +02:00
seen = sets.Set()
while 1:
2004-10-15 05:35:06 +02:00
self._waitingOn += 1
2004-10-15 17:53:50 +02:00
player = self.waitingOn()
if player in seen:
return None # Handled by checkEndOfRound.
seen.add(player)
if player not in self.buckets or player.stack <= 0:
continue
else:
break
2004-10-15 05:35:06 +02:00
return self.waitingOn()
def checkEndOfRound(self):
# if all currentBets are not currentBet for all users with stacks.
if len(self.buckets) == 1:
# Only one guy left, let's distribute.
self.finishGame()
return
2004-10-15 17:53:50 +02:00
finished = True
2004-10-15 05:35:06 +02:00
for player in self.buckets:
2004-10-15 17:53:50 +02:00
if player not in self.couldBet:
finished = False
break
2004-10-15 05:35:06 +02:00
if self.currentBet > self.currentBets[player] and player.stack:
2004-10-15 17:53:50 +02:00
finished = False
2004-10-15 05:35:06 +02:00
break
2004-10-15 17:53:50 +02:00
if finished:
self.nextRound()
2004-10-15 05:35:06 +02:00
else:
player = self.nextPlayer()
2004-10-15 17:53:50 +02:00
if player is not None:
2004-10-15 19:10:14 +02:00
s = '%s, it\'s your turn. ' % player.nick()
if self.currentBet:
s += 'The current bet is %s. ' % self.currentBet
playerBet = self.currentBets[player]
if playerBet:
s += 'You\'ve already bet %s this round.' % playerBet
else:
s += 'You haven\'t yet bet this round.'
else:
s += 'There have not yet been any bets this round.'
self.public(s)
2004-10-15 17:53:50 +02:00
else:
self.nextRound()
2004-10-15 05:35:06 +02:00
def checkNoCurrentBet(self):
if self.currentBet:
self.error('There\'s a bet of %s, you must call it, '
'raise it, or fold.' % self.currentBet)
2004-10-15 05:35:06 +02:00
return True
return False
2004-10-15 17:53:50 +02:00
def hand(self, player):
try:
self.private(player, 'Your hand is %s.' % self.hands[player])
except KeyError:
self.error('You\'re not dealt in right now.')
2004-10-15 17:53:50 +02:00
def table(self, player):
self.public('The table shows %s.' % self.tableCards)
2004-10-15 05:35:06 +02:00
def fold(self, player):
if self.checkWrongPlayer(player):
return
bucket = self.buckets.pop(player)
if bucket:
self.foldedBuckets.append(bucket)
2004-10-15 17:53:50 +02:00
del self.hands[player]
2004-10-15 19:10:14 +02:00
self.public('%s folds.' % player.nick())
2004-10-15 05:35:06 +02:00
self.checkEndOfRound()
def check(self, player):
if self.checkWrongPlayer(player):
return
if self.currentBet and self.currentBets[player] < self.currentBet:
self.error('There is a bet of %s, you must call it, raise it, '
'or fold.' % self.currentBet)
2004-10-15 17:53:50 +02:00
self.public('%s checks.' % player.nick())
self.couldBet[player] = True
self.checkEndOfRound()
2004-10-15 05:35:06 +02:00
def addCurrentBet(self, player, amount):
2004-10-15 17:53:50 +02:00
self.couldBet[player] = True
2004-10-15 05:35:06 +02:00
self.buckets[player] += amount
self.currentBets[player] += amount
self.currentBet = max(self.currentBet, self.currentBets[player])
player.stack -= amount
2004-10-15 17:53:50 +02:00
return amount
2004-10-15 05:35:06 +02:00
def call(self, player):
if self.checkWrongPlayer(player):
return
2004-10-15 19:10:14 +02:00
if not self.currentBet:
self.error('There isn\'t any bet to call. '
'Perhaps you should check.')
return
toCall = self.currentBet - self.currentBets[player]
bet = self.addCurrentBet(player, min(toCall, player.stack))
2004-10-15 17:53:50 +02:00
self.public('%s calls %s.' % (player.nick(), bet))
2004-10-15 05:35:06 +02:00
self.checkEndOfRound()
def bet(self, player, amount):
if self.checkWrongPlayer(player):
return
2004-10-15 19:10:14 +02:00
if self.currentBet and amount < self.currentBet:
self.error('The current bet is %s, you must bet at least that.' %
self.currentBet)
2004-10-15 05:35:06 +02:00
return
if amount > player.stack:
self.error('You only have %s in your stack, you can\'t '
2004-10-15 17:53:50 +02:00
'bet that much. Perhaps you should use the allin '
'command.' % player.stack)
2004-10-15 05:35:06 +02:00
return
if amount < 2*self.blind:
self.error('You must bet at least the big blind.')
2004-10-15 05:35:06 +02:00
return
2004-10-15 17:53:50 +02:00
bet = self.addCurrentBet(player, amount)
self.public('%s bets %s.' % (player.nick(), bet))
2004-10-15 05:35:06 +02:00
self.checkEndOfRound()
def RAISE(self, player, amount):
if self.checkWrongPlayer(player):
return
if not self.currentBet:
self.error('You can\'t raise when there\'s no current '
2004-10-15 17:53:50 +02:00
'bet. Perhaps you should use the bet command.')
2004-10-15 05:35:06 +02:00
return
if amount < self.currentBet:
self.error('You can\'t raise by less than the current '
2004-10-15 17:53:50 +02:00
'bet of %s.' % self.currentBet)
2004-10-15 05:35:06 +02:00
return
totalRaise = amount + self.currentBet - self.currentBets[player]
2004-10-15 17:53:50 +02:00
bet = self.addCurrentBet(player, min(totalRaise, player.stack))
self.public('%s raises to %s.' % (player.nick(), bet))
2004-10-15 05:35:06 +02:00
self.checkEndOfRound()
def allin(self, player):
if self.checkWrongPlayer(player):
return
2004-10-15 17:53:50 +02:00
bet = self.addCurrentBet(player, player.stack)
self.public('%s goes all-in, %s.' % (player.nick(), bet))
2004-10-15 05:35:06 +02:00
self.checkEndOfRound()
def getPlayer(irc, msg, args, state):
callConverter('user', irc, msg, args, state)
Holdem = irc.getCallback('Holdem')
try:
state.args[-1] = Holdem.getPlayer(state.args[-1])
except KeyError:
irc.error('You\'re not currently seated, sit down first.', Raise=True)
addConverter('player', getPlayer)
class Holdem(callbacks.Privmsg):
def __init__(self):
self.players = {}
self.tables = ircutils.IrcDict()
self.__parent = super(Holdem, self)
self.__parent.__init__()
setattr(self.__class__, 'raise', self.__class__.RAISE)
def __call__(self, irc, msg):
try:
# users is a global, used by Tables.
users[ircdb.users.getUser(msg.prefix)] = msg.nick
except KeyError:
pass
self.__parent.__call__(irc, msg)
def callCommand(self, name, irc, msg, *args, **kwargs):
if irc.isChannel(msg.args[0]):
self.__parent.callCommand(name, irc, msg, *args, **kwargs)
def getPlayer(self, user):
if user not in self.players:
self.players[user] = Player(user, 1000)
return self.players[user]
2004-10-15 17:53:50 +02:00
def getTable(self, irc, channel):
table = self.tables[channel]
table.irc = irc
return table
2004-10-15 05:35:06 +02:00
def forwarder(name):
def f(self, irc, msg, args, channel, player):
"""takes no arguments
Does %s in the current game in the channel in which it's given.
"""
try:
2004-10-15 17:53:50 +02:00
table = self.getTable(irc, channel)
2004-10-15 05:35:06 +02:00
getattr(table, name)(player)
except KeyError:
return
f.__doc__ %= name
f = utils.changeFunctionName(f, name)
f = wrap(f, ['onlyInChannel', 'player'])
return f
#forwarder = staticmethod(forwarder)
def start(self, irc, msg, args, player):
"""takes no arguments
Starts a table in the channel this message is sent in.
"""
channel = msg.args[0]
if channel in self.tables:
irc.error('There\'s already a table in this channel.', Raise=True)
else:
self.tables[channel] = Table(channel)
irc.replySuccess()
start = wrap(start, ['player'])
sit = forwarder('sit')
call = forwarder('call')
deal = forwarder('deal')
fold = forwarder('fold')
2004-10-15 17:53:50 +02:00
hand = forwarder('hand')
table = forwarder('table')
2004-10-15 05:35:06 +02:00
check = forwarder('check')
allin = forwarder('allin')
stand = forwarder('stand')
def stack(self, irc, msg, args, player):
"""takes no arguments
Returns the size of your stack.
"""
irc.reply(player.stack)
stack = wrap(stack, ['player'])
def bet(self, irc, msg, args, channel, player, amount):
"""<amount>
Bets <amount>.
"""
if channel in self.tables:
2004-10-15 17:53:50 +02:00
self.getTable(irc, channel).bet(player, amount)
2004-10-15 05:35:06 +02:00
bet = wrap(bet, ['onlyInChannel', 'player', 'positiveInt'])
2004-10-15 17:53:50 +02:00
def RAISE(self, irc, msg, args, channel, player, amount):
2004-10-15 05:35:06 +02:00
"""<amount>
Calls the current bet and raises it by <amount>.
"""
if channel in self.tables:
2004-10-15 17:53:50 +02:00
self.getTable(irc, channel).RAISE(player, amount)
RAISE = wrap(RAISE, ['onlyInChannel', 'player', 'positiveInt'])
2004-10-15 05:35:06 +02:00
Class = Holdem
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: