So I have an exercise on python - building a BlackJack game. I have started with defining how every phrase of the game would go. Now when I run this code below, In case the input is '0' - which means you don't want cards anymore, it runs perfectly. But when the input is '1' - which means you want to pick card, I get an error:
Traceback (most recent call last):
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 1, in <module>
class blackjack(object):
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 34, in blackjack
player(1)
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 25, in player
PickCard(1)
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 18, in PickCard
self.hand+= random.randrange(1, 13)
AttributeError: 'int' object has no attribute 'hand'
The code:
class blackjack(object):
#this func defines how player should react
def player(self):
#this func defines what case of technical loosing
def loser():
print("You have reached", hand , ". Which is beyond 21. Therefor, you have lost the game. Better luck next time!")
#this func is responsible for picking card issue.
def PickCard(self):
import random
x=1
while x == 1:
pick = int(raw_input("Enter 1 if you want another card, else Enter 0"))
if pick == 1:
self.hand = self.hand + random.randrange(1, 13)
else:
x=0
import random
print "Now your first card will automatically be given to you:"
hand=random.randrange(1,13)
print "hand: ", hand
PickCard(1)
print hand
if hand>21:
loser()
elif hand==21:
pass
else:
pass
player(1)
Thanks in advance.
You are making the function call as player(1)
where the player
function expects the argument as of self
type .ie instance of the class blackjack
. Hence, while doing self.hand = self.hand + random.randrange(1, 13)
it is throwing the above mentioned error.
I think you do not want to make a call to player()
function from within the class, Is it? Move that part to outside the class. Firstly create the object of class blackjack
(Note: In Python, class names should be defined as CamelCase variables like: BlackJack). For example:
blackjack_obj = blackjack()
Then call the player()
function as:
blackjack_obj.player()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.