首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中进行钓鱼

在Python中进行钓鱼
EN

Stack Overflow用户
提问于 2017-03-24 07:17:31
回答 2查看 791关注 0票数 2

对于我的班级,我必须制作一个可以正常工作的围棋钓鱼游戏。我在课堂上走了这么远,但我被卡住了,我不知道如何把球员送回手边,这样我就可以做一个检查声明,看看他是否有任何一种类型的4。有什么建议吗?

代码语言:javascript
复制
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()
EN

回答 2

Stack Overflow用户

发布于 2017-03-24 08:02:36

你所说的没有真正的意义。Hand是一个类;player1是该类的一个实例。翻译成个人术语,这相当于询问如何将Brandon送回human,以便您可以数他的牙齿。你不需要这样做:你只需使用对所有人都有效的牙齿计数程序。

具体看一下您的代码,我认为这与以下代码有关

代码语言:javascript
复制
player1.check(player1)

它所需要的就是

代码语言:javascript
复制
player1.check()

player1是一个Hand代码;此调用转到Hand的check方法。在这里,调用该方法的对象自动显示为第一个参数self<代码>E219。去掉第二个参数,只需使用

代码语言:javascript
复制
def check(self):

这是否澄清了混淆之处?

票数 2
EN

Stack Overflow用户

发布于 2017-03-24 07:24:10

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42988713

复制
相关文章

相似问题

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