f5a1eebd by Barry

Blackjack is now working. No double-down, split, or insurance

1 parent b5453b97
from random import randrange
from random import randrange
import pickle
SUITS = (':clubs:', ':spades:', ':hearts:', ':diamonds:')
CARDS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
......@@ -55,7 +56,7 @@ class Deck:
def draw(self, number_of_cards=1):
drawn_cards = []
for n in range(number_of_cards):
print("CARDS LEFT: {}".format(self.cards_left()))
#print("CARDS LEFT: {}".format(self.cards_left()))
choice = randrange(0, len(self.draw_pile))
drawn_cards.append(self.draw_pile.pop(choice))
return drawn_cards
......@@ -64,20 +65,23 @@ class Deck:
return len(self.draw_pile)
class Blackjack:
def __init__(self, bet):
self.bet = bet
self.deck = Deck()
self.player_hand = Hand()
self.player_hand.add_cards(self.deck.draw(2))
#print(player_hand.get_cards())
self.player_points = self.player_hand.get_points()
#print("Player: {}".format(player_points,))
self.dealer_hand = Hand()
self.dealer_hand.add_cards(self.deck.draw(2))
#print(dealer_hand.get_cards())
self.dealer_points = self.dealer_hand.get_points()
#print("Dealer: {}".format(dealer_points,))
def __init__(self, bet=0, state=None):
if state:
self.deserialize(state)
else:
self.bet = int(bet)
self.deck = Deck()
self.player_hand = Hand()
self.player_hand.add_cards(self.deck.draw(2))
#print(player_hand.get_cards())
self.player_points = self.player_hand.get_points()
#print("Player: {}".format(player_points,))
self.dealer_hand = Hand()
self.dealer_hand.add_cards(self.deck.draw(2))
#print(dealer_hand.get_cards())
self.dealer_points = self.dealer_hand.get_points()
#print("Dealer: {}".format(dealer_points,))
def draw(self):
self.player_hand.add_cards(self.deck.draw(1))
......@@ -87,6 +91,9 @@ class Blackjack:
self.dealer_hand.add_cards(self.deck.draw(1))
def is_busted(self):
self.dealer_points = self.dealer_hand.get_points()
self.player_points = self.player_hand.get_points()
if self.player_points > 21:
return 1
elif self.dealer_points > 21:
......@@ -95,6 +102,9 @@ class Blackjack:
return 0
def is_win(self):
if self.player_hand.is_blackjack() and not self.dealer_hand.is_blackjack():
return (int(self.bet + self.bet * 1.5), 'Blackjack! You win: {}')
# Resolve blackjack before dealer draws.
self.dealer_draw()
self.dealer_points = self.dealer_hand.get_points()
self.player_points = self.player_hand.get_points()
......@@ -102,29 +112,29 @@ class Blackjack:
# TODO: Check for blackjack Ace + 10 pt
if self.player_points > 21:
return (-self.bet, 'You Bust: {}')
elif self.player_hand.is_blackjack() and not self.dealer_hand.is_blackjack():
return (self.bet + self.bet * 1.5, 'Blackjack, you win: {}')
elif self.dealer_points > 21:
return (self.bet * 2, 'Dealer Busts: {}')
return (int(self.bet * 2), 'Dealer Busts: {}')
elif self.dealer_hand.is_blackjack():
return (-self.bet, 'You lose: {}')
elif self.player_points > self.dealer_points:
return (self.bet * 2, 'You win: {}')
return (int(self.bet * 2), 'You win: {}')
elif self.player_points == self.dealer_points:
return (self.bet, 'push your bet is returned: {}')
else:
return (-self.bet, 'You lose: {}')
def print_hand(self, show_dealer=False):
out_string = ""
if show_dealer:
dealers = ' '.join(self.dealer_hand.get_cards())
print("Dealer's Hand: {} for {} points".format(dealers, self.dealer_hand.get_points()))
out_string += "Dealer's Hand: {} showing for {} points\n".format(dealers, self.dealer_hand.get_points())
else:
dealers = ' '.join(self.dealer_hand.get_cards()[1:])
print("Dealer's Hand: {}".format(dealers))
out_string += "Dealer's Hand: {} showing\n".format(dealers)
self.player_points = self.player_hand.get_points()
print("Player's Hand: {} for {} points".format(' '.join(self.player_hand.get_cards()), self.player_hand.get_points()))
out_string += "Player's Hand: {} for {} points".format(' '.join(self.player_hand.get_cards()), self.player_hand.get_points())
return out_string
def get_actions(self):
points = self.player_hand.get_points()
......@@ -133,34 +143,43 @@ class Blackjack:
if self.player_hand.is_blackjack():
pass
elif points < 21 and not self.is_busted() == 2:
actions.append('hit')
actions.append('stand')
actions.append('double')
actions.append('!hit')
actions.append('!stand')
#actions.append('!double')
elif len(cards) == 2:
if cards[0][0] == cards[1][0]:
actions.append('split')
actions.append('!split')
return actions
bet = 10
bj = Blackjack(bet)
bj.print_hand()
actions = bj.get_actions()
done = False
while len(actions) > 0:
action = raw_input('Please choose an option [{}]'.format(', '.join(actions)))
if action == 'stand':
break
elif action == 'hit':
bj.draw()
bj.print_hand()
actions = bj.get_actions()
win, response = bj.is_win()
print('\n')
bj.print_hand(show_dealer=True)
print('\n')
print(response.format(win,))
def serialize(self):
return pickle.dumps(self)
def deserialize(self, state):
self = pickle.loads(state)
# bet = 10
# bj = Blackjack(bet)
# print(bj.print_hand())
# actions = bj.get_actions()
# done = False
# while len(actions) > 0:
# action = raw_input('Please choose an option [{}]'.format(', '.join(actions)))
# if action == 'stand':
# break
# elif action == 'hit':
# bj.draw()
# print(bj.print_hand())
# elif action == 'serialize':
# state = bj.serialize()
# print(state)
# bj.deserialize(state)
# actions = bj.get_actions()
# win, response = bj.is_win()
# print('\n')
# print(bj.print_hand(show_dealer=True))
# print('\n')
# print(response.format(win,))
......
No preview for this file type
......@@ -4,6 +4,7 @@ import random
import datetime
import re
import operator
import pickle
import traceback
import sys
......@@ -19,6 +20,7 @@ from collections import defaultdict
from nltk.tag import pos_tag
import wolframalpha
import sqlite3
from blackjack import Blackjack
VERSION = 1.6
......@@ -65,7 +67,7 @@ def leaders(xs, top=20):
def byteify(input):
if isinstance(input, dict):
return {byteify(key):byteify(value) for key,value in input.iteritems()}
return {byteify(key): byteify(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
......@@ -112,6 +114,32 @@ def dict_factory(cursor, row):
d[col[0]] = row[idx]
return d
def db_add_minigame(member_id, minigame_name, state):
c = conn.cursor()
db_state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id,minigame_name)).fetchone()
if not db_state:
c = conn.cursor()
c.execute("""INSERT INTO minigames(member_id, minigame_name, state)
VALUES(?, ?, ?);""", (member_id, minigame_name, state))
conn.commit()
else:
c = conn.cursor()
c.execute("""UPDATE minigames SET state = ?
WHERE member_id = ? AND minigame_name = ?;""", (state, member_id, minigame_name))
conn.commit()
pass
def db_get_minigame_state(member_id, minigame_name):
c = conn.cursor()
state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if state:
return state[0]
def db_delete_minigame_state(member_id, minigame_name):
c = conn.cursor()
c.execute("DELETE FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name))
conn.commit()
def db_add_message(message, delivery_time, channel, message_from, message_to, user_id):
c = conn.cursor()
c.execute("""INSERT INTO messages(message, delivery_time, channel, message_from, message_to, user_id)
......@@ -403,6 +431,10 @@ Games:
!games <username> - Returns a list of games played for a username.
!gameslist <count> - Returns a list of the top 20 games and the number of people who have played that game. if you pass a limit it will show that many games instead.
!whoplayed <gamename> - Returns a list of players who have played the game.
Minigames:
!bet <amount> - Start a game of BlackJack.
!hit - Draw a card
!stand - Show the cards
Spam:
!youtube <search term> - Returns the first video from the search results for the search term.
!gif <search term> - Returns the first gif from the search results.
......@@ -556,24 +588,104 @@ Stuff:
out_string = out_string[1900:]
return
if message.content.startswith('!hit') or message.content.startswith('!draw'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
bj.draw()
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
client.send_message(message.author, out_string)
else:
client.send_message(message.author, "You must start a game with !bet before you can ask for a new card.")
return
if message.content.startswith('!stay') or message.content.startswith('!stand'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
client.send_message(message.author, out_string)
return
if message.content.startswith('!bet'):
if type(message.channel) is not discord.channel.PrivateChannel:
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = db_get_minigame_state(member['member_id'], 'blackjack')
if state:
client.send_message(message.author, "You are already playing a game!")
out_string = ""
bj = pickle.loads(str(state))
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
client.send_message(message.author, out_string)
return
out_string = ""
bet_amount = message.content[5:]
client.send_message(message.author, "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}".format(bet_amount))
client.send_message(message.author, "Your Hand: {} {}".format(byteify('A:diamonds:'), byteify('J:hearts:')))
client.send_message(message.author, "Dealers Hand: {} {}".format(byteify('A:diamonds:'), byteify(':bell:')))
return
if not bet_amount.isdigit():
client.send_message(message.author, "Please provide a bet amount. !bet 10")
return
out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount)
bj = Blackjack(bet_amount)
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
if message.content.startswith('!direct'):
channel = message.channel
author = message.author
client.send_message(message.author, out_string)
log("{} {} - type: {}".format(channel.id, author.id, type(channel)))
client.send_message(author, "test")
return
# !msg joe in 5 minutes YOU ARE A DICK
if message.content.startswith('!msg'):
try:
......