continued trouble with classes in python 3.2 - python

In the below code, it is working at first but when I want it to tell me what card number the dealer has it is returning some sort encrypted stuff that I don't understand.
[<__main__.Card object at 0x025A4E50>]
How do I get this to return the corresponding card number?
Also someone said that I may need to use __eq__ when comparing things as opposed to the way that I currently am could someone explain why, and also how to use __eq__ ?
Below is the code for the program that I am trying to get to work, it is a blackjack game.
from random import*
class Card(object):
def __init__(self,suit,number):
self.suit=suit
self.number=number
class DeckofCards(object):
def __init__(self,deck):
self.deck=deck
self.shuffledeck=self.shuffle()
#print(self.shuffledeck)
def shuffle(self):
#print('This is shuffle function')
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 #self.blackjacksearch()
def blackjacksearch(self):#this is where it says there is an error we moved this because she said it needed to be in this class to get the Getot function
if self.player.hand.gettot()==21:
return True
else:
return False
def firstround(self):
self.player.inout=True
self.player.hand=[]
self.dealer.hand=[]
self.dealer.hand.append(DeckofCards.deal(self.deck))
print('The Dealer has '+str(self.dealer.hand))
playerbid=int(input('How much would you like to bet?'))
self.player.bid=playerbid
def playturn(self):
while self.player.blackjack!=True or hit=='yes':
print(self.player.hand)
a=self.player.hand.append(deal())
print('The card that you just drew is ' + str(a))
print(gettot())
hit=input('Would you like to hit? ')
if hit=='yes':
return(self.player.hand.append(deal()))
else:
return() #might need to change this
if self.player.blackjack==True:
print(self.player.name + " has blackjack ")
if hit=='no':
print (self.player.hand.gettot())
def playdealer(self):
while self.dealer.hand<17:
self.dealer.hand.append(deal())
dealerhand=self.dealer.hand.gettot() #confused
print(dealerhand)
if self.dealer.hand==21:
self.dealer.blackhjack=True
dealerhand1=self.dealer.hand.gettot()
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'):
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')]
'''tom=Card('Heart','Queen')
print(tom.suit)
print(DeckofCards(ls))
print(ls.suit)'''
def main():
x = input("Player's name? ")
blackjack = Game(ls,x)
blackjack.playgame()
main()

Print the card instead of the list of card objects and give the card a decent __str__ method to display itself human-readable. Instead of
print(self.player.hand)
try this:
for card in self.player.hand:
print(card)
and in class Card insert this:
def __str__(self):
return '%s%s' % (self.number, self.suit)
Concerning your question about the __eq__: An objects __eq__() method gets called whenever it gets compared for equality using the == operator. Without such a method, two objects are only equal if they are the same object. So in your cards you might want to have sth like this:
def __eq__(self, other):
return self.number == other.number and self.suit == other.suit

When you use str() on a Card object it calls an inherited __str__ method which will print out the class name and address of the object. What you call encrypted is the address of the object. If you want to print out something different, override the __str__ method in your class. For example:
class Card(object):
def __str__(self):
return "Card " + self.suit + " " + self.number

Related

TicTacToe and Minimax

