-2

我正在尝试用 Python 创建一个 Go Fish 游戏。但是我偶然发现了一个小问题,我似乎无法弄清楚如何处理。

有一个人类玩家(玩家 0)和三个电脑玩家(从 1-3)。人类玩家首先选择目标玩家。然后是牌的等级(例如,玩家可以针对玩家 2 并选择 Jack,然后计算机必须给玩家所有的 Jack)。

到目前为止我所拥有的内容如下,但我遇到的问题就在代码的底部。到目前为止,代码生成了一个套牌,为每个玩家创建手牌,然后向玩家展示他/她的牌。然后询问玩家他/她想要针对哪个计算机玩家以及牌的等级。

我遇到的问题是代码底部的最后一组行(def player_0_hitman)。任何帮助将非常感激。基本上我遇到了三个问题。

  1. 基本上,我的代码忽略了 if 和 else。我不明白为什么。一切似乎都正确定位,但出于某种奇怪的原因,即使在 if 之后,程序也会运行 else。

  2. “命中”没有被退回。即使在定义中,我将最后一个 else 的命中设置为 hit = hit - 1,它仍然会再次重新运行整个定义,就好像命中是 1

  3. 我正在尝试使用计数线来计算正在转移的卡片数量,因此程序会告诉玩家当他成功猜测时他获得了多少张卡片,但我只得到一个声明说我每次都得到 1 张卡片什么(无论我没有得到卡还是得到多张卡)。

我了解我需要做什么的基础知识,但我似乎无法为此获得工作代码。我已经尝试将“for”更改为“if”,但我得到了各种各样的错误,所以我认为这不会奏效。然后我尝试在输入定义之前将“命中”转换为另一个代码,在内部进行更改,然后在返回之前将其转换回来,但这似乎也无济于事,我仍然遇到同样的问题。我试图摆脱 for 但我收到一个涉及“card.

import random

def SetDeck():
    suitList = ["s", "c", "d", "h"]
    rankList = ["a", "2", "3", "4", "5", "6", "7", "8", "9", "t", "j", "q", "k"]
    deck = []
    for suite in range(4):
        for rank in range(13):
            deck.append(rankList[rank]+suitList[suite])
    return deck

def Shuffle(deck):
    nCards = len(deck)
    for i in range(nCards):
        j = random.randint(i,nCards-1)
        deck[i], deck[j] = deck[j], deck[i]
    return deck

def GetTopCard(shuffledDeck):
    return shuffledDeck.pop(0)

def DealInitialCards(nPlayers,nCards,shuffledDeck):
    playersCards = [["" for j in range(nCards)] for i in range(nPlayers)]
    for j in range(nCards):
        for i in range(nPlayers):
            playersCards[i][j] = GetTopCard(shuffledDeck)
    return playersCards

def Sort(cards):
    rankString = "a23456789tjqk"
    swapped=True
    while swapped:
        swapped = False
        for i in range(len(cards)-1):
            if rankString.find(cards[i][0])>rankString.find(cards[i+1][0]):
                cards[i],cards[i+1]=cards[i+1],cards[i]
                swapped = True
    return


def ShowCards(player,cards):
    print("\n****************************************************")
    print("************Player "+str(player)+" has**************")
    print("****************************************************\n")
    for i in range(len(cards)):
        print(cards[i]),
    print("\n")
    return

def ShowMessage(msg):
    print("****************************************************")
    print(str(msg))
    print("****************************************************\n")
    return

def remove_suits(player):
    new_hand = []
    for card in pHands[player]:
        new_card = card[0]
        new_hand.append(new_card)
    return new_hand

def choosing_target():
    target_player = raw_input ("Who do you want to ask? (1-3)")
    while target_player.isdigit() == False or 1 > int(target_player) or 3 < int(target_player):
        print "Error: Must type a valid player id (from 1 to 3)"
        target_player = raw_input ("Who do you want to ask? (1-3)")
    target_player = int(target_player)
    return target_player

def target_rank():
    target_card = raw_input ("What rank are you seeking? (" + str(",".join(new_hand)) + ")")
    while target_card not in new_hand:
        print "Error: Must type one of the follow valid single character card ranks"
        print str(",".join(new_hand))
        target_card = raw_input ("What rank are you seeking? (" + str(",".join(new_hand)) + ")")
    return target_card

print("~"*70)
print("~"*25+"WELCOME TO GO FISH!"+"~"*26)
print("~"*70)

nPlayers = 4
nCards = 10
deck = SetDeck()
sDeck = Shuffle(deck[:])
pHands = DealInitialCards(nPlayers,nCards,sDeck)
Sort(pHands[0])
ShowCards(0,pHands[0])

hit = 1

while hit == 1 :
    ShowMessage("TURN: Player 0, its your turn.")
    target_player = choosing_target()
    new_hand = remove_suits(0)
    target_card = target_rank()
    ShowMessage("Target: Player " + str(target_player) + " is being targeted for the rank <" + str(target_card) + ">")
    temp_hit = player_0_hitman(hit)
    print "hit = " + str(hit)

