I need to code an accelerate function, accelerating speed by 5 mph and a brake function decelerating speed by 5 mph for a car class with the following logic:
-when braked, speed must be >= 0. if speed < 0 then reset to 0 and display error
-when accelerated, speed be <= 130. if speed > 130 then reset to 130 and display error
I think I've gotten so far as the parameters but not sure how to proceed with the functions themselves.
Tester program:
from Car import *
def main():
my_car = Car("2008", "Honda Accord")
print(f"my_car after instantiating: {my_car}")
my_car.setSpeed(116)
print(f"my_car after my_car.setSpeed(116): {my_car}")
my_car.setSpeed(136)
print(f"my_car after my_car.setSpeed(136): {my_car}")
print ("*** car is accelerating ***")
for i in range(4):
my_car.accelerate()
print ("Current speed: ", my_car.getSpeed())
my_car.setSpeed(11)
print(f"my_car after my_car.setSpeed(11): {my_car}")
print ("*** car is braking ***")
for i in range(3):
my_car.brake()
print ("Current speed: ", my_car.getSpeed())
print(f"my_car at program end: {my_car}")
if __name__ == "__main__":
main()
This is the class:
class Car:
__make_model = ""
__year = ""
__speed = 0
def __init__(self, param_year, param_make_model):
self.__make_model = param_make_model
self.__year = param_year
self.__speed = 0
def setMake_model(self, param_make_model):
self.__make_model = param_make_model
def getMake_model(self):
return self.__make_model
def setYear(self, param_year):
self.__year = make
def getYear(self):
return self.__year
def setSpeed(self, inp_speed):
if inp_speed < 0 or inp_speed > 130:
print(f"Speed cannot be {inp_speed} mph.",
"Speed be must be 0-130 mph")
else:
self.__speed = inp_speed
def getSpeed(self):
return self.__speed
def __str__(self):
ret_val = f"Year : {self.__year}"
ret_val += f", Make and Model : {self.__make_model}"
ret_val += f", Speed : {self.__speed}"
return ret_val
I don't know how to proceed adding this to the class, specifically in getting the class to reset to the limit I want to set.
There is a lot of ways to skin this cat, but here is an option:
class Car:
__make_model = ""
__year = ""
__speed = 0
def __init__(self, param_year, param_make_model):
self.__make_model = param_make_model
self.__year = param_year
self.__speed = 0
def setMake_model(self, param_make_model):
self.__make_model = param_make_model
def getMake_model(self):
return self.__make_model
def setYear(self, param_year):
self.__year = make
def getYear(self):
return self.__year
def setSpeed(self, inp_speed):
if inp_speed < 0 or inp_speed > 130:
print(f"Speed cannot be {inp_speed} mph.",
"Speed be must be 0-130 mph")
else:
self.__speed = inp_speed
def getSpeed(self):
return self.__speed
def accelerate(self):
if self.__speed <= 125:
self.__speed += 5
else:
print("error max speed is 130")
self.__speed = 130
def brake(self):
if self.__speed >= 5:
self.__speed -= 5
else:
print("error reseting to 0")
self.__speed = 0
def __str__(self):
ret_val = f"Year : {self.__year}"
ret_val += f", Make and Model : {self.__make_model}"
ret_val += f", Speed : {self.__speed}"
return ret_val
Related
I've recently been trying to make a Textadventure but I'm having a big problem with the idea of "moving" around a List (x_achses) with a List inside(y-achses) it (my father called it a matrix) and in the second list (y-achses) there are a bunch of random types of things like an enemy. In that "Matrix" I wanna move around and on certain fields it should activate the assigned class(here it should simply print the classes name).
I've tried using the index of the list and changing dependently but it didn't work, I've tried using the len() function and changing it dependently but nothing ever seems to be happening. No classes or anything seem to be called. I have no idea what to do.
import random
import secrets
class Character:
def __init__(self, hp, ad, name):
self.hp = hp
self.ad = ad
self.name = name
def get_hit(self, ad):
self.hp = self.hp - ad
if self.hp <= 0:
self.die()
def is_dead(self):
return self.hp <= 0
def die(self):
print(self.name + " died")
class Human_enemies(Character):
def __init__(self):
super().__init__(self, 10, 3, "Mermaids")
Human_enemies.enemie_amount = random.randint(1, 9)
print("Mermaids")
def enemie_amount(self):
enemie_amount = random.randint(1, 9)
enemies = []
for i in range(enemie_amount):
enemies.append(Human_enemies())
class Vessel:
def __init__(self, hp, ad, storage, name):
self.hp = hp
self.ad = ad
self.storage = storage
self.name = name
def get_hit(self, ad):
self.hp = self.hp - ad
if self.hp <= 0:
self.die()
def is_dead(self):
return self.hp <= 0
def die(self):
print(self.name + " died")
class Sloop_ship(Vessel):
def __init__(self):
super().__init__(self, 1000, 50-100, 0, "Sloop")
def type(self):
print("Sloop")
class Brigattine_ship(Vessel):
def __init__(self):
super().__init__(self, 2500, 70-110, 15, "Brig")
def type(self):
print("Brig")
class Galleon_ship(Vessel):
def __init__(self):
super().__init__(self, 5000, 150-200, 40, "Galleon")
def type(self):
print("Galleon")
class Shipwreck:
def __init__(self):
print("Shipwreck")
wanna_loot = input("Do you want to check the wreck for any loot or survivors?\n")
#TODO: Make this better, sth. like chance of death or sth.
class Fields:
def Rougethingi(self):
random1 = random.randint(0, 5)
if random1 == 0:
return Shipwreck
elif random1 == 1:
return Human_enemies
elif random1 == 2:
return Sloop_ship
elif random1 == 3:
return Brigattine_ship
elif random1 == 4:
return Galleon_ship
else:
return None
class Map():
def __init__(self, x, y):
self.rowsX = []
self.x = x
self.y = y
for i in range(x):
self.rowsY = []
for r in range(y):
self.rowsY.append(Fields.Rougethingi(self))
self.rowsX.append(self.rowsY)
def print_map(self):
for j in self.rowsX:
print("")
for f in self.rowsY:
if f == None:
print("0 ", end = "")
elif f != None:
print("1 ", end = "")
print("\n")
class Player(Character):
def __init__(self):
super().__init__(self, 100, 1, player_name)
def start(self):
self.player_x = 1
self.player_y = 1
n.rowsX[self.player_x].__init__()
n.rowsY[self.player_y].__init__()
def move_right(self):
self.player_x = self.player_x + 1
if self.player_x >= n.x or self.player_x >= n.x - n.x:
print("You can't go further right")
def move_left(self):
self.player_x = self.player_x - 1
if self.player_x >= n.x or self.player_x >= n.x - n.x:
print("You can't go further right")
def move_up(self):
self.player_y = self.player_y + 1
if self.player_y >= n.y or self.player_y >= n.y - n.y:
print("You can't go further right")
def move_down(self):
self.player_y = self.player_y - 1
if self.player_y >= n.y or self.player_y >= n.y - n.y:
print("You can't go further right")
def quit_game():
exit("And the mighty adventurer decided to rest for the day...")
def print_help():
utility = print("(help, save, load, map,)")
movement = print("(forward, backwards, starboard, port)")
utility
movement
def save():
#TODO: Make a save system
pass
def load():
#TODO: Make a load system
pass
if __name__ == "__main__":
player_name = input("What is thy title scalywag?\n")
n = Map(30, 30)
m = Player.start
print("You shall call us for 'help' to help you with your role of Captain\n")
#? This is the main input loop --------------------------------------v
while True:
cmd = input(">>>")
if cmd == "help":
print_help()
continue
elif cmd == "map":
n.print_map()
continue
elif cmd == "quit":
quit_game()
elif cmd == "save":
save()
continue
elif cmd == "load":
load()
continue
elif cmd == "forward":
Player.move_up
continue
elif cmd == "backwards":
Player.move_down
continue
elif cmd == "starboard":
Player.move_right
continue
elif cmd == "port":
Player.move_left
continue
else:
print("I dont understand that... \n")
continue
#? This is the main input loop --------------------------------------v
I'm currently working on a blackjack game for my class and I think I've just about wrapped it up but for some reason I get stuck in an endless loop that keeps restarting the game. Can you help me find it?
import random as r
class Card:
def __init__(self, rank, suit, value):
self.rank = rank
self.suit = suit
self.value = value
def __str__(self):
return self.rank + ' of ' + self.suit
class Deck:
def __init__(self):
self.cards = []
self.shuffle()
def shuffle(self):
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
ranks = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
for suit in suits:
for rank in ranks:
value = ranks.index(rank) + 1
if value > 10: value = 10
if value == 1: value = 11
card = Card(rank, suit, value)
self.cards.append(card)
def deal(self):
if len(self.cards) < 1: self.shuffle()
index = r.randint(0, len(self.cards) - 1)
return self.cards.pop(index)
class Hand:
def __init__(self):
self.cards = []
def deal(self, card):
self.cards.append(card)
return self.value()
def value(self):
score = 0
aces = 0
for card in self.cards:
score += card.value
if card.value == 11: aces += 1
while score > 21 and aces > 1:
score -= 10
aces -= 1
return score
class Game:
def __init__(self):
self.deck = Deck()
self.player = Hand()
self.dealer = Hand()
self.wins = 0
self.losses = 0
self.exit = False
while not self.exit:
self.play()
def play(self):
self.deal()
if self.playerphase():
if self.dealerphase():
if self.player.value() > self.dealer.value():
self.outcome('player')
elif self.player.value() < self.dealer.value():
self.outcome('dealer')
else: self.outcome('pushback')
else: self.outcome('player', bust = True)
else: self.outcome('dealer', bust = True)
def deal(self):
self.player = Hand()
self.dealer = Hand()
for x in range(2):
self.player.deal(self.deck.deal())
self.dealer.deal(self.deck.deal())
def playerphase(self):
stand = False
options = ['hit', 'stand']
prompts = ["Enter 'hit or 'stand':"]
while not stand:
call = self.display(options, prompts)
if call == 'hit':
self.player.deal(self.deck.deal())
if self.player.value() > 21:
stand = True
else: stand = True
if self.player.value() > 21: return False
else: return True
def dealerphase(self):
while self.dealer.value() < 17:
self.dealer.deal(self.deal.deal())
if self.dealer.value() > 21: return False
else: return True
def display(self, options, prompts, show=False):
user = ''
while user not in options:
for x in range(30): print()
print('Wins: ' + str(self.wins))
print('Losses: ' + str(self.losses))
print('\nDealer: ')
if show: print(self.dealer.cards[0])
else: print('Face-Down Card')
for x in range (1, len(self.dealer.cards)):
print(self.dealer.cards[x])
print('\nPlayer:')
for card in self.player.cards:
print(card)
for prompt in prompts: print(prompt)
user = ''
return user
def outcome(winner, bust = False):
prompts = []
options = ['play', 'exit']
if winner == 'player':
prompts.append('player wins!')
if bust: prompts.append('dealer busts')
self.wins += 1
elif winner == 'dealer':
prompts.append('Dealer wins :(')
if bust: prompts.append('player busts')
self.losses += 1
else: prompts.append('Pushback!')
call = self.display(options, prompts, show = True)
if call == 'exit': self.exit = True
game = Game()
This question already has answers here:
Why does random.shuffle return None?
(5 answers)
Closed 3 years ago.
I tired to make a simple blackjack game in Python. When executing the code, list of cards in deck (self.deck) creates problems - becomes NoneType, when it should be a list.
'''
This is a blackjack game for the project 2
'''
import random
cardsuits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
cardrank = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
cardvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card:
#class card has two attributes: suit and rank. asking for string will result in rank of suit response. There is a value calcluated, using cardvalues dictionary.
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.rank + ' of ' + self.suit
#def value(self):
# self.value = cardvalues[self.rank]
# #think about ace here; it can be worth 10 or 1 depending on hand
class Deck:
def __init__(self):
self.deck = []
for suit in cardsuits:
for rank in cardrank:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = ""
for card in self.deck:
deck_comp = deck_comp + "\n" + card.__str__()
return "Deck contains " + deck_comp
def reroll(self):
self.deck = random.shuffle(self.deck)
def take_a_card(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self, card):
self.cards.append(card)
self.value = self.value + cardvalues[card.rank]
if card.rank == "Ace":
self.aces = self.aces + 1
def ace_adjust(self):
if self.value > 21 and self.aces > 0:
self.value = self.value - 10
self.aces = self.aces -1
class Funds:
def __init__(self):
self.balance= 0
self.bet = 0
def winbet(self):
self.balance = self.balance + self.bet * 2
def losebet(self):
self.bet = 0
def draw(self):
self.balance = self.balance + self.bet
self.bet = 0
def Place_a_Bet():
while True:
placebetamount = int(input(print('Select amount you want to bet.')))
if isinstance(placebetamount, int) == False:
print('Invalid bet type. You have to input a digit.')
continue
elif placebetamount > PlayerFunds.balance:
print('You tried to bet more money than you have available. You cannot bet more than: ' + PlayerFunds.balance)
continue
elif placebetamount <= 0:
print('Invaild Bet. You have to bet a positive number.')
continue
else:
PlayerFunds.balance = PlayerFunds.balance - placebetamount
PlayerFunds.bet = placebetamount
break
def hit(deck,hand):
hand.add_card(CurrentGameDeck.take_a_card())
hand.ace_adjust()
def hit_or_stand(deck, hand):
global playing # to control an upcoming while loop
Decision = input(str(print('Your Turn. Type "Hit" to get another card. Type "Stand" to move onto Dealers move')))
while True:
if Decision == "Hit":
hit(deck,hand)
elif Decision == "Stand":
playing = False
else:
print('just Hit or Stand. Other inputs are invalid')
continue
break
def CardStateGame(PlayerHand, DealerHand):
print('Dealer Shows : ' + DealerHand.cards[0] + ' out of ' + len(DealerHand.cards))
print('Dealer score is :' + DealerHand.value)
print('Your cards are ')
for card in PlayerHand.cards:
print(card)
print('and their value is: ' + PlayerHand.value)
def CardStateEndgame(PlayerHand, DealerHand):
print('Dealer value is ' + DealerHand.value + ' and his cards are: ')
for card in DealerHand.cards:
print(card)
print('Your cards are ')
for card in PlayerHand.cards:
print(card)
print('and their value is: ' + PlayerHand.value)
#end conditions
def player_bust(PlayerHand, PlayerFunds):
print('Value of your cards (' + PlayerHand.value +') exceeds 21. You lose.')
PlayerFunds.losebet()
def player_wins(PlayerFunds):
print('You won.')
PlayerFunds.winbet()
def dealer_bust(DealerHand, PlayerFunds):
print('Dealer loses, because value of his cards (' + DealerHand.value +') exceeds 21')
PlayerFunds.winbet()
def dealer_wins(PlayerFunds):
print('Dealer won.')
PlayerFunds.losebet()
def draw(PlayerFunds):
print('Both participants have same values. Its a draw')
PlayerFunds.draw()
#gameplay
print('This is a game of blackjack. You and the dealer (AI) will try to reach card value of 21, or just higher than your opponent. Scores higher than 21 will lose')
PlayerFunds = Funds()
while True:
startamount = int(input(print('Select the amount of money you enter the game with. Try to keep it plausible')))
if startamount <= 0 or isinstance(startamount, int) == False:
print('You cant play with that amount of money. try again')
continue
else:
PlayerFunds.balance = startamount
break
playing = True
while True:
CurrentGameDeck = Deck()
CurrentGameDeck.reroll()
Place_a_Bet()
DealerHand = Hand()
PlayerHand = Hand()
DealerHand.add_card(CurrentGameDeck.take_a_card())
PlayerHand.add_card(CurrentGameDeck.take_a_card())
DealerHand.add_card(CurrentGameDeck.take_a_card())
PlayerHand.add_card(CurrentGameDeck.take_a_card())
CardStateGame(PlayerHand, DealerHand)
while playing == True:
hit_or_stand(CurrentGameDeck,PlayerHand)
CardStateGame(PlayerHand, DealerHand)
if PlayerHand.value >21:
player_bust(PlayerHand, PlayerFunds)
break
if PlayerHand.value <= 21:
while DealerHand.value <17:
hit(CurrentGameDeck, DealerHand)
CardStateEndgame
if DealerHand.value > 21:
dealer_bust()
elif DealerHand.value > PlayerHand.value:
dealer_wins()
elif PlayerHand.value > DealerHand.value:
player_wins()
elif PlayerHand.value == DealerHand.value:
draw()
newgame = 0
newgame = input(print('Do you want to play again? Type Y or N'))
if newgame.lower() == 'Y' and PlayerFunds.balance >=0:
playing = True
continue
elif newgame.lower() == 'Y' and PlayerFunds.balance < 0:
print('no more funds. GG')
break
else:
print('thanks for playing')
break
I tried to use only
cardsuits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
cardrank = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
cardvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card:
#class card has two attributes: suit and rank. asking for string will result in rank of suit response. There is a value calcluated, using cardvalues dictionary.
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.rank + ' of ' + self.suit
#def value(self):
# self.value = cardvalues[self.rank]
# #think about ace here; it can be worth 10 or 1 depending on hand
class Deck:
def __init__(self):
self.deck = []
for suit in cardsuits:
for rank in cardrank:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = ""
for card in self.deck:
deck_comp = deck_comp + "\n" + card.__str__()
return "Deck contains " + deck_comp
def reroll(self):
self.deck = random.shuffle(self.deck)
def take_a_card(self):
single_card = self.deck.pop()
return single_card
and then
test = Deck()
allows me to shuffle the deck, and pop a single card out of it - so other parts of the code may be a problem, but I have no idea which, where and why.
In the future you should try to slim your code down to pinpoint the problem. Since the issue was surrounding the deck you only really needed to post that class. The error you are getting is because of this function below:
def reroll(self):
self.deck = random.shuffle(self.deck)
If you take a look at the docs you will see that this function shuffles in place. Change the function to be this instead:
def reroll(self):
random.shuffle(self.deck)
I'm supposed to create an Account class which uses some of the functions defined in the class above it. I'm having trouble with error checking in my withdraw class.
def withdraw(self, amount):
if amount > self.money:
return 'Error'
self.money -= amount
>>> a = Money(5,5)
>>> b = Money(10,1)
>>> acct1 = Account('Andrew', a)
>>> print(acct1)
Andrew's account balance is $5.05
>>> c = Money(3,50)
>>> acct1.deposit(c)
>>> print(acct1)
Andrew's account balance is $8.55
>>> acct1.withdraw(b)
>>> print(acct1)
Andrew's account balance is $-2.54
The output should be Error, but instead it just calculates and gives me back a negative balance.
The entire code is here:
class Money:
def __init__(self, dollars = 0, cents = 00):
'constructor'
self.dollars = dollars
self.cents = cents
if self.cents > 99:
self.dollars += 1
self.cents = self.cents - 100
def __repr__(self):
'standard representation'
return 'Money({}, {})'.format(self.dollars,self.cents)
def __str__(self):
'returns a string representation of ($dollars.cents)'
if self.cents < 10:
return '${}.0{}'.format(self.dollars, self.cents)
else:
return '${}.{}'.format(self.dollars, self.cents)
def __add__(self, new):
'Adds two money objects together'
d = self.dollars + new.dollars
c = self.cents + new.cents
return Money(d,c)
def __sub__(self, new):
'Subtracts two money objects'
d = self.dollars - new.dollars
c = self.cents - new.cents
return Money(d,c)
def __gt__(self, new):
'computes greater then calculations'
a = self.dollars + self.cents
b = new.dollars + new.cents
return a > b
class Account:
def __init__(self, holder, money = Money(0,0)):
'constructor'
self.holder = holder
self.money = money
def __str__(self):
return "{}'s account balance is {}".format(self.holder, self.money)
def getBalance(self):
return self.money
def deposit(self, amount):
self.money = self.money + amount
def withdraw(self, amount):
if amount > self.money:
return 'Error'
self.money -= amount
Actually it is because you don't compute the "balance" inside your __gt__ correctly.
The dollars should be multiplied by 100:
def __gt__(self, new):
a = self.dollars * 100 + self.cents
b = new.dollars * 100 + new.cents
return a > b
Optional: Instead of returning 'Error' you should consider raising an Exception:
def withdraw(self, amount):
if amount > self.money:
raise ValueError('Not enough money')
self.money -= amount
We are making this Black Jack program to test card counting methods. We are trying to get the auto play function working, and it does, but when we run it in a while loop the loop never finishes and exits.
"""
Eli Byers
Josh Rondash
Black_Jack.py
"""
import random
#---------- CLASSES -----------------------------------------------------------
class Card(object):
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.value = 0
if self.rank is "Ace":
self.value = 11
if self.rank.isdigit():
self.value = int(self.rank)
if self.rank in ["Jack", "Queen", "King"]:
self.value = 10
def __str__(self):
return "["+str(self.rank)+" "+str(self.suit)+"]"
class Deck(object):
def __init__(self, numofdecks):
self.deck = []
self.suit = [" Clubs", " Hearts", " Spades", " Diamonds"]
self.rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
self.numofdecks = numofdecks
for i in range(self.numofdecks):
for r in self.rank:
for s in self.suit:
self.deck.append(Card(r,s))
def __str__(self):
deck_str = ""
for card in self.deck:
deck_str += str(card)+" "
deck_str = deck_str[:-1]
return deck_str
def __len__(self):
return len(self.deck)
def __getitem__(self,i):
return self.deck[i]
def __delitem__(self, i):
del self.deck[i]
def draw(self):
top_card = self.deck[0]
del self.deck[0]
return top_card
def addcard(self,card):
self.deck.append(card)
def shuffle(self): #Random shuffle function
a = len(self.deck)
b = a-1
for d in range(b,0,-1):
e = random.randint(0,d)
if e == d:
continue
self.deck[d],self.deck[e] = self.deck[e],self.deck[d]
return self.deck
class Player(object):
def __init__(self, bankroll):
self.hand = []
self.bankroll = bankroll
self.score = 0
self.bet = 0
self.count = 0
self.aces = 0
self.dealer_hand = []
def __str__(self):
hand = ""
for card in self.hand:
hand += str(card)+" "
return "Hand: "+hand+" Bank: "+str(self.bankroll)+" Bet: "+str(self.bet)+" Ct: "+str(self.count)+" A: "+str(self.aces)
def __getitem__(self, i):
return self.hand[i]
def getcard(self,Card):
self.hand.append(Card)
self.score = 0
ace = 0
for card in self.hand:
if card.rank == "Ace":
ace += 1
self.score += 1
else:
self.score += card.value
for a in range(ace):
if (self.score + 10) <= 21:
self.score += 10
self.updateCount(Card,"P")
def placebet(self, b=0):
if b != 0:
self.bankroll -= b
self.bet += b
else:
self.bet += input("Bankroll: "+str(self.bankroll)+" Ct: "+str(self.count)+" A: "+str(self.aces)+" Place bet: ")
self.bankroll -= self.bet
def updateCount(self, card, player):
if card.value in range(2,6):
self.count += 1
elif card.value is 10:
self.count -= 1
elif card.rank is "Ace":
self.aces += 1
if player == "D":
self.dealer_hand.append(card)
def makeBet(self):
bet = 0.1*self.bankroll
if self.count > 3:
c = 0
for i in range(self.count):
c += 1
if c == 3:
bet += 0.5 * bet
c = 0
elif self.count < -3:
bet -= 0.5 * bet
return bet
def Play(self):
if self.score < 17:
choice = 1 #hit
else:
choice = 2 #stand
return choice
class Dealer(object):
def __init__(self, Deck, discardpile, Player):
self.deck = Deck
self.discardpile = discardpile
self.player = Player
self.hand = []
self.score = 0
def __str__(self):
hand = ""
for card in self.hand:
hand += str(card)+" "
return "Dealer Hand: "+hand
def __getitem__(self, i):
return self.deck[i]
def draw(self):
cardval = self.deck.draw()
self.hand.append(cardval)
self.score = 0
ace = 0
for card in self.hand:
if card.rank == "Ace":
ace += 1
self.score += 1
else:
self.score += card.value
for a in range(ace):
if (self.score + 10) <= 21:
self.score += 10
player.updateCount(cardval,"D")
def deal(self, Player):
for i in range(2):
self.player.getcard(self.deck.draw())
self.draw()
def burn(self):
self.discardpile.addcard(self.deck.draw())
def blackjack(self):
if self.score == 21:
return True
else:
return False
class Table(Dealer, Player):
def __init__(self, Dealer, Player, Deck , discardpile):
self.dealer = Dealer
self.player = Player
self.deck = Deck
self.discardpile = discardpile
self.betplaced = 0
def initGame(self):
self.clearTable()
Deck.shuffle(self.deck)
self.dealer.burn()
def clearTable(self):
for card in self.player.hand:
self.discardpile.addcard(card)
for card in self.dealer.hand:
self.discardpile.addcard(card)
self.player.hand = []
self.dealer.hand = []
def playGame(self):
self.betplaced = self.player.placebet()
self.dealer.deal(self.player)
print self.player
print self.dealer
if self.dealer.blackjack():
print("Dealer Black Jack!")
elif self.player.score <= 21:
stand = 0
while self.player.score < 21 and stand == 0:
print("Use number Keys> Hit: 1 Stand: 2")
choice = input()
if choice == 1: # Hit
self.player.getcard(self.deck.draw())
elif choice == 2: # Stand
stand = 1
print self.player
print ("Your score is "+str(self.player.score))
while self.dealer.score <= 17 and self.player.score <= 21:
if self.dealer.score == 17:
for card in self.dealer.hand:
if card.rank == "Ace":
self.dealer.draw()
else:
self.dealer.draw()
print self.dealer
print ("Dealer score is "+str(self.dealer.score))
if self.dealer.score <= 21:
if (self.player.score > self.dealer.score) and (self.player.score <= 21) :
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
elif self.player.score == self.dealer.score:
self.player.bankroll += self.player.bet
print("Push")
else:
print("You Lose")
elif (self.dealer.score > 21) and (self.player.score <= 21):
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
else:
print("You Lose.")
self.player.bet = 0
self.player.dealer_hand = []
print
def autoPlay(self):
self.betplaced = self.player.placebet(int(self.player.makeBet()))
self.dealer.deal(self.player)
if (self.dealer.blackjack() == False) and (self.player.score <= 21):
stand = 0
while self.player.score < 21 and stand == 0:
choice = player.Play()
if choice == 1: # Hit
self.player.getcard(self.deck.draw())
elif choice == 2: # Stand
stand = 1
while self.dealer.score <= 17 and self.player.score <= 21:
if self.dealer.score == 17:
for card in self.dealer.hand:
if card.rank == "Ace":
self.dealer.draw()
else:
self.dealer.draw()
if self.dealer.score <= 21:
if (self.player.score > self.dealer.score) and (self.player.score <= 21):
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
elif self.player.score == self.dealer.score:
self.player.bankroll += self.player.bet
print("Push")
else:
print("Lose")
elif (self.dealer.score > 21) and (self.player.score <= 21):
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
else:
print("Lose")
self.player.bet = 0
self.player.dealer_hand = []
print self.player.bankroll
#----------- MAIN -----------------------------------
deck = Deck(6)
player = Player(500)
discardpile = Deck(0)
dealer = Dealer(deck, discardpile, player)
table = Table(dealer, player, deck, discardpile)
table.initGame()
while (player.bankroll > 0) and (player.bankroll < 1000):
table.autoPlay()
table.clearTable()
print "Game Over."
Just add some debug statements. You have multiple while loops in your methods. I'm sure a simple print statement will catch the errors in your logic.
DUDE, I found the infinite loop within 1 minute. lucky i had python installed on my box.
LINE 251
if (self.dealer.blackjack() == False) and (self.player.score <= 21):
stand = 0
while self.player.score < 21 and stand == 0:
print "in player score"
choice = player.Play()
if choice == 1: # Hit
self.player.getcard(self.deck.draw())
elif choice == 2: # Stand
stand = 1
while self.dealer.score <= 17 and self.player.score <= 21:
print "in dealer score"
print self.dealer.score
if self.dealer.score == 17:
for card in self.dealer.hand:
if card.rank == "Ace":
self.dealer.draw()
else:
self.dealer.draw()