I am a young programmer that is learning python and struggling to implement an AI (using minimax) to play TicTacToe. I started watching a tutorial online, but the tutorial was on JavaScript and thus couldn't solve my problem. I also had a look at this question ( Python minimax for tictactoe ), but it did not have any answers and the implementation was considerably different from mine.
EDIT: the code you will find below is an edit suggested by one of the answers (#water_ghosts).
EDIT #2: I deleted possiblePositions, as the AI should choose a free field and not a place from the possiblePositions (that wouldn't make it that smart while implementing minimax :) )
Now the code doesn't give out any errors at all and functions properly, but one small thing: the AI always chooses the next available field. For example in situations where i am i move away from winning, instead of blocking my win option, it chooses the next free spot.
If you're wondering what that elements dict is doing there: i just wanted to make sure the programm chose the best index...
Here is my code:
class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.score = 0
self.winner = None
self.scoreBoard = {
self.playerSymbol: -1,
self.aiSymbol: 1,
"tie": 0
}
self.turn = 0
self.optimalMove = int()
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
print("___" + "___" + "___")
print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
print("___" + "___" + "___")
print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
else:
self.playerSymbol = "O"
self.aiSymbol = "X"
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 4, 8}, {2, 4, 6}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}]
for position in winningPositions:
if position.issubset(self.playerPosition):
self.winner = self.playerSymbol
print("Player Wins :)")
return True
elif position.issubset(self.aiPosition):
self.winner = self.aiSymbol
print("AI wins :(")
return True
if self.board.count(" ") == 0:
self.winner = "tie"
print("Guess it's a draw")
return True
return False
def findOptimalPosition(self):
bestScore = float("-Infinity")
elements = {} # desperate times call for desperate measures
for i in range(9):
if self.board[i] == " ":
self.board[i] = self.aiSymbol # AI quasi made the move here
if self.minimax(True) > bestScore:
bestScore = self.score
elements[i] = bestScore
self.board[i] = " "
return max(elements, key=lambda k: elements[k])
def minimax(self, isMaximizing):
if self.winner is not None:
return self.scoreBoard[self.winner]
if isMaximizing:
bestScore = float("-Infinity")
for i in range(9):
if self.board[i] == " ":
self.board[i] = self.aiSymbol
bestScore = max(self.minimax(False), bestScore)
self.board[i] = " "
return bestScore
else:
bestScore = float("Infinity")
for i in range(9):
if self.board[i] == " ":
self.board[i] = self.playerSymbol
bestScore = min(self.minimax(True), bestScore)
self.board[i] = " "
return bestScore
def play(self):
self.choice()
while not self.won():
if self.turn % 2 == 0:
pos = int(input("Where would you like to play? (0-8) "))
self.playerPosition.append(pos)
self.board[pos] = self.playerSymbol
self.turn += 1
self.drawBoard()
else:
aiTurn = self.findOptimalPosition()
self.aiPosition.append(aiTurn)
self.board[aiTurn] = self.aiSymbol
self.turn += 1
print("\n")
print("\n")
self.drawBoard()
else:
print("Thanks for playing :)")
tictactoe = TicTacToe()
tictactoe.play()
I come from a java background and am not used to this :(
Any help would be highly appreciated
I am open to suggestions and ways to improve my code and fix this problem.
Thanks in advance and stay healthy,
Kristi
Change this part, your implementation will return optimalMove even if it doesn't go inside the if statement, and optimalMove will not be assigned at that point, so put the return inside.
if score > sampleScore:
sampleScore = score
optimalMove = i
return optimalMove
optimalMove = 0 in play() and optimalMove = i in findOptimalField() are declaring two distinct variables, each of which is local to the function declaring it.
If you want multiple functions to have access to the same variable, you can use the global keyword, but that's generally considered a bad practice. It can make it hard to reason about the code (e.g. is var = x creating a new local variable or overwriting the value of a global?) and it doesn't stop you from accidentally using a variable before it's declared.
Since you're coming from a Java background, you can turn this into a class to get behavior more like what you expect, eliminating the need for globals:
class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.score = 0
self.playerSymbol = None
self.aiSymbol = None
...
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
...
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
...
Each method now takes an explicit self argument that refers to the current instance, and you can use this to access any variables that belong to the class instance instead of a particular method. If you don't include self. before a variable, that variable will still be local to the method that declares it. In this case, the drawBoard() method won't be able to access the answer variable defined in choice().
You can create new self. variables in any of the class's methods, but the best practice is to initialize all of them in the __init__ constructor method, using None as a placeholder for variables that don't have a value yet.
I am posting this as an answer, just in case somebody in the future stumbles upon the same problem :)
the main issue i encountered (besides my bad programming style) is that i forgot to update the contents the lists playerPosition and aiPosition.
You can review the rest of the changes in the working code:
class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.winner = None
self.scoreBoard = None
self.turn = 0
self.optimalMove = int()
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
print("___" + "___" + "___")
print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
print("___" + "___" + "___")
print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
else:
self.playerSymbol = "O"
self.aiSymbol = "X"
self.scoreBoard = {
self.playerSymbol: -1,
self.aiSymbol: 1,
"tie": 0
}
def availableMoves(self):
moves = []
for i in range(0, len(self.board)):
if self.board[i] == " ":
moves.append(i)
return moves
def won_print(self):
self.won()
if self.winner == self.aiSymbol:
print("AI wins :(")
exit(0)
elif self.winner == self.playerSymbol:
print("Player Wins :)")
exit(0)
elif self.winner == "tie":
print("Guess it's a draw")
exit(0)
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 4, 8}, {2, 4, 6}, {0, 3, 6},
{1, 4, 7}, {2, 5, 8}]
for position in winningPositions:
if position.issubset(self.playerPosition):
self.winner = self.playerSymbol
return True
elif position.issubset(self.aiPosition):
self.winner = self.aiSymbol
return True
if self.board.count(" ") == 0:
self.winner = "tie"
return True
self.winner = None
return False
def set_i_ai(self, i):
self.aiPosition.append(i)
self.board[i] = self.aiSymbol
def set_clear_for_ai(self, i):
self.aiPosition.remove(i)
self.board[i] = " "
def set_i_player(self, i):
self.playerPosition.append(i)
self.board[i] = self.playerSymbol
def set_clear_for_player(self, i):
self.playerPosition.remove(i)
self.board[i] = " "
def findOptimalPosition(self):
bestScore = float("-Infinity")
elements = {} # desperate times call for desperate measures
for i in self.availableMoves():
self.set_i_ai(i)
score = self.minimax(False)
if score > bestScore:
bestScore = score
elements[i] = bestScore
self.set_clear_for_ai(i)
if bestScore == 1:
print("you messed up larry")
elif bestScore == 0:
print("hm")
else:
print("whoops i made a prog. error")
return max(elements, key=lambda k: elements[k])
def minimax(self, isMaximizing):
if self.won():
return self.scoreBoard[self.winner]
if isMaximizing:
bestScore = float("-Infinity")
for i in self.availableMoves():
self.set_i_ai(i)
bestScore = max(self.minimax(False), bestScore)
self.set_clear_for_ai(i)
return bestScore
else:
bestScore = float("Infinity")
for i in self.availableMoves():
self.set_i_player(i)
bestScore = min(self.minimax(True), bestScore)
self.set_clear_for_player(i)
return bestScore
def play(self):
self.choice()
while not self.won_print():
if self.turn % 2 == 0:
pos = int(input("Where would you like to play? (0-8) "))
self.playerPosition.append(pos)
self.board[pos] = self.playerSymbol
self.turn += 1
self.drawBoard()
else:
aiTurn = self.findOptimalPosition()
self.aiPosition.append(aiTurn)
self.board[aiTurn] = self.aiSymbol
self.turn += 1
print("\n")
print("\n")
self.drawBoard()
else:
print("Thanks for playing :)")
if __name__ == '__main__':
tictactoe = TicTacToe()
tictactoe.play()
But as mentioned, the code may work, but there are MANY problems regarding the logic and structure, so do not straight-forward copy-paste it :))

