首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python blackjack代码

Python blackjack代码
EN

Code Review用户
提问于 2022-06-04 06:30:50
回答 1查看 553关注 0票数 4

下面的代码,对于python来说是非常新的,它会喜欢一些建设性的批评,主要是关于我可以改进什么,如果我使用aces (在这里我减去10)是聪明的,以及我对函数的使用?

我的代码是从向经销商和用户发送两张卡片开始,这是随机的,然后询问用户是否想要另一个card...if,他们说不,经销商得到他们的卡片,如果他们键入是,然后他们得到另一张卡片,然后再问这个问题。我在使用上有困难,所以我基本上从所有超过21岁的人中减去10,因为这基本上是人们玩黑棋的方式(如果他们可以选择11,并且保持在21岁以下,就没有人会选择1)。

对于那些对规则感到好奇的人来说:21岁是一种用扑克牌玩的赌场游戏。这场比赛的目标是抽签,总积分尽可能接近21分而不超过。所有的面牌数为10分,aces数为1或11,所有其他牌数其数值。

这个游戏是针对一个毒贩的。玩家试图接近21 (不超过)比经销商。如果经销商崩溃(超过21),玩家会自动获胜(前提是球员还没有被逮捕)。经销商必须始终按照一套固定的规则取牌。发牌者在获得至少17张牌之前都会取牌。如果经销商的手包含一个王牌,则当该牌的总数在17至21之间(包括在内)时,该牌将被计算为11;否则,该王牌将被计算为1。

代码语言:javascript
复制
import random

deck =(2,3,4,5,6,7,8,9,10,10,10,10,11) # main deck tuple including aces (aces become 1 if user > 21)
dealer_hand = [] # dealer list to hold cars
user_hand = [] # user list to hold cards
    
def draw(): # function that will be called to draw a random card from the deck
    new_card = random.choice(deck)
    return new_card

def dealer_draw(user_total):
    if user_total < 21:
        while sum(dealer_hand) < 17:
            dealer_hand.append(draw())
    return dealer_hand

def blackjack(): # game fuction
    for i in range(2): # for loop to draw 2 cards to both the user and dealer
        user_hand.append(draw())
        dealer_hand.append(draw())
        
    print(f'User has: {user_hand}')
    print(f'Dealer has: {dealer_hand}')
    
    continue_game = True # will be used to terminate while loop
    
    while continue_game == True and sum(user_hand) < 21:
        drawing = input("Would you like to draw another card (y/n)       : ").lower()
        
        if drawing == 'y': # if users types y, it draws another card
            user_hand.append(draw())
            
            if 11 in user_hand and sum(user_hand) > 21: # aces (11's) get converted to 1's if > 21
                user_hand.remove(11)
                user_hand.append(1)
                
            print(f'User now has has: {user_hand}')
            print(f'Dealer has: {dealer_hand}')
            
        else:
            continue_game = False        
        
    dealer_draw(sum(user_hand)) # Function to draw card for dealer (if necessary)
                              
    print("~~~~~~~~~~~~~~~~~ Final results ~~~~~~~~~~~~~~~~~")
    print(f"User has {user_hand} for a total of {sum(user_hand)}")
    print(f"Dealer has {dealer_hand} for a total of {sum(dealer_hand)}")
    
    if sum(user_hand) > 21: #if statements check for bust, then draws, then checks for values between user/dealer 
        print("User busts! Dealer wins")
    elif sum(user_hand) == sum(dealer_hand):
        print("Draw")
    elif sum(dealer_hand) > sum(user_hand) and sum(dealer_hand) <= 21:
        print("Dealer wins")
    else:
        print("User wins")
    

# Main Game
print('____________________________________________________________________')
print("                      Welcome to Blackjack           ")
print("Blackjack is a card game where the user goes against the dealer.")
print("Your Goal is to draw cards to get closest to 21 points,")
print("however you don't want to go above 21 points because you will lose!")


play_game = False
while play_game == False:
    play = input("          Would you like to play?     (y/n)       :       ").lower()

    if play == "y":
        blackjack()
        play_game = True
    elif play == "n":
        print('_______________________________________________________________')
        print("Goodbye")
        play_game = True
    else:
        print("You did not enter either 'y' or 'n'.")
EN

回答 1

Code Review用户

发布于 2022-06-04 10:27:36

关于你使用功能的问题:我认为你没有充分利用它们。请注意,我可以删除大量您的注释,因为从代码中可以清楚地看到代码所做的事情,只需通过提取函数并对它们进行适当的命名(我将推荐伯伯清洁代码中的章节命名公约 )。我认为你和aces的解决方案是好的。

哦,我还把所有的东西都移到了一个类中,所以只要初始化一个新实例就可以更容易地重新启动游戏。这样,游戏可以玩不止一次,而不重新启动整个应用程序。

代码语言:javascript
复制
import random


def draw_for(hand):
    deck = (2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11)  # main deck tuple including aces (aces become 1 if user > 21)
    new_card = random.choice(deck)
    hand.append(new_card)


class BlackJack:
    def __init__(self):
        self.user_hand = None  # init so pycharm doesn't warn
        self.dealer_hand = None

    def play(self):  # game function
        self.reset()
        self.draw_starter_cards()
        self.print_hands()

        self.main_action()
        self.dealer_draw_to_limit()

        self.print_final_hands()
        self.print_winner()

    def reset(self):
        self.dealer_hand = []
        self.user_hand = []

    def main_action(self):  # could use a better name
        continue_game = True
        while continue_game and not self.user_busted():
            drawing = input("Would you like to draw another card (y/n)       : ").lower()

            if drawing == 'y':
                self.user_draws()
                self.print_hands()
            else:
                continue_game = False

    def user_busted(self):
        return sum(self.user_hand) > 21

    def user_draws(self):
        draw_for(self.user_hand)

        if self.user_has_aces() and self.user_busted():
            self.convert_aces()

    def user_has_aces(self):
        return 11 in self.user_hand

    def convert_aces(self):
        self.user_hand.remove(11)
        self.user_hand.append(1)

    def dealer_draw_to_limit(self):
        if not self.user_busted():
            while sum(self.dealer_hand) < 17:
                draw_for(self.dealer_hand)
        return self.dealer_hand

    def print_winner(self):
        if self.user_busted():
            print("User busts! Dealer wins")
        elif sum(self.user_hand) == sum(self.dealer_hand):
            print("Draw")
        elif sum(self.user_hand) < sum(self.dealer_hand) <= 21:
            print("Dealer wins")
        else:
            print("User wins")

    def print_final_hands(self):
        print("~~~~~~~~~~~~~~~~~ Final results ~~~~~~~~~~~~~~~~~")
        print(f"User has {self.user_hand} for a total of {sum(self.user_hand)}")
        print(f"Dealer has {self.dealer_hand} for a total of {sum(self.dealer_hand)}")

    def print_hands(self):
        print(f'User has: {self.user_hand}')
        print(f'Dealer has: {self.dealer_hand}')

    def draw_starter_cards(self):
        for i in range(2):
            draw_for(self.user_hand)
            draw_for(self.dealer_hand)
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/277080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档