Welcome, guest | Sign In | My Account | Store | Cart

This is a blackjack game code that I have programed first. Welcome to test it. In the game, ace will be fixed as low (value=1). Thanks.

Python, 142 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142``` ```from random import * from math import * #GLOBAL VARIABLES cards = range(0,52) def randRange(in_lower,in_upper): """ generates a random number between in_lower and in_upper""" temp_range = in_upper - in_lower return int(round((temp_range)*random() + (in_lower))) def popRandArray(in_list): return in_list.pop(randRange(0,len(in_list)-1)) def realDealCard(): global cards if len(cards)==0: print "new deck" cards = range(0,52) return popRandArray(cards) def cardAsString(in_card): value = ["ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king"] suit = ["hearts","diamonds","spades","clubs"] return value[in_card%13]+ " of " + suit[in_card/13] def cardScore(in_card): score = in_card%13+1 if score > 10: score = 10 return score print "\$Blackjack\$" player_reply="r" while player_reply == "r" : #~ player is delt with two cards player_card1 = realDealCard() player_card2 = realDealCard() #~ show player the two cards print "your card1 is", cardAsString(player_card1) print "your card2 is", cardAsString(player_card2) #~ count score of player player_score = cardScore(player_card1) + cardScore(player_card2) #~ show playerthe score print "your score is", player_score #~ computer is delt with two cards computer_card1 = realDealCard() computer_card2 = realDealCard() #~ show player one of the two cards print "The card1 of computer is", cardAsString(computer_card1) #~ count score of computer computer_score = cardScore(computer_card1) + cardScore(computer_card2) #~ ask players action while True: player_action = str(raw_input("twist (t) or stick (s)?")) #~ if player chooses twist while player_action == "t" : #~ player is delt with one more card player_card3 = realDealCard() #~ show player the third card print "your new card is", cardAsString(player_card3) #~ count current score of player player_score += cardScore(player_card3) #~ show player current score print "your score is", player_score #~ check bust #~ if current score of player > 21 if player_score > 21 : #~ bust print "you bust" #~ player lose print "you lose and computer wins" break elif player_score == 21 : #~player has a blackjack print "blackjack!" #~win print "you win and computer loses" player_action = "" elif player_score < 21 : player_action = str(raw_input("twist (t) or stick (s)?")) #~ elif current score of player == 21 #~ elif player chooses stick if player_action == "s" : #~ dealers turn print "you choose stick" print "It is computers turn" #~ if first score of computer <= 18 while computer_score <=18 : #~ computer chooses twist print "computer twist" #~computer is delt one more card computer_card3 = realDealCard() computer_score += cardScore(computer_card3) #~ check bust #~ if current score of computer > 21 if computer_score > 21 : #~computer bust print "computer score is", computer_score print "computer bust and You win" break elif computer_score == player_score : print "computer score is", computer_score print "draw- No winner" break #~ elif first two score > 18 elif computer_score > 18 : #~computer choose stick print "computer stick" #~ print "computer score is", computer_score #~compare score if computer_score < player_score : print "computer score is", computer_score print "you win and computer loses" elif computer_score > player_score : print "computer score is", computer_score print "you lose and computer wins" break break break player_reply = str(raw_input("restart (r) or quit (q)?")) ```

Charlie Clark 14 years, 9 months ago

I think this is an example of code that just looks from the level of indentation like it should be refactored.

A couple of notes: try and avoid the from x import * approach. If you want access to all a module's contents then just import the module and keep the namespace.

If you have a class for your card you can delegate scoring and representation to instances.

``````class Card(object):
value = 0
identity = ""
``````

You can then initialise a whole deck of cards and simply pop() from it as you would do with a normal deck.

You might do the same for the players

``````class Player(object):
cards = []
``````

This will let you have a single function that compares scores decides who has won. It's probably a good idea to take this up on a mailing list.

Charlie Clark 14 years, 9 months ago

Avoid using "globals" unless you have no other choice. Python functions can always see global variables but should not be able to modify them. Pass values in, modify them and return them but never modify constants.

Charlie Clark 14 years, 9 months ago

He's a reworked version. It's far from perfect but hopefully a bit more pythonic.

``````import random

VALUES = ["ace", "two","three","four","five","six", "seven","eight","nine","ten","jack","queen","king"]

class Card(object):

def __init__(self, value, name, suit):
self.value = value
self.name = "%s of %s" % (name, suit)

def __repr__(self):
return self.name

class Player(object):

deck = []

def __init__(self, name=""):
self.name = name
self.cards = []
self.score = 0
self.deck = deck
self.twist()
self.twist()
self.playing = True

def twist(self):
card = self.deck.pop()
self.score += card.value
self.cards.append(card)
if self.score > 21:
raise ValueError("Bust!")
return card

def stick(self):
if self.score < 15:
return "You cannot stick with less than 15!"
else:
self.playing = False

class Computer(Player):

def play(self):
"""What the computer decides to do"""
if self.score < 19:
print("The computer twists")
print(self.twist())

def deal():
deck = []
for s in SUITS:
for idx, v in enumerate(VALUES):
card = Card(idx + 1, v, s)
deck.append(card)
random.shuffle(deck)
return deck

def score(Player1, Player2):
if Player1.score < 18:
return
elif Player1.score > Player2:
return "You win!"
else:
return "You lose!"

if __name__ == '__main__':
deck = deal()
player = Player()
computer = Computer()
print("Your cards %s %s" % (player.cards[0], player.cards[1]))
print("The computer's first card is %s" % computer.cards[0])

while player.playing:
action = raw_input("twist (t) or stick (s)?")
if action == "t":
print player.twist()
elif action == "s":
print(player.stick())
result = score(player, computer)
while not result:
computer.play()
result = score(player, computer)
print(result)
``````
Larry Hastings 14 years, 9 months ago

It is inappropriate to use the recipes database as a way of asking for help. Please delete this or something.

Gary Eakins 14 years, 9 months ago

Here is the address of the Python Tutor mailing list:

http://mail.python.org/mailman/listinfo/tutor

That is a better place to post your code and get help.

Don't clutter the recipes.

Stephen Chappell 14 years, 7 months ago

Would you mind debugging your program before submitting it first? The second one has an infinite loop somewhere.

 Created by Neo Gao on Sun, 19 Jul 2009 (MIT)