Python skipping elif statement

I'm trying to write a program that prints the values and keys in a dictionary depending of the input the user types. The problem appears when the elif statement on line 11 gets skipped. It doesn't matter if the if statement is false, the elif statement gets skipped. I'm learning so I don't really know where my error is. Thanks for the help!
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
print("Enter a conversion")
if input() == "Area Meassure":
displayConversion(areaM)
elif input() == "Linear Meassure":
displayConversion(linearM)
else:
print("Conversion not available")
Maybe this as the full code (too much inputss):
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
a=input("Enter a conversion\n")
if a == "Area Meassure":
displayConversion(areaM)
break
elif a == "Linear Meassure":
displayConversion(linearM)
break
else:
print("Conversion not available")

Tic-Tac-Toe Game

I've wrote a code for the Tic-Tac-Toe game.
Here's what the code does:
Gets the name of Player 1.
Gets the name of Player 2.
Asks if the Player 1 wants X or O.
If he chooses X then Player 2 gets O and vice versa.
Prints the empty board.
Asks both players to enter the row and column one by one and prints the updated board.
If a player doesn't repeat previous player's spot, everything works fine until the end without any problem.
If a player repeats previous player's spot, a message is displayed saying that the previous player has already taken this spot and makes him guess again.
Now, after this point, if I guess any index other than the one that the previous player has already taken, it overwrites the previous players spot.
Screenshot of the terminal when this occurs:
I'm certain that the problem is in the function enterguess(turncount), but haven't been able to spot it yet. Any idea where the problem is?
<----------------------------------------------[ Demo Without the colors ]-------------------------------------------->
Code:
import termcolor
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
vb = termcolor.colored("|", "yellow", None, ['bold'])
s = termcolor.colored("\t+---+---+---+", "yellow", None, ['bold'])
players = {
'player1' : '',
'player2' : ''
}
sym = {
'player1': '',
'player2': ''
}
def rules ():
print("\nWelcome to Tic Tac Toe...")
def printboard():
#boardlist = [[" "," "," "],[" "," "," "],[" "," "," "]]
for row in board:
print s
print "\t" + vb + " " + row[0] + " " + vb + " " + row[1] + " " + vb + " " + row[2] + " " + vb
print s
def playerNames():
p1 = termcolor.colored(raw_input("\nEnter name of Player 1: ").title(), 'red', None, ['underline'])
p2 = termcolor.colored(raw_input("Enter name of Player 2: ").title(), 'blue', None, ['underline'])
sym['player1'] = termcolor.colored(raw_input("\n" + p1 + ', you want X or O? - ').capitalize(), 'red', None, ['bold'])
if sym['player1'] == 'X':
sym['player2'] = termcolor.colored('O', 'blue', None, ['bold'])
else:
sym['player2'] = termcolor.colored('X', 'red', None, ['bold'])
players['player1'] = p1
players['player2'] = p2
return {p1:termcolor.colored('X', 'red', None, ['bold']), p2: termcolor.colored('O', 'blue', None, ['bold'])}
def enterguess(turncount):
def guess(name):
return (int(input("\n" + players[name] + ", Enter row number: ")),
int(input(players[name] + ", Enter column number: ")))
if turncount % 2 == 0:
(row, col) = guess('player1')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player2'] + " already took that spot! Please guess again."
enterguess(turncount)
except:
print "\nPlease enter the indexes between 1 and 3."
enterguess(turncount)
else:
(row, col) = guess('player2')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player1'] + " already took that spot! Please guess again."
enterguess(turncount)
except IndexError:
print "\nPlease enter a number between 1 and 3."
enterguess(turncount)
return (row - 1, col - 1)
def changeboard(row, col, xo, c):
if c % 2 == 0:
board[row][col] = xo[players['player1']]
else:
board[row][col] = xo[players['player2']]
def checkWinner():
for x in range(3):
if board[x][0] == board[x][1] == board[x][2] and board[x][0] != " ":
return [players[n] for n, s in sym.iteritems() if s == board[x][0]][0]
for y in range(3):
if board[0][y] == board[1][y] == board[2][y] and board[0][y] != " ":
return [players[n] for n, s in sym.iteritems() if s == board[0][y]][0]
xx = 0
yy = 2
while True:
if board[xx][xx] == board[1][1] == board[2][yy] and board[xx][xx] != " ":
return [players[n] for n, s in sym.iteritems() if s == board[xx][xx]][0]
xx += 2
yy -= 2
if xx == 2:
break
def main():
rules()
xo = playerNames()
printboard()
turncount = 0
for turn in range(9):
(r, c) = enterguess(turncount)
print (r, c)
changeboard(r, c, xo, turncount)
turncount += 1
winner = checkWinner()
printboard()
if winner:
print("\nCongratulations " + winner + "! You are the winner.\n")
break
if turn == 8:
print ("\n Well! Its a tie.\n")
main()
The issue you have is that although you recall enterguess, you don't return it. So it simply keeps recalling enterguess until a valid input is given, then it just ignores all this and goes to the final return statement which still has the malformed guess.
Add return statements:
def enterguess(turncount):
def guess(name):
return (int(input("\n" + players[name] + ", Enter row number: ")),
int(input(players[name] + ", Enter column number: ")))
if turncount % 2 == 0:
(row, col) = guess('player1')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player2'] + " already took that spot! Please guess again."
return enterguess(turncount)
except:
print "\nPlease enter the indexes between 1 and 3."
return enterguess(turncount)
else:
(row, col) = guess('player2')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player1'] + " already took that spot! Please guess again."
return enterguess(turncount)
except IndexError:
print "\nPlease enter a number between 1 and 3."
return nterguess(turncount)
return (row - 1, col - 1)

