我正在尝试用Python创建一个Go Fish游戏。但我偶然发现了一个小问题,我似乎无法弄清楚如何处理。
有一个人类玩家(玩家0)和三个电脑玩家(1-3岁)。人类玩家首先选择目标玩家。然后是卡级(例如,玩家可以瞄准玩家2并选择插孔,那么计算机就必须给玩家所有的插孔)。
到目前为止我所拥有的内容如下,但我遇到的问题就在代码的底部。到目前为止,代码生成一个牌组,为每个玩家创建牌,然后向玩家显示他/她的牌。然后向玩家询问他/她想要定位的计算机玩家以及卡的等级。
我遇到的问题是代码底部的最后一行(def player_0_hitman)。任何帮助将非常感激。基本上我遇到了三个问题。
基本上,我的代码忽略了if和else。我不明白为什么。一切看起来都是正确的,但由于一些奇怪的原因,即使在if之后,该程序也会运行其他的。
未返回“点击”。即使在定义中,我的命中设置为hit = hit - 1为最后一个,它仍然重新运行整个定义,就好像命中为1
我正在尝试使用计数线来计算正在转移的牌数,因此程序会告诉玩家当他获得成功猜测时他会获得多少张牌但是我只得到一张声明说我得到了每次无论如何都会有1张卡片(无论我是否获得卡片,或者我获得的卡片不止一张)。
我理解我需要做的基本知识,但我似乎无法获得有效的代码。我已经尝试将“for”改为“if”,但是我得到了各种各样的错误,所以我认为这不会起作用。然后我尝试在输入定义之前将“hit”转换为另一个代码,在内部更改它,然后在返回之前将其转换回来,但这似乎也无所作为,我仍然遇到相同的问题。我试图摆脱for,但我得到一个涉及“卡片的错误。
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
答案 0 :(得分: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)
答案 1 :(得分:0)
我看到的一些错误(如果他们已经在您的代码中,我很抱歉):
发布您遇到的错误也很有帮助,以帮助我们排除故障。
另外,我不认为这是Go Fish的演奏方式..
答案 2 :(得分:0)
免责声明:我不知道GoFish是什么或者它是如何播放的,但我从Python的角度回答这个问题。
Matt为你的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
我更新的内容:
使用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']
使用format mini language,您可以优化横幅广告制作:
>>> print('{0:~^70}'.format('Welcome to go fish!'))
~~~~~~~~~~~~~~~~~~~~~~~~~Welcome to go fish!~~~~~~~~~~~~~~~~~~~~~~~~~~
使用itertools.repeat
,您可以优化循环:
>>> def foo(i):
... return i
...
>>> list(itertools.repeat(foo('x'), 3))
['x', 'x', 'x']
此行str
中您不需要print str(",".join(new_hand))
,因为您通过将列表与','
一起加入来创建字符串。