def player_0_hitman(hit):
    for card in pHands[target_player]:
        if target_card[0] == card[0]:
            count = pHands[target_player].count(card)
            pHands[0].append(card)
            pHands[target_player].remove(card)
            ShowMessage("HIT: " + str(count) + " card(s) transferred")
        else:
            top_card = GetTopCard(sDeck)
            pHands[0].append(top_card)
            if top_card[0] == target_card[0]:
                ShowMessage("HIT: LUCKILY Player 0 has fished up a rank <" + str(top_card[0]) + ">!!!")
            else:
                ShowMessage("MISS: You fished up the rank <" + str(top_card[0]) + ">")
                hit = hit - 1
4

3 回答 3

1

替换以下内容:

if any(card[0] == target_card for card in pHands[target_player]):
    transfer_cards = card[0] == target_card in pHands[target_player]
    del card[0] == target_card in pHands[target_player]
    if any(card[0] == target_card for card in pHands[0]):
        pHands[0].extend(transfer_cards)

# Make a copy of the list so we don't modify it while enumerating it [:]
for i, card in enumerate(pHands[target_player][:]):
    # Example: "Do you have a seven?"
    if target_card[0] == card[0]:
        pHands[0].append(target_card)
        del pHands[target_player][i]

还有一个快速提示,首先更改此代码块以消除硬编码索引:

for suite in range(4):
     for rank in range(13):
         deck.append(rankList[rank]+suitList[suite])

for suite in suitList:
     for rank in rankList:
         deck.append(rank+suit)
于 2013-08-02T16:09:05.093 回答
0

我看到了一些错误(如果它们已经在您的代码中,我深表歉意):

  • 你的变量 target_card 只保存卡片的价值,而不是花色。您可能需要将整张牌一分为二,因为它们包括花色和价值
  • 那不是正确使用 del 命令;您无需将其设置为等于任何值或测试是否相等。

发布您遇到的错误也很有帮助,以帮助我们进行故障排除。

另外,我不认为这就是 Go Fish 的玩法。

于 2013-08-02T14:03:49.080 回答
0

免责声明:我不知道 GoFish 是什么或它的播放方式,但我从 Python 的角度回答这个问题。

马特为您的 if 语句给出了答案,但我看到您正在复制一些 Python 可用的东西。

使用itertools.product您可以替换您的SetDeck方法,并且正如其他人所提到的那样,已经存在sort并且sorted已经可用。这和其他一些重构,作为初学者,你最终得到以下内容:

import itertools
import random

def create_deck(suits, cards):
      return list(''.join(i).upper() for i in itertools.product(suits, cards))

def shuffle_deck(deck):
    return random.shuffle(deck)

def get_top_card(deck):
    return shuffle_deck(deck)[0]

def deal_cards(players, cards, deck):
    player_cards = {}
    for i in players:
        # For each player, shuffle the deck
        # then get as many cards as the cards
        # variable from the deck
        player_cards[i] = list(itertools.repeat(get_top_card(deck), cards))
    return player_cards

def show_message(message):
    border = '*'*52 
    return '{0}\n{1:*^52}\n{2}\n'.format(border, message, border)

def show_cards(player, cards):
    print(show_message('Player {0} has'.format(player)))
    print('\n'.join(cards[player]))

def remove_suits(player, cards, suit):
    new_cards = []
    for i in cards[player]:
       if not i.startswith(suit):
           new_cards.append(i)

    cards[player] = new_cards
    return cards

def choosing_target():
    choice = raw_input("Who do you want to ask? (1-3)")
    try:
        choice = int(choice)
    except ValueError:
        print('Error, you must enter a number')
        choosing_target()
    if 1 < choice < 4:
        print('Please enter a number between 1 and 3')
        chooing_target()
    return choice  

def target_rank(ranks):
    ranks_choice = ','.join(ranks)
    choice = raw_input("What rank are you seeking? ({0})".format(ranks_choice))
    while choice not in ranks:
        print("You much choose from one of the following\n")
        print("{0}".format(ranks_choice))
        choice = raw_input("What rank are you seeking? ({0})".format(ranks_choice))
    return choice

我更新的东西:

  1. 使用itertools.product将为您提供所需的组合:

    >>> suitList = ["s", "c", "d", "h"]
    >>> rankList = ["a", "2", "3", "4", "5", "6", "7", "8", "9", "t", "j", "q", "k"]
    >>> list(''.join(i).upper() for i in itertools.product(suitList, rankList))
    ['SA', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', 'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'HA', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'HT', 'HJ', 'HQ', 'HK']
    
  2. 使用格式 mini language,您可以优化您的横幅创建:

    >>> print('{0:~^70}'.format('Welcome to go fish!'))
    ~~~~~~~~~~~~~~~~~~~~~~~~~Welcome to go fish!~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  3. 使用itertools.repeat,您可以稍微优化循环:

    >>> def foo(i):
    ...    return i
    ...
    >>> list(itertools.repeat(foo('x'), 3))
    ['x', 'x', 'x']
    
  4. 您不需要str在此行print str(",".join(new_hand))中,因为您正在通过将列表加入来创建字符串','

于 2013-08-03T01:52:06.217 回答