有人可以指导我如何在类中重用函数,以便通过导入随机数获得不同的输出吗?
这是我使用python 3.7以Conda
为基础的python 3.7代码在VS Code中编写的二十一点游戏。
我正在尝试重用功能player_hand(随机卡),并为player_score(卡值作为整数)获得不同的结果
,然后将这2个得分相加为final_player(最终得分) 我非常感谢有关如何应对这一挑战的指导和反馈...
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'))
以下输出示例:
Player balance: $100
Place bet:5
Player balance: $95
dealer [('Queen', 10), 'Diamonds']
dealer 10
player [('Seven', 7), 'Heart']
player 7
None
dealer wins
答案 0 :(得分:0)
我认为这里的挑战在于理解如何使用类对问题进行建模,特别是如果您是初次接触面向对象编程(OOP)时。
您对于使my_list = '[-0.2226099967956543, 0.2235500067472458, -0.2384900003671646, 0.14377999305725098]'
import ast
ast.literal_eval(my_list)
Out[567]:
[-0.2226099967956543,
0.2235500067472458,
-0.2384900003671646,
0.14377999305725098]
对象(即具有 rank 和 suit 的对象)的构想是一个合理的想法。 但这就是一张卡片应该拥有的全部。所有卡片都具有这两个属性,因此创建类似Card
的类几乎没有意义。该卡只是一张纸,不应该知道持有该卡的玩家或庄家,手中的其他卡,玩家的钱等。包括这些无关的数据会导致玩家之间“耦合” ,下注和纸牌彼此之间开始,从而产生“意大利面代码”。
这是从我编写的Card2
中绘制Card
个对象的快速实现:
Deck
请注意,一旦您编写了各个片段(例如,对牌进行改组和绘制卡片),则主要功能中的代码应该很直观。请让我知道任何代码是否没有道理。