用Python去钓鱼

时间:2017-03-23 23:17:31

标签: python

对于我的班级,我必须做一个正在进行的Go鱼游戏。我在课堂上得到了这么多,但是我不知道如何将球员送回手中,所以我可以做一个检查声明,看他是否有任何四种。有什么建议吗?

class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]

    def __init__(self, rank, suit):
        self.rank = rank 
        self.suit = suit

    def __str__(self):
        rep = self.rank + self.suit
        return rep


class Hand(object):
    """ A hand of playing cards. """
    def __init__(self):
        self.cards = []
    def __str__(self):
        if self.cards:
           rep = ""
           for card in self.cards:
               rep += str(card) + "  "
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)

    def check(self,player):
        print(player1)
        for self.cards in rep:
            print("i")
            #####################
class Deck(Hand):
    """ A deck of playing cards. """
    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS: 
                self.add(Card(rank, suit))

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print ("Out of cards!")

def main():
    deck1 = Deck()
    deck1.populate()
    deck1.shuffle()
    player1 = Hand()
    player2 = Hand()
    hands = [player1, player2]
    deck1.deal(hands, per_hand = 5)
    print(player1)
    player1.check(player1)
main()

2 个答案:

答案 0 :(得分:2)

你所说的并不是真的有意义。 是一个班级; player1 是该类的一个实例。翻译成个人用语,这与询问如何将 Brandon 发送回平行,这样您就可以算上他的牙齿了。你不是:你只是使用适合所有人的牙齿计数程序。

专门查看您的代码,我认为这涉及到行

player1.check(player1)

它应该需要的只是

player1.check()

player1 ;此调用转到检查方法。这里,调用该方法的对象自动显示为第一个参数 self 。摆脱第二个,只需使用

def check(self):

这是否澄清了混淆点?

答案 1 :(得分:1)

检查此代码,这是Go Fish可执行文件的工作版本,可从控制台播放。看看他们如何使用:

def makeTurn(self):
        print '%s\'s hand: %s' % (self.name,self.displayHand())
        chooseCard = raw_input('What card do you ask for? ').strip()
        if chooseCard == 'quit':
            sys.exit(0)
        if chooseCard not in self.hand:
            print 'You don\'t have that card. Try again! (or enter quit to exit)'
            chooseCard = self.makeTurn()
        return chooseCard

以下是完整的Python Go Fish game

import random
import sys
from collections import defaultdict

class HumanPlayer(object):
    def __init__(self,deck):
        self.hand = defaultdict(int)
        self.book = []
        self.deck = deck #making a copy of deck, all changes within
                        #this class should affect the global deck
        self.score = 0
        self.name = raw_input('Name yourself: ')

    def Draw(self): #assuming that deck is a global
        cardDrawn = self.deck.pop() #removes the last card from deck
        self.hand[cardDrawn] += 1 #adds card to hand
        print '%s drew %s.' % (self.name,cardDrawn)
        self.checkForBooks()

    def checkForBooks(self):
#       Removes all items of which are 4.
        for key,val in self.hand.items(): #can't use iteritems() because we are modifying hand in loop
            if val == 4: #completed a book
                self.book.append(key)
                print '%s completed the book of %s\'s.' % (self.name,key)
                self.score += 1
                del self.hand[key]
        self.emptyCheck()

    def emptyCheck(self):
        if len(self.deck)!=0 and len(self.hand)==0: #checks if deck/hand is empty
            self.Draw()
    def displayHand(self): #Displays current hand, cards separated by spaces
        return ' '.join(key for key,val in self.hand.iteritems()
                        for i in range(val)) #meh, make it prettier

    def makeTurn(self):
        print '%s\'s hand: %s' % (self.name,self.displayHand())
        chooseCard = raw_input('What card do you ask for? ').strip()
        if chooseCard == 'quit':
            sys.exit(0)
        if chooseCard not in self.hand:
            print 'You don\'t have that card. Try again! (or enter quit to exit)'
            chooseCard = self.makeTurn()
        return chooseCard

    def fishFor(self,card):
        if card in self.hand: # if card in hand, returns count and removes the card from hand
            val = self.hand.pop(card)
            self.emptyCheck()
            return val
        else:
            return False
    def gotCard(self,card,amount):
        self.hand[card] += amount
        self.checkForBooks()



class Computer(HumanPlayer):
    def __init__(self,deck):
        self.name = 'Computer'
        self.hand = defaultdict(int)
        self.book = []
        self.deck = deck
        self.opponentHas = set()
        self.score = 0

    def Draw(self): #assuming that deck is a global
        cardDrawn = self.deck.pop() #removes the last card from deck
        self.hand[cardDrawn] += 1 #adds card to hand
        print '%s drew a card.' % (self.name)
        self.checkForBooks()

    ##AI: guesses cards that knows you have, then tries cards he has at random.
    ##Improvements: remember if the card was rejected before, guess probabilities
    def makeTurn(self):
#        print self.displayHand(),self.opponentHas
        candidates = list(self.opponentHas & set(self.hand.keys())) #checks for cards in hand that computer knows you have
        if not candidates:
            candidates = self.hand.keys() #if no intersection between those two, random guess
        move = random.choice(candidates)
        print '%s fishes for %s.' % (self.name,move)
        return move

    def fishFor(self,card): #Same as for humans players, but adds the card fished for to opponentHas list.
        self.opponentHas.add(card)
        if card in self.hand: # if card in hand, returns count and removes the card from hand
            val = self.hand.pop(card)
            self.emptyCheck()
            return val
        else:
            return False

    def gotCard(self,card,amount):
        self.hand[card] += amount
        self.opponentHas.discard(card)
        self.checkForBooks()

class PlayGoFish(object):
    def __init__(self):
        self.deck = ('2 3 4 5 6 7 8 9 10 J Q K A '*4).split(' ')
        self.deck.remove('')
        self.player = [HumanPlayer(self.deck),Computer(self.deck)] #makes counting turns easier

    def endOfPlayCheck(self):#checks if hands/decks are empty using the any method
            return self.deck or self.player[0].hand or self.player[1].hand

    def play(self):
        random.shuffle(self.deck)
        for i in xrange(9): # Deal the first cards
            self.player[0].Draw()
            self.player[1].Draw()
        turn = 0
        while self.endOfPlayCheck():
            print '\nTurn %d (%s:%d %s:%d) %d cards remaining.' % (turn,self.player[0].name,
                    self.player[0].score,self.player[1].name,self.player[1].score,len(self.deck))
            whoseTurn = turn%2
            otherPlayer = (turn+1)%2
            while True: #loop until player finishes turn
                cardFished = self.player[whoseTurn].makeTurn()
                result = self.player[otherPlayer].fishFor(cardFished)
                if not result: #Draws and ends turn
                    self.player[whoseTurn].Draw()
                    break
                print '%s got %d more %s.' % (self.player[whoseTurn].name,result, cardFished)
                self.player[whoseTurn].gotCard(cardFished,result)
                if not self.endOfPlayCheck(): break
            turn+=1
        print '\nScores: \n%s: %d\n%s: %d\n' % (self.player[0].name,self.player[0].score,
                                          self.player[1].name,self.player[1].score)
        if self.player[0].score>self.player[1].score:
            print self.player[0].name,'won!'
        elif self.player[0].score==self.player[1].score:
            print 'Draw!'
        else:
            print self.player[1].name,'won!'

if __name__=="__main__":
    game = PlayGoFish()
    game.play()