trouble with classes in python

I am getting an error that reads this and no matter what I do I am unable to get rid of this code.
Traceback (most recent call last):
File "C:\Users\Ian\Desktop\BlackJack.py", line 226, in <module>
main()
File "C:\Users\Ian\Desktop\BlackJack.py", line 225, in main
blackjack.playgame()
File "C:\Users\Ian\Desktop\BlackJack.py", line 145, in playgame
self.firstround()
File "C:\Users\Ian\Desktop\BlackJack.py", line 83, in firstround
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
AttributeError: type object 'DeckofCards' has no attribute 'shuffledeck'
The following is the actual code that I have written ( I have changed a great deal in order to move the error along but can no longer figure out what is going on) I am really just want someone to skim over this and tell me about the obvious mistakes, I am sure there are many, and I apologize but our professor doesn't teach use how to do things and then just expects us to know how.
from random import*
class Card(object):
def __init__(self,suit,number):
self.suit=suit
self.number=number
class DeckofCards(object):
def __init__(self,deck):
self.deck=deck
self.shuffledeck=self.shuffle()
#print(self.shuffledeck)
def shuffle(self):
#print('This is shuffle function')
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 #self.blackjacksearch()
def blackjacksearch(self):#this is where it says there is an error we moved this because she said it needed to be in this class to get the Getot function
if self.player.hand.gettot()==21:
return True
else:
return False
def firstround(self):
self.player.inout=True
self.player.hand=[]
self.dealer.hand=[]
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
print(a)
playerbid=int(input('How much would you like to bet?'))
self.player.bid=playerbid
def playturn(self):
while self.player.blackjack!=True or hit=='yes':
print(self.player.hand)
a=self.player.hand.append(deal())
print('The card that you just drew is ' + str(a))
print(gettot())
hit=input('Would you like to hit? ')
if hit=='yes':
return(self.player.hand.append(deal()))
else:
return() #might need to change this
if self.player.blackjack==True:
print(self.player.name + " has blackjack ")
if hit=='no':
print (self.player.hand.gettot())
def playdealer(self):
while self.dealer.hand<17:
self.dealer.hand.append(deal())
dealerhand=self.dealer.hand.gettot() #confused
print(dealerhand)
if self.dealer.hand==21:
self.dealer.blackhjack=True
dealerhand1=self.dealer.hand.gettot()
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'):
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')]
'''tom=Card('Heart','Queen')
print(tom.suit)
print(DeckofCards(ls))
print(ls.suit)'''
def main():
x = input("Player's name? ")
blackjack = Game(ls,x)
blackjack.playgame()
main()
This line right is one problem:
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
append returns None (regardless of what you append), so a will be None
DeckofCards refers to the class object, not an instance of the class. You probably want to use self.deck instead of DeckofCards.
x==Card('S','A'): isn't going to work either. You haven't defined __eq__ for the Card object, so comparisons don't work (you'll always get False).
The shuffledeck attribute only exists for instances of DeckOfCards, change DeckOfCards.shuffledeck to DeckOfCards().shuffledeck.
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 #self.blackjacksearch()
def blackjacksearch(self):#this is where it says there is an error we moved this because she said it needed to be in this class to get the Getot function
if self.player.hand.gettot()==21:
return True
else:
return False
def firstround(self):
self.player.inout=True
self.player.hand=[]
self.dealer.hand=[]
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
You are using the class incorrectly. The DeckofCards was never created.
a=self.dealer.hand.append(self.deck.deal(self.deck.shuffledeck))

