简体   繁体   English

有人可以指导我如何在类中重用一个函数吗?

[英]Can someone please guide me on how to reuse a function in a class?

Can someone please guide me on how to reuse a function in class in order to receive a different output with import random? 有人可以指导我如何在类中重用一个函数,以便随机导入接收不同的输出?

This is a blackjack game that I am writing in VS Code using python 3.7 with Conda base as an interpreter. 这是一个二十一点游戏,我在VS Code中使用python 3.7编写, Conda base作为解释器。

I am trying to reuse the function player_hand(random card) and get a different result for player_score(the card value as an integer) 我正在尝试重用函数player_hand(随机卡)并为player_score获取不同的结果(卡值作为整数)

and then add those 2 scores for a final_player (final score) I would highly appreciate guidance and feedback on how to proceed on this challenge... 然后为final_player添加这2个分数(最终分数)我非常感谢如何继续应对这一挑战的指导和反馈......

import random

suit = {'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11, 'Two': 2, 'Three': 3,
        'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9}
symb = ['Spade', 'Clubs', 'Heart', 'Diamonds']

player_hand = random.sample(suit.items(), 1) + random.sample(symb, 1)
dealer_hand = random.sample(suit.items(), 1) + random.sample(symb, 1)

player_score = player_hand[0][1]
dealer_score = dealer_hand[0][1]
final_player = player_score + player_score
final_dealer = dealer_score + dealer_score


class Bet:
    def __init__(self, player, bank=0):
        self.bank = bank
        self.player = player

    def __str__(self):
        return f'Player balance: ${self.bank}\n'

    def bet(self):

        self.amount = int(input('Place bet:'))

        if self.bank <= self.amount:
            return 'put more $ '

        else:
            self.bank -= self.amount
            return f'Player balance: ${self.bank}'


class Card:

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

    def deal(self, player_hand, dealer_hand, dealer_score, player_score):
        while True:
            print('dealer', dealer_hand)
            print('dealer', dealer_score)

            print('player', player_hand)
            print('player', player_score)
            break


class Card2:

    def deal(self, player_hand, dealer_hand, dealer_score, player_score):
            while True:
                print('dealer', dealer_hand)
                print('dealer', dealer_score)

                print('player', player_hand)
                print('player', player_score)
                break

    def total_score(self):
        print(final_dealer)
        print(final_player)

    def winner(self):
        if final_dealer < final_player:
            return 'Player wins!'
        elif final_player < final_dealer:
            return 'dealer wins'


be = Bet('Player', bank=100)

print(be)
print(be.bet())
print('\n')

print(Card.deal('p', player_hand, dealer_hand, dealer_score, player_score))

print('\n')
print(Card2.winner('winner'))

Example of output below: 以下输出示例:

Player balance: $100
Place bet:5
Player balance: $95
dealer [('Queen', 10), 'Diamonds']
dealer 10
player [('Seven', 7), 'Heart']
player 7
None
dealer wins

I think the challenge here is in understanding how to use classes to model a problem, especially if you are coming to grips with object oriented programming (OOP) for your first time. 我认为这里的挑战在于理解如何使用类来模拟问题,特别是如果你是第一次掌握面向对象编程(OOP)的话。

Your idea for what makes a Card object (ie something that has a rank and a suit ) is a reasonable one. 你对Card对象(即具有等级套装的东西)的想法是合理的。 But that is all a card should have. 但这就是卡应该有的全部。 All cards just have these two properties, and it makes little sense to create classes like Card2 . 所有的卡都有这两个属性,创建像Card2这样的类是没有意义的。 The card is just a piece of paper, which should know nothing about the player or dealer who holds it, the other cards it is in a hand with, the player's money, etc. Including such extraneous data results in "coupling" where your player, bets, and cards all start depending on one another, leading to "spaghetti code." 这张卡片只是一张纸,它不应该知道持有它的玩家或经销商,手中的其他牌,玩家的钱等等。包括这些无关的数据导致你的玩家“耦合” ,赌注和卡片都是相互依赖的,导致“意大利面条代码”。

Here is a quick implementation of drawing Card objects from a Deck that I wrote up: 这是我编写的Deck中绘制Card对象的快速实现:

import random

class Player:
    def __init__(self, money):
        self.money = money

    def bet(self, amount):
        self.money -= amount

class Deck:
    def __init__(self):
        self.build()

    def build(self):
        self.cards = []
        for rank in Card.ranks:
            for suit in Card.suits:
                card = Card(rank, suit)
                self.cards.append(card)

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

    def draw(self):
        if self.cards != []:
            card = self.cards.pop()
            return card
        else:
            raise IndexError("Cannot draw from empty deck")

class Card:
    ranks = {
        "Two": 2, "Three": 3, "Four": 4, "Five": 5, 
        "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9,
        "Ten": 10, "Jack": 10, "Queen": 10, "King": 10,
        "Ace": 11,
    }
    suits = ["Spade", "Club", "Heart", "Diamond"]

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

    def get_value(self):
        return Card.ranks[self.rank]

    def __str__(self):
        return "{0} of {1}s".format(self.rank, self.suit)

if __name__ == "__main__":
    deck = Deck()
    deck.shuffle()
    for i in range(100):#should error out once deck is empty
        card = deck.draw()
        print(i, str(card))

Note that once you write the individual pieces (such as shuffling the deck, and drawing a card) the code in your main function should be intuitive. 请注意,一旦您编写了各个部分(例如洗牌并绘制卡片),主函数中的代码应该是直观的。 Please let me know if any of the code does not make sense. 如果任何代码没有意义,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据两个不同列的分数形成三个不同的类,有人可以指导我,请参考我的代码 - How to form three different classes based on scores of two different columns, can someone guide me, please refer my code 有人可以给我解释一下吗 - Can someone please explain to me 我们在 Selenium Java 中有 @FindBys 和 @FindAll,如何使用相同的代码在 Python 中查找定位器请指导我 - We have @FindBys and @FindAll in Selenium Java, how to use same code to find locators in Python please guide me someone 有人可以向我解释一下这个算法吗? - Can someone please explain me this algorithm? 有人可以向我解释这段代码 - python 3 - can someone please explain to me this code - python 3 有人可以向我解释这些代码行吗? - Can someone please explain me these lines of code? 在图表上绘制其上方条形的值。 有人可以指导我如何做到这一点吗? 谢谢 - Plotting values of the bar above it on the graph. Can someone guide me through how to do this? Thanks 有人可以用正确的方法指导我在以下代码中进行迭代吗 - Can someone guide me with correct way to iterate in the following code 任何人请指导我我该怎么做 web scarping 多页预订。com - - anyone please guide me how can i do web scarping multiple pages of booking.com - 有人可以解释一下内容丢失功能吗? - Can someone please explain the content loss function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM