I am converting an array into a string to print, but the compiler still says not iterable.
Traceback (most recent call last):
File "python", line 157, in <module>
File "python", line 56, in total
TypeError: 'int' object is not iterable
The function total() is located on line 56, if you think it is the problem, but if you run the script, you should find that the function works properly every other instance.
import random
import time
def makeDeck():
cards = []
num = 1
for card in range(52):
cards.append(num)
num += 1
if num == 13:
num = 1
return cards
#def shuffle(cards):
#for card in cards:
#num = random.randint(0,51)
#cards.insert(0, cards[num])
#return cards
def shuffle(deck):
for card in deck:
hold = deck.pop(0)
deck.insert(random.randint(1,51),hold)
return deck
def cardToString(hand):
cardString = []
for card in hand:
if card == 1:
cardString.append('Ace')
elif card == 11:
cardString.append('Jack')
elif card == 12:
cardString.append('Queen')
elif card == 13:
cardString.append('King')
else:
cardString.append(str(card))
for card in cardString:
return card
def deal(user,deck):
hand = []
for x in range(2):
hand.append(deck.pop(0))
return hand
def deal1(user,deck):
hand = []
for card in deck:
hand.append(deck.pop(0))
return hand
def total(hand):
score = 0
for card in hand:
if(card>10):
score += 10
elif(card != 1):
score += card
else:
if(score>=11):
score+=1
else:
score+=11
return score
#def playGame():
#to do
name1 = input('Player 1, please enter your name:\n')
p2q = input('Will there be two plaers? (y/n)')
if(p2q == 'y' or p2q == 'Y' ):
p2yn = 1
name2 = input('Player 2, please enter your name:\n')
elif(p2q == 'n' or p2q == 'N'):
p2yn = 0
deck = makeDeck()
shuffle(deck)
p1hand = deal(name1,deck)
if(p2yn == 1):
p2hand = deal(name2,deck)
else:
print(end = ' ')
hs=0
print(str(name1)+', your hand is:', end = ' ' )
cardToString(p1hand)
print(str(p1hand[0])+',',p1hand[1], end = ' ')
print('and your total is', total(p1hand))
time.sleep(2)
tot1 = total(p1hand)
while(tot1 < 21):
p1cvar = input('Would you like another card? (y/n)\n')
if(p1cvar =='n' or p1cvar == 'N'):
break
else:
p1hand.append(deck.pop(0))
newCard = str(p1hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p1hand))
time.sleep(1)
if(total(p1hand) <= 21):
hs = total(p1hand)
else:
print('You went over 21!')
p1hand=0
time.sleep(1)
break
if(p1hand != 0):
print('The high score is', total(p1hand), 'held by', str(name1)+'.')
time.sleep(1)
shuffle(deck)
if(p2yn == 1):
print(str(name2)+', your hand is:', end = ' ' )
cardToString(p2hand)
print(str(p2hand[0])+',',p2hand[1], end = ' ')
print('and your total is', total(p2hand))
time.sleep(2)
tot1 = total(p2hand)
while(tot1 < 21):
p2cvar = input('Would you like another card? (y/n)\n')
if(p2cvar =='n' or p2cvar == 'N'):
break
else:
p2hand.append(deck.pop(0))
newCard = str(p2hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p2hand))
time.sleep(1)
if(total(p2hand)>21):
print('You went over 21!')
p2hand=0
time.sleep(1)
break
if(p2hand != 0 and total(p2hand)>hs):
print('The high score is', total(p2hand), 'held by', str(name2)+'.')
hs = total(p2hand)
time.sleep(1)
dealerHand = deal('Dealer',deck)
print("The dealer's hand is:", end = ' ' )
cardToString(dealerHand)
print(str(dealerHand[0])+',',dealerHand[1], end = ' ')
print('and their total is', total(dealerHand))
time.sleep(2)
totD = total(dealerHand)
while(totD < 21):
tdh = total(dealerHand)
if(tdh<hs and tdh<22):
dealerHand.append(deck.pop(0))
newCard = str(dealerHand[-1])
cardToString(newCard)
print('Dealer got a', newCard)
time.sleep(.5)
print("Dealer's total is now", total(dealerHand))
time.sleep(1)
if(total(dealerHand) <= 21 and total(dealerHand)>hs):
hs = total(dealerHand)
else:
print('Dealer went over 21!')
dealerHand=0
else:
break
if(dealerHand != 0):
print('The high score is', total(dealerHand), 'held by', str("Dealer")+'.')
while(total(p1hand)>21 or total(dealerHand)>21):
if(total(dealerHand)>21):
print('Dealer has been eliminated from play!')
elif(total(p1hand)>21):
print(name1,'has been eliminated from play!')
About 11 lines up from the bottom of your code block, you are setting the dealers hand to 0:
....
else:
print('Dealer went over 21!')
dealerHand=0
This is concerning since their hand should be a list. Thus when you try to iterate over it to count the total, you get that an int isn't iteratable.
Should probably be something like
dealerHand = []
Also, a few lines after that, you are asking if dealerHand!=0, when I think you mean total(dealerHand)
You should also be careful with your other assignments that change a variable from a list to an int such as
#Around line 111
print('You went over 21!')
p1hand=0
time.sleep(1)
break
.....
#Around line 140
print('You went over 21!')
p2hand=0
time.sleep(1)
break
Because Python is not strongly type, changing the type of a given variable name can lead to a lot of these kinds of problems
#Stephen gave you the direct answer. I suggest using pylint3 (or some other linter) on your code. It would have told you the problem
R:170, 6: Redefinition of dealerHand type from list to int
(redefined-variable-type)
This will help you in the future.
Related
so my code is designed to basically create a bingo card, then when you press enter draws a number and changes the bingo card value to 0 if the drawn number matches. My issue is that my code isn't properly producing a bingo or not a bingo which you can see towards the end of the code. How should I change this so that my code will return bingo when I have bingo.
import random #Condernsed solo version with call and player together
import numpy as np
def bingo_card(): #Code to generate BINGO card using numpy array
test1=np.array(random.sample(range(1,16),5))
test2=np.array(random.sample(range(16,31),5))
test3=np.array(random.sample(range(31,46),5))
test4=np.array(random.sample(range(46,61),5))
test5=np.array(random.sample(range(61,76),5))
test= np.concatenate((test1,test2,test3,test4,test5))
test= test.reshape(5,5)
test[2,2]=0
bingo_card.test = test
BINGO= print("Your Card")
print("B", test[0]),
print("I", test[1]),
print("N", test[2]),
print("G", test[3]),
print("O", test[4])
card = BINGO
return card
def called_value(): #should be close to the code we use to check if called value is in generated matrix, may need some formatting and fixing
checked_card = bingo_card.test
while True:
called_num = input ("Type called number to mark card or press 's' to quit if you think you have bingo").lower()
if called_num != "s":
number_check = int(called_num)
checked_card = np.where(checked_card==number_check,0,checked_card)
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
elif called_num == "s":
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
row_zeros = np.count_nonzero(checked_card == 0, axis=1)
col_zeros = np.count_nonzero(checked_card == 0, axis=0)
diagonal_zeros = np.count_nonzero(np.diag(checked_card) == 0)
diagonal1_zeros = np.count_nonzero(np.diag(np.fliplr(checked_card)) == 0)
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
def solo():
bingo_card()
called_value()
solo()
You've committed one of the classic blunders.
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
row_zeros[i] or col_zeros[i] is going to be True or False (usually True), which is never equal to 5. And you don't need to loop to check the diagonals. You need:
if diagonal_zeros == 5 or diagonal1_zeros == 5:
return ("Bingo!")
for i in range (5):
if row_zeros[i] == 5 or col_zeros[i] == 5:
return ("Bingo!")
return ("Not Bingo")
I get a TypeError int object is not subscriptable and my code is unfinished I just want to know where my mistake is and how can I fix it, Thanks :)
Traceback (most recent call last):
File "C:\Users\TOSHIBA\.spyder-py3\untitled1.py", line 40, in <module>
print('You have:' , card_values(player_hand)) # telling the player's value if he stands
File "C:\Users\TOSHIBA\.spyder-py3\untitled1.py", line 19, in card_values
if (i[0:1] == 'J' or i[0:1] == 'Q' or i[0:1] == 'K' or i[0:1] == 10):
TypeError: 'int' object is not subscriptable
This is the error I get
#Code Begins
print('Welcome to BLACKJACK!') # welcome message
import random #importing random function
cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q','K'] # list for the cards with mixed data types
player_hand = random.choices(cards, k=2) #Drawing the player's cards(hand)
dealer_hand = random.choices(cards, k=2) #Drawing the dealer's cards(hand)
def card_values(the_hand): #function to calculate card values
the_count = 0
ace_count = 0
for i in the_hand:
if (i[0:1] == 'J' or i[0:1] == 'Q' or i[0:1] == 'K' or i[0:1] == 10):
the_count +=10
elif (i[0:1] != 'A'):
the_count += int(cards[0:1])
else:
ace_count +=1
if (ace_count == 1 and the_count <= 10):
the_count += 11
elif(ace_count != 0):
the_count += 1
return the_count
print ('Your cards are:' , player_hand) #printing the hands
print ("The dealer's cards are:" , '[' ,'X', ',', dealer_hand[0], ']') #printing the hands
game = input('What would you like to do? H = HIT ME or S = Stand: ') #asking the user to hit or stand
if game == 'Hit': #drawing a card to the player's hand if he hits
player_hand = random.choices(cards , k=1)
else:
print('You have:' , card_values(player_hand)) # telling the player's value if he stands
while card_values(dealer_hand) <= 16: #adding a card if the dealer's hand is less than 16
dealer_hand = random.choices(cards , k=1)
While #Michael Guidry's answer is correct, I would like to build on it to address the style issues.
You can put the card_values definition at the top before the cards and hands because those are not relevant yet. Using explicit variable names is much better for reading and comprehension so I replaced with for i in the_hand: with for card in the_hand:. The choices are now sorted in an order that's easier to understand (if ace/elif figures/else others rather than if figures or 10/elif not ace/else others). The hit/stand choice is now encased in a while loop to ask the question again in case the user does not reply "H" or "S" but something that is not supported.
import random # Importing random function.
def card_values(the_hand):
"""This function calculate the values of a given hand."""
the_count = 0
ace_count = 0
for card in the_hand:
if card == "A":
ace_count += 1
elif card in ("J", "Q", "K"):
the_count += 10
else:
the_count += card
if ace_count == 1 and the_count <= 10:
the_count += 11
elif ace_count != 0:
the_count += 1
return the_count
# This is where the game starts.
cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q','K'] # List for the cards with mixed data types.
player_hand = random.choices(cards, k=2) # Drawing the player's cards (hand).
dealer_hand = random.choices(cards, k=2) # Drawing the dealer's cards (hand).
print('Your cards are:', player_hand) # Printing the hands.
print("The dealer's cards are:", '[' ,'X', ',', dealer_hand[0], ']') # Printing the hands.
# Ask the user to hit or stand. Repeat until the input is valid.
while True:
choice = input('What would you like to do? H = HIT ME or S = Stand: ')
if choice in ("H", "S"):
break
else:
print(f'Your choice "{choice}" is not supported, please provide the input again.)'
if choice == "H": # Drawing a card to the player's hand if he hits.
player_hand = random.choices(cards , k=1)
else:
print(player_hand)
print('You have: ', card_values(player_hand)) # Telling the player's value if he stands.
while card_values(dealer_hand) <= 16: # Adding a card if the dealer's hand is less than 16.
dealer_hand = random.choices(cards , k=1)
Your problem is simple: i is not subscriptable because i is the value. After you fix that your next error will be this part the_count += int(cards[0:1]) which should be the_count += i.
full example
import random #importing random function
cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q','K'] # list for the cards with mixed data types
player_hand = random.choices(cards, k=2) #Drawing the player's cards(hand)
dealer_hand = random.choices(cards, k=2) #Drawing the dealer's cards(hand)
def card_values(the_hand): #function to calculate card values
the_count = 0
ace_count = 0
for i in the_hand:
if i in ('J', 'Q', 'K', 10):
the_count +=10
elif (i != 'A'):
the_count += i
else:
ace_count +=1
if (ace_count == 1 and the_count <= 10):
the_count += 11
elif(ace_count != 0):
the_count += 1
return the_count
print ('Your cards are:' , player_hand) #printing the hands
print ("The dealer's cards are:" , '[' ,'X', ',', dealer_hand[0], ']') #printing the hands
game = input('What would you like to do? H = HIT ME or S = Stand: ') #asking the user to hit or stand
if game == 'Hit': #drawing a card to the player's hand if he hits
player_hand = random.choices(cards , k=1)
else:
print(player_hand)
print('You have:' , card_values(player_hand)) # telling the player's value if he stands
while card_values(dealer_hand) <= 16: #adding a card if the dealer's hand is less than 16
dealer_hand = random.choices(cards , k=1)
EDIT
If we are going to get into the style of scripts then we can start over entirely. This is a game so, automatically the first thing you need is a game loop. The next thing to do is simply 'play' the game with code. In blackjack the dealer and player get a hand. The first thing to happen in the game loop is for the dealer and player to get a hand. Both of those hands already have a value so we immediately get it and keep it updated the entire time. The next step is the player's choice to get hit or stand. We only need to know about 'hit'. 'hit' is the only choice that isn't the end of the game. Finally we simply compare the scores to concoct the proper message and print all of the game properties. The user is then asked if they want to run the loop again. Anything other than 'n' or 'no' is 'yes' ... regardless of our little message claiming something about a 'y'.
import random, os
# card references
facecards = ['Ace', 'Jack', 'Queen', 'King']
numcards = ['2', '3', '4', '5', '6', '7', '8', '9', '10']
# clears the console on windows
clear = lambda: os.system('cls')
# calculate hand total
def sum(hand):
c = 0
for card in hand:
if card != 'Ace':
c += 10 if not card in numcards else int(card)
else:
c += 11 if c < 11 else 1
return c
# create a shuffled deck
def shuffled_deck(shuffles=3, cuts=2):
deck = [*facecards, *numcards] * 4
shuffles = 3 if shuffles < 1 else shuffles
cuts = 2 if cuts < 1 else cuts
for i in range(shuffles):
random.shuffle(deck)
for i in range(cuts):
n = random.randint(1, len(deck))
deck = [*deck[n::], *deck[0:n]]
return deck
# the actual game
def game_loop():
playing = True # we wont be 'playing' if the dealer busts
deck = shuffled_deck() # get a fresh deck
# you get a hand
player_hand = [deck.pop(0), deck.pop(1)] # simulate alternating cards
player = sum(player_hand)
#the dealer gets a hand
dealer_hand = [deck.pop(0), deck.pop(0)]
dealer = sum(dealer_hand)
#the dealer continues to pick until the hand is worth at least 16
while dealer < 16:
dealer_hand.append(deck.pop(0))
dealer = sum(dealer_hand)
playing = dealer <= 21
# allow the player to keep getting hit as long as the player hasn't busted
while playing:
if player < 21:
clear()
print(f'\tDealer\ttotal: ??\tcards: X, {", ".join(dealer_hand[1::])}\n')
print(f'\tPlayer\ttotal: {player}\tcards: {", ".join(player_hand)}\n')
if input('\tTake a hit? (y)es or (n)o: ').lower() in ('y', 'yes'):
player_hand.append(deck.pop(0))
player = sum(player_hand)
continue
else:
break
else:
break
# end of game
clear()
if player <= 21:
if dealer > 21 or dealer <= player:
print('\tCongratulations! You Are The Big Winner!\n')
else:
print('\tUnfortunately, You Lose.\n')
else:
print('\tYou Busted! Better Luck Next Time.\n')
print(f'\tDealer\ttotal: {dealer}\tcards: {", ".join(dealer_hand)}\n')
print(f'\tPlayer\ttotal: {player}\tcards: {", ".join(player_hand)}\n')
if not input('\tWould you like to play again? (y)es or (n)o: ').lower() in ('n', 'no'):
game_loop()
I have just starting learning Python and I am writing a rudimentary Blackjack game. I have got the basic stuff working but I want to add a little bit of finesse here and there. I am looking for a way in which my introduction function at the beginning of my while loop is substituted for my new_round function.
My idea was that I could have a round counter running at the top which would dictate which function would run through and if/elif statement.
Suffice it to say, it doesn't work. Firstly, I would like to know why it doesn't and secondly would like a way to do it!
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'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}
player_name = ''
playing = True
class Card:
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'{self.rank} of {self.suit}'
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = ''
for card in self.deck:
deck_comp += '\n '+card.__str__()
return 'The deck has:' + deck_comp
def shuffle(self):
random.shuffle(self.deck)
def deal(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 += values[card.rank]
if card.rank == 'Ace':
self.aces += 1
def adjust_for_ace(self):
#if value of players hand is over 21 and includes an ace then the player will automatically have the ace value reduced to 1
#also track ace counter will revert to 0
while self.value > 21 and self.aces > 0:
self.value -= 10
self.aces -= 1
class Chips:
def __init__(self,total):
self.total = total
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
player_chips.bet = int(input('How many chips would you like to bet?: '))
except ValueError:
print('\nSorry, the number of chips must be a number!')
else:
if player_chips.bet > player_chips.total:
print(f"\nSorry guy, your bet can't exceed {player_chips.total} chips.")
else:
print(f"\nYour bet of {player_chips.bet} chips has been accepted - good luck!")
break
def introduction():
global player_name
print("\nWelcome to BlackJack! Get as close to 21 as you can without busting.\n\nThe Dealer will hit up to 17, Face cards count as 10 and Aces are 1/11.")
player_name=input("The first round is about to begin, what is your name friend?: ")
def next_round():
global player_name
print("Hey ho, let's go another round!")
def chip_count():
global player_name
print(f"{player_name}, your current chip count stands at {player_chips.total}")
def play_again():
global player_name
global playing
while True:
replay = input(f"{player_name}, would you like to play another round?: ").upper()
if replay[0] == 'Y':
return True
elif replay[0] == 'N':
print(f"\nThanks for playing - you leave the table with {player_chips.total} chips.")
break
else:
print("Sorry, I don't understand what you are saying, do you want to play the next round, or not? Y or N!: ")
continue
def total():
global player_name
while True:
try:
total = int(input(f'Hello {player_name}, how many chips will you be using this game?: '))
except ValueError:
print('\nSorry, the number of chips must be a number!')
else:
return total
print(f"\nWelcome to the table - you currently have {total} chips to play with.")
def hit(deck,hand):
#run the add card function within the Hand Class with the card argument being generated by the deal function within the Deck Class.
hand.add_card(deck.deal())
hand.adjust_for_ace()
def hit_or_stand(deck,hand):
global player_name
global playing
while True:
response = input(f"{player_name}, Would you like to hit or stand?: ")
if response[0].upper() == 'H':
hit(deck,hand)
elif response[0].upper() == 'S':
print(f"{player_name} stands. It is the Dealer's turn")
playing = False
else:
print("\nI can't understand what you are saying - are you hitting or standing?!")
continue
break
def show_some(player,dealer):
print("\nDealer's Hand:")
print("<card hidden>")
print(dealer.cards[1])
print("\nPlayer's Hand: ",*player.cards, sep='\n')
print("Value of your cards: ",player.value)
def show_all(player,dealer):
print("\nDealer's Hand: ",*dealer.cards, sep='\n')
print("Dealer's Hand = ",dealer.value)
print("\nPlayer's Hand: ",*player.cards, sep='\n')
print("Player's Hand = ",player.value)
def player_busts(player,dealer,chips):
global player_name
print(f"{player_name} busts!")
chips.lose_bet()
def player_wins(player,dealer,chips):
global player_name
print(f"{player_name} wins the round!")
chips.win_bet()
def dealer_busts(player,dealer,chips):
print("Dealer busts!")
chips.win_bet()
def dealer_wins(player,dealer,chips):
print("Dealer wins!")
chips.lose_bet()
def push(player,dealer,chips):
print("You have tied with the Dealer! It's a push, your chips have been refunded.")
############################################################################################################################################################
while True:
counter = 0
if counter > 0:
next_round()
elif counter == 0:
introduction()
#Create & shuffle the deck, deal 2 cards to each player.
deck = Deck()
deck.shuffle()
player_hand = Hand()
player_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand = Hand()
dealer_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
#Set up Player's chips
player_chips = Chips(total())
#Prompt the Player for their bet
take_bet(player_chips)
#Show cards (keep one dealer card hidden)
show_some(player_hand,dealer_hand)
while playing == True:
#Prompt for player hit or stand
hit_or_stand(deck,player_hand)
#show cards (keep one dealer card hidden)
show_some(player_hand,dealer_hand)
#if player's hand exceeds 21, player busts - break loop
if player_hand.value > 21:
player_busts(player_hand,dealer_hand,player_chips)
break
#if player hasn't bust, play dealer's hand until dealer reaches 17 or busts.
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck,dealer_hand)
#show all cards
show_all(player_hand,dealer_hand)
#run different winning scenarios
if dealer_hand.value > 21:
dealer_busts(player_hand,dealer_hand,player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand,dealer_hand,player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand,dealer_hand,player_chips)
else:
push(player_hand,dealer_hand,player_chips)
#inform player of their current chip count.
chip_count()
counter += 1
#play another round?
if play_again() == True:
continue
else:
break
You are resetting counter to 0 at the start of every loop.
You probably meant to set it to 0 before the loop started, then have it increase every loop.
Instead of:
while True:
counter = 0
if counter > 0:
try:
counter = 0
while True:
if counter > 0:
The issue in your code is that each time you loop through your While True: loop, you are setting the variable counter back to zero.... So even though you increment counter at the end of your loop, it is then immediately set back to zero as the loop restarts.
A different way to accomplish what you are looking for would be to run your introduction() function just before your While True: loop, and then edit the final lines of your code to call the next_round() function, as such:
if play_again() == True:
next_round()
continue
import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I'm trying to make a very basic slot machine.
My question is: How do I make the generator function repeat 3 times and return 3 outputs, and then how do I make it recognise certain combinations?
Is this possible at all, keeping with my current format?
Also, how could I incorporate arrays into my code?
Thanks
Make the generator return a list or tuple of three values after generating three values, also it would be easier to use random.choice() rather than random.random() . random.choice() randomly selects a element for a list of values/iterable with equal probability for all elements. Example -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
If you want to have different probabilities for different elements, you can keep the current method, just loop over that three times and append to ret like done above and return ret from it.
Then in your win function, keep a dictionary such that the key is the tuple of combination and the value is the amount the user wins, then you can simply use .get() with a default value of 0 , to get how much the user won. Do not pass in generator as an argument. Example -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
Then in your main loop, call this win() function to roll and see how much the user won.
Use the range function to choose 3 times and store it in a list.
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list
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.