Recording a win or loss in a game of craps

So I have to create a game of craps that takes into account bets for an assignment. So far, my code works in that the dice rolls are correct and other little tidbits the assignment called for. But now I don't know how to record each game as a win / lose for the player or computer so that the pot can be added to the winner's money. I realize that my code is half doe, isn't finished, and doesn't run as is, but I just seriously need some help from someone. Please and thank you. Here are more specific directions on my assignment:
http://www.ics.uci.edu/~kay/courses/i42/hw/labA.html
import random
def craps():
print("Welcome to Sky Masterson's Craps Game")
handle_commands()
def handle_commands(): # Collection -> Collection (plus interaction)
""" Display menu to user, accept and process commands
"""
playerInitial = 500
compInitial = 500
MENU = "How much would you like to bet?: "
while True:
bet = float(input(MENU))
if bet <= playerInitial:
human_game()
elif bet > playerInitial:
print("Sorry, you can't bet more than you have")
def handle_commands2():
MENU2 = "Would you like to play again? (y or n): "
while True:
response = input (MENU2)
if response=="y":
counter = counter + multipleGames()
elif response=="n":
while ( counter < 2000):
roll = random.randint(1, 6) + random.randint(1,6)
updateCount(roll)
counter += 1
print ("Thank you for playing." + "\n" + "\n" + "Distribution of dice rolls: " + "\n")
return
else:
invalid_command(response)
def invalid_command(reponse):
"""print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
def play_game():
"""prints shooters roll results
"""
diceRoll = 0
roll = random.randint(1, 6) + random.randint(1, 6)
updateCount(roll)
diceRoll = diceRoll + 1
point = 0
print("The roll is " + str(roll))
response = (roll)
if response== 7 or response== 11:
print("Natural; shooter wins" + "\n" + "Thank you for playing")
handle_commands2()
elif response== 2 or response== 3 or response== 12:
print("Crapped out; shooter loses" + "\n" + "Thank you for playing")
handle_commands2()
else:
print("The point is " + str(roll))
point = roll
secondRoll = 0
handle_commands()
while (secondRoll !=point) and (secondRoll != 7):
secondRoll = random.randint(1, 6) + random.randint(1, 6)
updateCount(secondRoll)
diceRoll += 1
print("The roll is " + str(secondRoll))
handle_commands()
if secondRoll== point:
print ("Made the point; shooter wins." + "\n" + "Thank you for playing")
handle_commands2()
elif (secondRoll == 7):
print ("Crapped out; shooter loses." + "\n" + "Thank you for playing")
handle_commands2()
return diceRoll
def multipleGames():
gameCounter = 0
while (gameCounter <= 2000):
print("Your game: ")
gameCounter += play_game()
print("\n")
print("Computer's game: ")
gameCounter += play_game()
print( "\n")
return gameCounter
def updateCount(point):
count =List[point] + 1
List[point] = count
List = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
def human_game():
playerInitial = 500
compInitial = 500
while True:
play_game()
if
playerInitial += bet
compInitial += bet
counter = 0
counter = counter + multipleGames()
playerInitial -= bet
craps()
for point in List:
print("%2d" %(point) + ": " + "%3d" %(List[point]) + " " + "(" + ("%2d" % (int((List[point])/2000*100)))+ "%" + ")" + " " + ("*" *(int((List[point])/2000*100))))
Use classes:
import random
class Human:
def __init__(self):
self.name = 'Human'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Computer:
def __init__(self):
self.name = 'Computer'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Game:
def __init__(self):
self.rolls = []
self.currentPlayer = None
def roll(self):
self.rolls.append(random.randint(1, 6))
if __name__ == '__main__':
human = Human()
computer = Computer()
game = Game()
game.roll()
print games.rolls
I won't code all of it for you, but using classes will make things much simpler.

Categories