2013-12-01 3 views
1

Я пишу блэкджки для моего класса, и я не могу показаться, чтобы выяснить, что случилось с кодом вообще, может быть, я просто смотрел на нее слишком долго, но любая помощь будет оцененTypeError: неподдерживаемый операнд int и NoneType? Python

def payout(betAmount): 
    global option1 
    if option1 == "1": 
     betAmount*1.5 
     return int(betAmount) 
    elif option1 == "2": 
     betAmount*=1.25 
     return int(betAmount) 
    elif option1 == "3": 
     betAmount*=1.2 
     return int(betAmount) 

следуют этим:

winning=payout(bet) 
playerPool+=winning 

жаль, что полный код:

import random, pickle 

option1=None 

def payoutRule(): 
    global option1 
    pick=None 
    while pick != "1" or "2" or "3": 
     pick=input(""" 
What is the house payout you want to play with? 

1- 3:2 (1.5X) 
2- 5:4 (1.25X) 
3- 6:5 (1.2X)\n 
""") 

     if pick == "1": 
      option1=1 
      break 
     elif pick == "2": 
      option1=2 
      break 
     elif pick == "3": 
      option1=3 
      break 
     else: 
      print("That is not a valid option!\n") 

def payout(betAmount): 
    global option1 
    if option1 == "1": 
     betAmount*1.5 
     return int(betAmount) 
    elif option1 == "2": 
     betAmount*=1.25 
     return int(betAmount) 
    elif option1 == "3": 
     betAmount*=1.2 
     return int(betAmount) 

def hitDeck(): 
    CARDS=(2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11) 

    drawCard=random.choice(CARDS) 
    return drawCard 

def aceCounter(hand): 
    aces=hand.count(11) 
    total=sum(hand) 
    if total > 21 and aces > 0: 
     while aces > 0 and total > 21: 
      total-=10 
      aces-=1 
    return total 


def main(): 
    print("\t\tWelcome to the Blackjack Table!") 
    payoutRule() 
    playerPool=int(250) 

    while True: 
     playerCard=[] 
     dealerCard=[] 

     playerBust=False 
     dealerBust=False 
     endGame=None 
     bet=None 

     playerCard.append(hitDeck()) 
     playerCard.append(hitDeck()) 
     print("You have", playerPool, "dollars to play with.") 

     while True: 
      bet=input(""" 
How much are you betting? 
\t1- $5 
\t2- $10 
\t3- $25 
""") 
      if bet == "1": 
       print("You put down $5 on the table.") 
       bet=int(5) 
       break 
      elif bet == "2": 
       print("You put down $10 on the table.") 
       bet=int(10) 
       break 
      elif bet == "3": 
       print("You put down $25 on the table.") 
       bet=int(25) 
       break 
      else: 
       print("That is not a valid choice!") 

     while endGame != "1": 
      totalPlayer=aceCounter(playerCard) 
      print("You have", len(playerCard), "cards with a total value of", totalPlayer) 
      if totalPlayer > 21: 
       print("You are busted!") 
       playerBust=True 
       break 
      elif totalPlayer == 21: 
       print("You've got a blackjack!!!") 
       break 
      else: 
       hit=input(""" 
Would you like to: 
\t1- Hit 
\t2- Stand 
""") 
       if "1" in hit: 
        playerCard.append(hitDeck()) 
       elif "2" in hit: 
        break 
       else: 
        print("That is not a valid choice!") 
     while True: 
      dealerCard.append(hitDeck()) 
      dealerCard.append(hitDeck()) 
      while True: 
       totalDealer=aceCounter(dealerCard) 
       if totalDealer <= 17: 
        dealerCard.append(hitDeck()) 
       else: 
        break 
      print("The dealer has", len(dealerCard), "cards with a total value of", totalDealer) 
      if totalDealer > 21: 
       print("The dealer busted!") 
       dealerBust=True 
       if playerBust == False: 
        winning=payout(bet) 
        print("You won!") 
        print("You just won", winning, "dollars!") 
        playerPool+=winning 
       elif playerBust == True: 
        print("You both busted but the house will still collect.") 
        print("You just lost", bet, "dollars...") 
        playerPool-=bet 
      elif totalPlayer > totalDealer: 
       if playerBust == False: 
        winning=payout(bet) 
        print("You won!") 
        print("You just won", winning, "dollars!") 
        playerPool+=winning 
       if playerBust == True: 
        print("The dealer won!") 
        print("You just lost", bet, "dollars...") 
        playerPool-=bet 
      elif totalPlayer == totalDealer: 
       print("It's a draw, but the house still wins.") 
       print("You just lost", bet, "dollars...") 
       playerPool-=bet 
      elif totalPlayer < totalDealer: 
       print("The dealer won!") 
       print("You just lost", bet, "dollars...") 
       playerPool-=bet 
      break 

     if playerPool == 0: 
      print("You don't have anymore money to play with!") 
      break 
     elif playerPool < 0: 
      print("You owe the house", -playerPool, "dollars, time to work in the kitchen...") 
      break 
     print("You have", playerPool, "dollars in your pocket now.") 
     playAgain=input("Press the Enter key to play again or 'q' to quit.\n") 
     if "q" in playAgain.lower(): 
      break 

фактическая ошибка заключается в следующем:

Traceback (самый последний вызов последнего): Файл "C: \ Users \ Daniel \ Desktop \ Software Design \ Кульминирующий проекта revised2.py", строка 175, в главном()

Файл «C: \ Пользователи \ Daniel \ Desktop \ Software Design \ Кульминирующий проекта revised2.py», строка 140, в основной playerPool + = выигрыш

TypeError: неподдерживаемый тип (ы) операндом + =: 'Int' и 'NoneType'

+0

Сообщите нам об ошибке. На самом деле, вероятно, было бы неплохо также показать нам весь код в полном объеме. – jwodder

+0

Помимо забывания строки '=' для 'betAmount * = 1.5', ваш код должен работать отлично, если' bet' не 'None'. или 'option1' не является строковым значением, которое вы проверяете. –

+0

Покажите нам 'bet' и' option1', пожалуйста. –

ответ

0

При установке option1 в payoutRules вы назначаете целое число значений.

Когда вы проверяете option1 в payout, вы сравниваете его с строк. Он ничего не может сопоставить, и поэтому payout всегда возвращает None.

Вы можете изменить payout функцию:

def payout(betAmount): 
    return betAmount * (1.5, 1.25, 1.2)[option1] 

Делая это таким образом вы используете option1, который представляет собой целое число в качестве индекса в (1.5, 1.25, 1.2) кортеж, чтобы получить множитель умножить с betAmount. Если option1 не является целым числом, вы получите ошибку прямо здесь.

+0

Благодарим за помощь! Я определенно пропустил это, вместо того, чтобы изменять функцию, я действительно избавился от кавычек в моей функции payout(), поскольку она работает одинаково. Наверное, мне просто нужен еще один взгляд, чтобы посмотреть на него – user3052919

0

Ваша функция вернется None, если option1 не является ни '1', ни '2' и '3'. В этом случае падение winning (которое является результатом payout) до playerPool.

Возможно, вы добавите print(option1) в качестве первой строки своей функции, чтобы увидеть, как она выглядит.

Вы можете реорганизовать функцию следующим образом:

def payout(betAmount, option1): 
    return int({'1': 1.5, '2': 1.24, '3': 1.2}[option1] * betAmount) 

Таким образом, вы получаете по крайней мере ключевую ошибку, когда option1 не является допустимым вариантом.

Смежные вопросы