2013-05-09 3 views
0

아래 코드를 사용하여 아래에 나와있는 매개 변수를 인쇄해야합니다. 그러나 현재는이를 수행 할 수 없으며 round about 메서드를 사용하고 있습니다. 이 대신에 당신은 또한 당신의 입력이 될 다른 문제를 보면 우리는 playturn 기능 여기Python의 클래스에서 인쇄 할 때 문제가 발생했습니다.

def __str__(self): 
     x = self.name + ":\t" 
     x += "Card(s):" 
     for y in range(len(self.hand)): 
      x +=self.hand[y].face + self.hand[y].suit + " " 
     if (self.name != "dealer"): 
      x += "\t Money: $" + str(self.money) 
     return(x) 

우리의 실제 코드가있는 게임 클래스에 인쇄 무슨 일을 인쇄하도록되어 크게

감사
from random import* 
#do we need to address anywhere that all face cards are worth 10? 
class Card(object): 
    def __init__(self,suit,number): 
     self.number=number 
     self.suit=suit 
    def __str__(self): 
     return '%s'%(self.number) 

class DeckofCards(object): 
    def __init__(self,deck): 
     self.deck=deck 
     self.shuffledeck=self.shuffle() 

    def shuffle(self): 
     b=[] 
     count=0 
     while count<len(self.deck): 
      a=randrange(0,len(self.deck)) 
      if a not in b: 
       b.append(self.deck[a]) 
       count+=1 
     return(b) 

    def deal(self): 
     if len(self.shuffledeck)>0: 
      return(self.shuffledeck.pop(0)) 
     else: 
      shuffle(self) 
      return(self.shuffledeck.pop(0)) 
class Player(object): 
    def __init__(self,name,hand,inout,money,score,bid): 
     self.name=name 
     self.hand=hand 
     self.inout=inout 
     self.money=money 
     self.score=score 
     self.bid=bid 

    def __str__(self): 
     x = self.name + ":\t" 
     x += "Card(s):" 
     for y in range(len(self.hand)): 
      x +=self.hand[y].face + self.hand[y].suit + " " 
     if (self.name != "dealer"): 
      x += "\t Money: $" + str(self.money) 
     return(x) 

