如何为我的简单纸牌游戏压缩冗长的代码?

时间:2018-12-31 09:40:50

标签: python

代码按照我想要的方式工作,但是我认为random.shuffle(deck)下的所有内容都是错误/冗长的代码。我正在寻找有关如何减少代码并实现相同输出的任何建议。例如,我不是在寻找Ace = 0King = 0,...,Two = 0(在游戏开始时打出的那种类型的纸牌数量),而是在寻找类似于Ace, King, ..., Two = 0(例如,为所有卡写入一次= 0,而不是写入= 0十三次)。

import random

cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["Jack", "Queen", "King", "Ace"]
deck = []

for i in range(2,11):
    cardfaces.append(str(i))

for j in range(4):
    cardfaces.append(royals[j])

for k in range(4):
    for l in range(13):
        card = (cardfaces[l] + " of " + suits[k])
        deck.append(card)

random.shuffle(deck)

total = 0

Ace = 0
King = 0
Queen = 0
Jack = 0
Ten = 0
Nine = 0
Eight = 0
Seven = 0
Six = 0
Five = 0
Four = 0
Three = 0
Two = 0

print("Welcome to Card Game")

while True:
    a = input("Continue? y/n:")
    if a == "y":
        total += 1
        if "Ace" in (deck[total]):
            Ace += 1
        elif "King" in (deck[total]):
            King += 1
        elif "Queen" in (deck[total]):
            Queen += 1
        elif "Jack" in (deck[total]):
            Jack += 1
        elif "10" in (deck[total]):
            Ten += 1
        elif "9" in (deck[total]):
            Nine += 1
        elif "8" in (deck[total]):
            Eight += 1
        elif "7" in (deck[total]):
            Seven += 1
        elif "6" in (deck[total]):
            Six += 1
        elif "5" in (deck[total]):
            Five += 1
        elif "4" in (deck[total]):
            Four += 1
        elif "3" in (deck[total]):
            Three += 1
        elif "2" in (deck[total]):
            Two += 1
        print(deck[total],  "   K(", King, ")""  Q(", Queen, ")" "  J(", Jack, ")"
            "  10(", Ten, ")" "  9(", Nine, ")""  8(", Eight, ")" "  7(", Seven, ")"  
            "  6(", Six, ")" "  5(", Five, ")""  4(", Four, ")" "  3(", Three, ")" "  2(", Two, ")"
            "  A(", Ace, ")" "  [Cards left:", 52 - total, "]")
        continue
    elif a == "n":
        print("Game Over")
        break
    else:
        print("Enter either y or n")

1 个答案:

答案 0 :(得分:2)

  1. 主要内容:每当您看到代码中的基本结构重复时,这就是考虑使用支持迭代的循环和数据结构的明显标志。

    在您的情况下,主要问题是卡片面-而不是使用13个变量来处理金额,最好将所有内容保留在单个词典中-这将使您能够“以编程方式”使用它:

    hand = {
        'Ace': 0,
        'King': 0,
        'Queen': 0,
        'Jack': 0,
        'Ten': 0,
        'Nine': 0,
        'Eight': 0,
        'Seven': 0,
        'Six': 0,
        'Five': 0,
        'Four': 0,
        'Three': 0,
        'Two': 0
    }
    
    ...
    
    for face in hand:
        if face in deck[total]:
            hand[face] += 1
    

    如果要进一步优化,可以使用

    faces = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two']
    hand = dict.fromkeys(faces, 0)
    

    这里的重点是使用相同的值来识别“手”和“副牌”中的牌

  2. 一旦有了这个,就可以清楚地知道您并不需要total计数器,因为您可以使用hand动态访问sum(hand.values())字典中的所有值(实际上,您最有可能在“绘画”时最好从卡组中取出卡,而只需使用len(deck)