首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python项目类型错误: Chips.place_bet()缺少一个必需的位置参数

Python项目类型错误: Chips.place_bet()缺少一个必需的位置参数
EN

Stack Overflow用户
提问于 2022-11-07 19:10:46
回答 1查看 25关注 0票数 1

我正在尝试编写我的第一个python项目blackjack。我被建议在不同的文件中用每个类及其方法编写程序,这样代码就更易于管理了。我将代码分成更小的文件,并使用导入语句。

当我运行我的代码时,会收到以下错误消息:

Chips.place_bet()缺少一个必需的位置参数。self

我认为self是,原谅双关语,不言自明。我不需要为self设置一个值。我想知道这是否是一个重要的问题。

我试图让我的place_bet功能激活,以便我可以要求用户输入的筹码数目为一个赌注。有人能告诉我怎么做吗?

我的代码分散在以下文件上:

blackjack.py

代码语言:javascript
复制
import random

from player import Player
from hand import Hand
from chips import Chips
from deck import Deck
from card import Card
# import helper_functions

# Blackjack/
# ├── app/
# │   ├── card.py
# │   ├── chips.py
# │   ├── deck.py
# │   ├── hand.py
# │   ├── player.py
# │   ├── main.py
# │   ├── helper_functions.py

# Gameplay and Outline of Project

# Welcome message and rules
print("Welcome to Blackjack! The rules for blackjack can be found here. https://www.youtube.com/watch?v=PljDuynF-j0")
print("The object of this blackjack game is to make it to 100 chips. You will start with 25 chips.")

# Establish player name
print("Please insert your player name: ")
player_name = input()
print('Please insert your player name ' + player_name)
print("Lets get started" + player_name + "please place your bet!")
# Place the bets BEFORE the cards are dealt. Pure risk.
place_bet()
# .  Deal 2 cards to user and dealer
# . print a message explaining the total hand value of the user. ask player to hit/stay?
# . If the player busts print player busts. if the player is under 21 ask them again to hit or stay.
# . If stay, move on to dealers turn.
# . If the hand is less than 17 have him hit, if it is over 17 have the dealer stay.
# . If the dealer stays print the dealers hand total. IF the dealers hand total is greater than the player the dealer wins.
# . if the dealer busts print the message he busts and the player wins and the player gets the chips.

# 1. Ask dealer to hit/stay?
# 2. If hit, deal 2 cards
# 3. If broke or blackjack deliver message
# 4. If stay, compare hands
# 5. If users hand is closer to 21, (user wins)
# 6. If dealers hand is closer to 21, (user loses)


def main():
    player = Player('strikeouts27', 500,)
    dealer = Player()

    player_chips = Chips()
    dealer_chips = Chips()

    cards = Card()
    deck = Deck()


if __name__ == '__main__':
    main()

card.py

代码语言:javascript
复制
class Card:
    """Card class"""

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

    def __repr__(self):
        return f'{self.__class__.__name__}(rank={self.rank}, suit={self.suit})'

class Chips:
    """Chip class manages chip balance"""

    def __init__(self, balance):
        self.balance = balance
        self.bet = 0

    def place_bet(self):
        while True:
            total = input(f'How much do you bet? (1-{self.balance}):\n> ')
            # return True if a digit string. false otherwise. hover over the method for visual studio code to show you.
            if not total.isdigit():
                continue
            total = int(total)
            if total > self.balance:
                print('You do not have enough')
                continue
            return total

    def add_value(self, value):
        """Add value to chip total"""
        self.balance += value

    def deduct_value(self, value):
        """Deduct value from chip total"""
        self.balance -= value

    def display_chips(player, dealer):
        print(f'player chips: ${player.chips.balance}')
        print(f'dealer chips: ${dealer.chips.balance}')
            # Displays player and dealer chip count

class.py

代码语言:javascript
复制
class Card:
    #"""Card class"""

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

    def __repr__(self):
        return f'{self.__class__.__name__}(rank={self.rank}, suit={self.suit})'

deck.py

代码语言:javascript
复制
class Deck:
    """Deck class, represents 52 cards"""

    def __init__(self):
        self.ranks = [str(n) for n in range(2, 11)] + list('jqka')
        self.suits = ["hearts", "diamonds", "clubs", "spades"]
        self.cards = [Card(rank, suit)
                      for suit in self.suits for rank in self.ranks]
        random.shuffle(self.cards)

    # dunder method rewrites what pythons default method to show better information about itself.
    def __repr__(self):
        return f'{self.__class__.__name__}({self.cards})'

    def __len__(self):
        return len(self.cards)

    def __getitem__(self, item):
        return self.cards[item]

    def shuffle(self):
        """shuffles deck of cards"""
        random.shuffle(self.cards)

hand.py

代码语言:javascript
复制
class Hand:
    """Hand class to hold the cards for the player and the dealer"""

    def __init__(self, cards=None):
        self.cards = [] if cards is None else cards
        self.value = 0
        self.aces = 0

    def add_to_hand(self, card):
        """Adds a cards to self.cards."""
        self.cards.append(card)

    def display_hand(self):
        hashtable = {'hearts': 9829, 'diamonds': 9830,
                     'spades': 9824, 'clubs': 9827}
        return [[i.rank, chr(hashtable.get(i.suit))] for i in self.cards]

    def display_hand_two(player, dealer):
        # Displays player and dealer hand
        print(
            f'players Hand: {player.hand.display_hand()} -->  total {player.total}')
        print(
            f'dealer Hand: {dealer.hand.display_hand()} -->  total {dealer.total}')