class Game(object): 
    def __init__(self,deck, player): 
     self.player=Player(player,[],True,100,0,0) 
     self.dealer=Player("Dealer",[],True,100,0,0) 
     self.deck=DeckofCards(deck) 
     self.blackjack= False 
    def blackjacksearch(self): 
     if Game.gettot(self.player.hand)==21:#changed 
      return True 
     else: 
      return False  
    def firstround(self): 
     #self.player.inout=True#do we need this since this is above 
     #self.player.hand=[]#do wee need this.... 
     #self.dealer.hand=[]#do we need this .... 
     self.player.hand.append(DeckofCards.deal(self.deck)) 
     for card in self.player.hand: 
      a=card 
     print(self.player.name + ' ,you were dealt a '+str(a)) 
     self.dealer.hand.append(DeckofCards.deal(self.deck)) 
     for card in self.dealer.hand: 
      a=card 
     print('The Dealer has '+str(a)) 
     playerbid=int(input(self.player.name + ' how much would you like to bet? ')) 
     self.player.money-=playerbid 
     self.player.bid=playerbid 
    def playturn(self): #should this be changed to inout instead of hit.....we never use inout 
     #for player in self.player: 
     # a=player 
     #print(str(a)) 
     hit=input('Would you like to hit? ') #should input be in loop? 
     while self.player.inout==True: #and self.blackjack!=True:#changed 
      print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets 
      self.player.hand.append(DeckofCards.deal(self.deck)) 
      for card in self.player.hand: 
       a=card 
      print('The card that you just drew is: ' + str(a)) 
      #print(Game.gettot(self.player.hand)) 
      hit=input('Would you like to hit? ') 
      if hit=='yes': 
       (self.player.hand.append(DeckofCards.deal(self.deck)))#changed 
       self.player.inout==True# 
      else: 
       (self.player.hand) #changed 
       self.player.inout==False #changed 
     if self.player.blackjack==True: 
      print(self.player.name + " has blackjack ") 
     if hit=='no': 
      print (self.player.hand.gettot()) 
    def playdealer(self): 
     while Game.gettot(self.dealer.hand)<17:#changed 
      self.dealer.hand.append(DeckofCards.deal(self.deck)) 
      dealerhand=Game.gettot(self.dealer.hand) #changed 
      print(dealerhand) 
     if Game.gettot(self.dealer.hand)==21:#changed 
      self.dealer.blackhjack=True 
     dealerhand1=Game.gettot(self.dealer.hand)#changed 
     print(dealerhand1) 

    def gettot(self,hand): 
     total=0 
     for x in self.hand: 
      if x==Card('H','A'): 
       b=total+x 
       if b>21: 
        total+=1 
       else: 
        total+=11 
      if x==Card('D','A'): 
       b=total+x 
       if b>21: 
        total+=1 
       else: 
        total+=11 
      if x==Card('S','A'): 
       b=total+x 
       if b>21: 
        total+=1 
       else: 
        total+=11 
      if x==Card('C','A'): 
       b=total+x #changed 
       if b>21: 
        total+=1 
       else: 
        total+=11 
      else: 
       total+=x 
     return(total) 

    def playgame(self): 
     play = "yes" 
     while (play.lower() == "yes"): 
      self.firstround() 
      self.playturn() 
      if self.player.blackjack == True: 
       print(self.player.name + " got BLACKJACK! ") 
       self.player.money += self.player.bid * 1.5 
       print (self.player.name + " now has " + str(self.player.money)) 
       print("\n") 
       self.player.inout = False 
      if self.player.score > 21: 
       print(self.player.name + " lost with a tot of " + str(self.player.score)) 
       self.player.money -= self.player.bid 
       print (self.player.name + " now has " + str(self.player.money)) 
       print ("\n\n") 
       self.player.inout = False 
      self.playdealer() 
      if self.dealer.blackjack == True: 
       print("Dealer got blackjack, dealer wins\n") 
       self.player.money -= self.player.bid 
       print("Round\n") 
       print("\t",self.dealer) 
       print("\t",self.player) 
       print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score)) 
      elif self.player.inout == True: 
       print("Round\n") 
       print("\t",self.dealer) 
       print("\t",self.player) 
       print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score)) 
       if self.dealer.score > 21: 
        print("\t Dealer lost with a total of " + str(self.dealer.score)) 
        self.player.money += self.player.bid 
        print(self.player.name + " now has " + str(self.player.money)) 
       elif self.player.score > self.dealer.score: 
        print("\t" +self.player.name + " won with a total of " + str(self.player.score)) 
        self.player.money += self.player.bid 
        print("\t"+self.player.name + " now has " + str(self.player.money)) 
       else: 
        print("\t Dealer won with a total of " + str(self.dealer.score)) 
        self.player.money -= self.player.bid 
        print("\t"+self.player.name + " now has " + str(self.player.money)) 
      else: 
       print("Round") 
       print("\t",self.dealer) 
       print("\t",self.player) 
       if self.player.blackjack == False: 
        print("\t "+ self.player.name + " lost") 
       else: 
        print("\t "+self.player.name + " Won!") 

      if self.player.money <= 0: 
       print(self.player.name + " out of money - out of game ") 
       play = "no" 
      else: 
       play = input("\nAnother round? ") 
       print("\n\n") 
     print("\nGame over. ") 
     print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n") 
     print("Thanks for playing. Come back soon!") 



ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'), 
Card('H','J'),Card('H','Q'),Card('H','K'), 
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'), 
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'), 
Card('S','J'),Card('S','Q'),Card('S','K'), 
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'), 
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'), 
Card('C','J'),Card('C','Q'),Card('C','K'), 
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'), 
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'), 
Card('D','J'),Card('D','Q'),Card('D','K')] 


def main(): 
    x = input("Player's name? ") 
    blackjack = Game(ls,x) 
    blackjack.playgame() 
main() 
+2

