Friday, August 2, 2013

Blackjack with Python (for codeskulptor)

1:  import simplegui  
2:  import random  
3:    
4:  # load card sprite - 949x392 - source: jfitz.com  
5:  CARD_SIZE = (73, 98)  
6:  CARD_CENTER = (36.5, 49)  
7:  card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")  
8:    
9:  CARD_BACK_SIZE = (71, 96)  
10:  CARD_BACK_CENTER = (35.5, 48)  
11:  card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png")    
12:    
13:  # initialize some useful global variables  
14:  in_play = False  
15:  message1 = ""  
16:  wins = 0  
17:  losses = 0  
18:    
19:  # define globals for cards  
20:  SUITS = ('C', 'S', 'H', 'D')  
21:  RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')  
22:  VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}  
23:    
24:    
25:  # define card class  
26:  class Card:  
27:    def __init__(self, suit, rank):  
28:      if (suit in SUITS) and (rank in RANKS):  
29:        self.suit = suit  
30:        self.rank = rank  
31:      else:  
32:        self.suit = None  
33:        self.rank = None  
34:        print "Invalid card: ", suit, rank  
35:    
36:    def __str__(self):  
37:      return self.suit + self.rank  
38:    
39:    def get_suit(self):  
40:      return self.suit  
41:    
42:    def get_rank(self):  
43:      return self.rank  
44:    
45:    def draw(self, canvas, pos):  
46:      card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank),   
47:            CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))  
48:      canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)  
49:        
50:    def draw_back(self, canvas, pos):  
51:      card_loc = (CARD_BACK_CENTER[0], CARD_BACK_CENTER[1])  
52:      canvas.draw_image(card_back, card_loc, CARD_BACK_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_BACK_CENTER[1]], CARD_BACK_SIZE)  
53:        
54:        
55:  # define hand class  
56:  class Hand:  
57:    def __init__(self):  
58:      self.cards = []  
59:      pass     # create Hand object  
60:    
61:    def __str__(self):  
62:      ans = " "  
63:      for i in range(len(self.cards)):  
64:        ans += str(self.cards[i]) + " "  
65:      return "Hand contains" + ans  
66:      pass     # return a string representation of a hand  
67:    
68:    def add_card(self, card):  
69:      self.cards.append(card)  
70:      pass     # add a card object to a hand  
71:        
72:    def get_value(self):  
73:      hand_value = 0  
74:      check = 0  
75:      for card in self.cards:  
76:        card_rank = card.get_rank()  
77:        hand_value += VALUES[card.get_rank()]  
78:        if card_rank == 'A':  
79:          check += 1  
80:        else:  
81:          pass  
82:      if check != 0:  
83:        if hand_value + 10 <= 21:  
84:          hand_value += 10  
85:        else:  
86:          pass  
87:          
88:      return hand_value  
89:          
90:      # count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust  
91:      pass     # compute the value of the hand, see Blackjack video    
92:    
93:      
94:    def draw(self, canvas, pos):  
95:                       
96:      for card in self.cards:  
97:        if pos == [100, 350]:  
98:          if in_play == True:   
99:            card.draw_back(canvas, pos)  
100:          else:  
101:            card.draw(canvas, pos)  
102:        else:  
103:          card.draw(canvas, pos)  
104:        
105:        pos[0] += 50  
106:    
107:      pass     # draw a hand on the canvas, use the draw method for cards  
108:     
109:        
110:  # define deck class   
111:  class Deck:  
112:    def __init__(self):  
113:      self.card = []  
114:      for suit in SUITS:  
115:        for rank in RANKS:  
116:          self.card.append(Card(suit, rank))  
117:      pass     # create a Deck object  
118:    
119:    def shuffle(self):  
120:      # add cards back to deck and shuffle  
121:      self.card_shuffled = random.shuffle(self.card)  
122:      pass     # use random.shuffle() to shuffle the deck  
123:    
124:    def deal_card(self):  
125:      return self.card.pop()  
126:      pass     # deal a card object from the deck  
127:      
128:    def __str__(self):  
129:      s = ""  
130:      for i in self.card:  
131:        s += str(i) + " "  
132:      return s  
133:      pass     # return a string representing the deck   
134:    
135:    
136:    
137:  #define event handlers for buttons  
138:  def deal():  
139:    global outcome, in_play, p_hand, d_hand, deck, message1, message2, wins, losses  
140:    message1 = "Hit, Stand, or New Deal?"  
141:    deck = Deck()  
142:    deck.shuffle()  
143:    p_hand = Hand()  
144:    d_hand = Hand()  
145:    p_hand.add_card(deck.deal_card())  
146:    p_hand.add_card(deck.deal_card())  
147:    d_hand.add_card(deck.deal_card())  
148:    d_hand.add_card(deck.deal_card())  
149:    if in_play == True:  
150:      message1 = "Dealer Won-Hit, Stand or New Deal?"  
151:      losses += 1  
152:    print "Player's", p_hand  
153:    print "Dealer's", d_hand  
154:    print message1  
155:    print wins - losses  
156:    
157:    # your code goes here  
158:      
159:    in_play = True  
160:    
161:  def hit():  
162:    global message1, in_play, losses, wins  
163:    if in_play == True:  
164:      if p_hand.get_value() <= 21:   
165:        p_hand.add_card(deck.deal_card())  
166:      else:  
167:        message1 = "You bust-New Deal?"  
168:        in_play = False  
169:        losses += 1  
170:        print message1  
171:    print wins - losses  
172:    print "Player's", p_hand  
173:    print "Dealer's", d_hand  
174:    pass     # replace with your code below  
175:     
176:    # if the hand is in play, hit the player  
177:      
178:    # if busted, assign a message to outcome, update in_play and score  
179:        
180:  def stand():  
181:    global message1, in_play, losses, wins  
182:    if in_play == True:  
183:      if p_hand.get_value() > 21:  
184:        message1 = "You bust-New Deal?"  
185:        in_play = False  
186:        losses += 1  
187:        print message1  
188:      else:   
189:        while d_hand.get_value() < 17:  
190:          d_hand.add_card(deck.deal_card())  
191:        if d_hand.get_value() > 21:  
192:          message1 = "Dealer Busts-New Deal?"  
193:          wins += 1  
194:          print message1  
195:        else:  
196:          if p_hand.get_value() <= d_hand.get_value():  
197:            message1 = "Dealer Wins-New Deal?"  
198:            losses += 1  
199:            print message1  
200:          else:  
201:            message1 = "You Win-New Deal?"  
202:            wins += 1  
203:            print message1  
204:        in_play = False    
205:    print "Player's", p_hand  
206:    print "Dealer's", d_hand  
207:    print wins - losses  
208:    pass     # replace with your code below  
209:      
210:    # if hand is in play, repeatedly hit dealer until his hand has value 17 or more  
211:    
212:    # assign a message to outcome, update in_play and score  
213:    
214:  # draw handler    
215:  def draw(canvas):  
216:    p_pos = [100, 50]  #player hand position      
217:    d_pos = [100, 350]            #dealer draw position  
218:    p_hand.draw(canvas, p_pos)  
219:    d_hand.draw(canvas, d_pos)  
220:      
221:    #if in_play == True:  
222:      #d_hand.draw(canvas, d_pos)      
223:    #else:  
224:      #d_hand.draw(canvas, d_pos)  
225:      
226:    canvas.draw_text(message1, [30, 300], 30, "black")  
227:    canvas.draw_text("Blackjack", [300, 50], 50, "red")  
228:    canvas.draw_text("Player", [100, 170], 30, "blue")  
229:    canvas.draw_text("Dealer", [100, 470], 30, "blue")  
230:    canvas.draw_text("Score:" + str(wins - losses), [400, 130], 30, "white")  
231:      
232:      
233:  # initialization frame  
234:  p_hand = Hand()  
235:  d_hand = Hand()  
236:    
237:    
238:  frame = simplegui.create_frame("Blackjack", 600, 600)  
239:  frame.set_canvas_background("Green")  
240:    
241:    
242:  #create buttons and canvas callback  
243:  frame.add_button("Deal", deal, 200)  
244:  frame.add_button("Hit", hit, 200)  
245:  frame.add_button("Stand", stand, 200)  
246:  frame.set_draw_handler(draw)  
247:    
248:  # get things rolling  
249:  frame.start()  
250:    
251:    

No comments:

Post a Comment

Linguistics and Information Theory