player.py

代码语言:javascript
复制
class Player:
    """Player class"""

    def __init__(self, name, chips, hand):
        self.name = name
        self.chips = chips
        self.hand = hand

    @property
    def total(self):
        """Returns the value of the cards. Face cards equal 10, aces can equal
        11 or 1, this function picks best case"""

        value = 0
        aces_count = 0
        # Each card is a tuple in a list:
        cards = [card for card in self.hand.cards]

        for card in cards:
            if card.rank == 'a':
                aces_count += 1
            elif card.rank in 'kqj':
                # Face cards are worth 10 points
                value += 10
            else:
                # Numbered cards are worth their value.
                value += int(card.rank)
        # Add value of aces - 1 per ace
        value += aces_count
        for i in range(aces_count):
            # If another 10 can be added,then do it!
            if value + 10 <= 21:
                value += 10

        return value

    @staticmethod
    def get_move():
        """returns player choice to hit or stand"""
        move = input('>>> (H)it, (S)tand ?:\n> ').lower()
        return move


def main():
    # Instantiate Deck
    deck = Deck()

    # shuffle deck
    deck.shuffle()

    # Instantiate player and dealer chips
    player_chips = Chips(500)
    dealer_chips = Chips(500)

    while True:
        # Instantiate player and dealer hand
        player_hand = Hand()
        dealer_hand = Hand()

        # Instantiate player and dealer
        player = Player('seraph', player_chips, player_hand)
        dealer = Player('codecademy', dealer_chips, dealer_hand)

        # Check if player has enough money
        if player_chips.balance <= 0:
            print('need more money')

        # Then place bet
        bet = player_chips.place_bet()

        # player draws 2 cards
        player.hand.add_to_hand(deck.cards.pop())
        player.hand.add_to_hand(deck.cards.pop())

        # Dealer draws cards
        dealer.hand.add_to_hand(deck.cards.pop())
        dealer.hand.add_to_hand(deck.cards.pop())

        # display player ann dealers hand
        display_hand(player, dealer)

        # Begin game
        while True:
            if player.total > 21:
                break

            #  Get the player's moves
            player_move = player.get_move()
            if player_move == 'h':
                new_card = deck.cards.pop()
                rank, suit = new_card.rank, new_card.suit
                player.hand.add_to_hand(new_card)
                print(f'You drew a {rank} of {suit}')
                display_hand(player, dealer)
                if player.total > 21:
                    print('You busted...')
                    # Busted
                    continue
            if player_move == 's':
                break

        # Get the dealer's moves
        if dealer.total <= 21 and not player.total > 21:
            while dealer.total <= 17:
                print('Dealer hits...')
                new_card = deck.cards.pop()
                dealer.hand.add_to_hand(new_card)
                if dealer.total > 21:
                    break

        if dealer.total > 21:
            print('Dealer Busted - You win!')
            display_hand(player, dealer)
            player.chips.add_value(bet)
            dealer.chips.deduct_value(bet)
            display_chips(player, dealer)

        elif player.total > 21 or player.total < dealer.total:
            print('You lost!')
            display_hand(player, dealer)
            player.chips.deduct_value(bet)
            dealer.chips.add_value(bet)
            display_chips(player, dealer)

        elif player.total == dealer.total:
            print("It's a tie! Money is returned")


if __name__ == '__main__':
    main()

有人对菜鸟有建议吗?

我试着调用这个函数,并得到了一个错误。老实说没别的了。

EN

回答 1

Stack Overflow用户

发布于 2022-11-08 09:23:48

以下几个问题:

  • 文件class.py是多余的。它不是导入的,它只定义了一个已经在card.py.

中定义的类。

  • 有两个main函数定义。一个在blackjack.py,一个在player.py。第一个定义了玩家的‘罢工27’,而另一个定义了'seraph',‘Co量学’。第二个似乎更发达,使用的比player.py中的更多,因此它实际上应该移到player.py中。

与前一点相关的

  • blackjack.py有在任何函数之外执行的代码。这与将驱动程序代码放入函数main中的模式相反。最好将所有相关的驱动程序代码移动到放置在main中的一个blackjack.py函数中。但是,这段代码看起来还没有完成,main中已经存在的代码已经开发得更多了。我认为您只需要main (较大的代码)中的代码。

  • 与前一点有关:blackhack.py中的代码调用未定义的函数place_bet。有一个具有该名称的方法,但没有一个具有该名称的独立函数。为了调用该方法,您首先需要一个Chips实例,因此,正如我在前面的项目中提到的那样,我建议只删除这段代码,包括在其中生成的input。也许你只想保留这里所做的介绍性print声明,并将它们移到print中。

  • random用于deck.py,但它是在blackjack.py中导入的。如果将deck.py语句移动到deck.py文件.

中,则会使deck.py更加独立。

  • display_hand_two不应该是Hand类的方法。它甚至不期望有一个Hand类型的Hand参数。相反,这应该是blackjack.py.

中的一个独立函数。

  • In main您有几个类似于display_hand(player, dealer)的调用,但是display_hand不是一个独立的函数,而是一个方法。这里您真正想要做的是调用display_hand_two(player, dealer),为此您必须使display_hand_two成为一个独立的函数,就像前面的要点中提到的那样。

如果您实现了所有这些更改,您的代码将运行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74351716

复制
相关文章

相似问题

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