그리고 정확히 무엇이 당신의 질문입니까? 무엇이 잘못 되었습니까, 오류 메시지가 있다면 무엇입니까, 대신 무엇을 기대합니까? –

+0

질문에 기초한 일종의 학교/과제처럼 보입니다. 정확히 이해하지 못하거나 예상대로 작동하지 않는 것은 무엇입니까? –

+0

하나의 문제는 '임의 가져 오기에서 온 것'입니다. 와일드 카드 가져 오기를 사용하지 마십시오. –

답변

1

문제에

str(self.player.hand) 

을 변경하려고하는 것은 적어도 일부 장소에서, 당신이 list를 인쇄 할 노력하고 있다는 점이다.

list을 포함한 모든 것을 인쇄하는 동안 str을 호출하면 list.__str__ 메서드는 해당 요소에 repr을 호출합니다. (당신이 strrep의 차이를 알 수없는 경우, Difference between __str__ and __repr__ in Python를 참조하십시오.)

당신이 목록에있는 모든 요소의 str를 인쇄 할 경우, 당신은 map 또는 목록 이해와 함께, 명시 적으로해야한다. 대신이의 예를 들어

:

print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand]) 

을하지만 당신이 원하는 여전히 아마되지 않습니다 :

print(self.player.name + ' , your hand has:' + str(self.player.hand)) 

가 ... 이렇게. [<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>] 대신에 ['8', '9']을 얻지 만, 아마도 '8H 9C'와 같은 것을 원할 것입니다. Player.__str__ 내부

print(self.player.name + ' , your hand has:' + 
     ' '.join(str(card) for card in self.player.hand)) 

당신은 이미 비슷한 (더 자세한 비록) 코드 :이 코드는 몇 가지 방법으로 개선 될 수

for y in range(len(self.hand)): 
    x +=self.hand[y].face + self.hand[y].suit + " " 

그렇게하려면, 당신은 뭔가를 원하는 것입니다.

number 대신 face을 사용하고 있기 때문에 먼저 AttributeError이 발생합니다. 하지만 실제로는이 작업을 수행 할 필요가 없습니다. Card.__str__ 메서드를 만든 모든 이유가 있으므로 str(Card)을 사용할 수 있습니다. 맞습니까?

둘째, 특히 루프 내에 foo[y]을 수행하는 경우 range(len(foo))을 반복 할 필요가 없습니다. foo을 바로 반복하면됩니다.

함께 그 퍼팅 :

for card in self.hand: 
    x += str(card) + " " 

을 어쨌든, 당신은 두 곳에서 같은 일을 할 필요가있다.

join 메서드와 생성자 표현식을 사용하는 버전은 명시 적 루프보다 약간 간단하지만 이해할 수있는 Python 지식이 조금 더 필요합니다. 여기에 당신이 여기를 사용하십시오 방법은 다음과 같습니다

x += " ".join(str(card) for card in self.hand) + " " 

당신의 다음 문제는 Card.__str__가 소송을 포함하지 않습니다. 따라서 8H 9C 대신 8 9을 얻으실 수 있습니다. 혼자서하는 것은 쉬운 수정이어야합니다.


한편 동일한 코드를 두 번 이상 쓰는 사람이 있다면 그 코드를 추출하는 것이 좋습니다. 당신 단지 손 list을 소요하고 문자열로 그것을 켤 수있는 기능을 작성할 수

def str_hand(hand): 
    return " ".join(str(card) for card in self.hand) 

그러나 카드의 목록을 감싸는 Hand 클래스를 생성하고, 그 주위에 전달하는 더 나은 수 있습니다 대신 list을 직접 사용하는 대신

0

player.hand을 참조하기 때문에 원하는 기능이 실행되고 있지 않습니다.

str(self.player) 
+0

그래서 "당신은 가지고 있습니다"라고 말하고 플레이어의 이름, 손, 돈을 보여주는'Player' 오브젝트를 출력하십시오. – abarnert

+0

@abarnert'아래에있는 코드를 사용하여 인쇄 된 매개 변수를 인쇄해야합니다. ' – John

+0

@abarnert 이것이 우리가 성취하려고하는 것입니다. –

관련 문제