Roulette program will not recognize correct guess. Why? - python-2.7

The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets == True:
bets = True
return bets
else:
print "You bet on: ", bets
print "Better luck next time."
bets = False
return bets
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
self.spin(bets)
# payout for bets
if bets == True:
print "You win $", bet_amount*35
self.wallet += bet_amount*35
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()

Your main error was this:
# start spin
self.spin(bets)
# payout for bets
It should read:
#start spin
bets = self.spin(bets)
# payount bets
the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets:
return True
else:
print "You bet on: ", bets
print "Better luck next time."
return False
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
did_win = self.spin(bets)
# payout for bets
if did_win == True:
ammount = bet_amount*35
self.wallet += ammount
print "You win $", ammount
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()

Related

Python Pokemon Battle - pokemon attack twice in one turn

I'm sorta new to python. I'm trying to make a pokemon battle. But i can't seem to figure out why whenever you attack and the enemy attacks, they attack twice. It should work like this:
*battle starts
*you attack enemy
*enemy attacks you
*one of you faints
import time
import random
# pokemon beginning battle
print "mewtwo has appeared"
time.sleep(1)
print "lvl 70"
time.sleep(0.5)
print "HP 128"
print " \n "
# Mewtwo stats
mewtwo_HP = 128
mewtwo_atk = 20
mewtwo_atk2 = 45
move = random.randrange(-1, 1)
# Lapras stats
attack1 = ['hydro pump']
attack2 = ['ice beam']
lapras_HP = 100
attack1range = random.randrange(15,32)
attack2range = random.randrange(20, 25)
run = "you can't run away!"
pokemon = "Lapras"
# Lapras's turn
while True:
print "Lapras's moves:"
print "[ice beam][hydro pump]"
B = raw_input('> ').strip()
Battle = B
if Battle in attack1:
print "Lapras used Hydro pump!"
mewtwo_HP -= attack1range
time.sleep(0.5)
print "Mewtwo has", + mewtwo_HP, 'HP!'
if Battle in attack2:
print "Lapras used Ice beam!"
mewtwo_HP -= attack2range
time.sleep(0.5)
print "Mewtwo has", + mewtwo_HP, 'HP!'
# Mewtwo's turn
if move == 0:
lapras_HP -= random.randrange(21,27)
time.sleep(1)
print "Mewtwo used Psystrike!"
time.sleep(0.5)
print "Lapras has", + lapras_HP,'HP!'
else:
lapras_HP -= random.randrange(19, 35)
print "Mewtwo used Psywave!"
time.sleep(0.5)
print "Lapras has", + lapras_HP,'HP!'
if mewtwo_HP <= 0:
print "Mewtwo fainted!"
if lapras_HP <= 0:
print "Lapras fainted!"
print "you lose!"
And if you have any suggestions to make my code better that would be great (:

Increasing money when the dealer or player win the game

I am a beginner I am trying to add money if I wont to the money that I typed in the very start of the game if I won the money will be added to the input money that I had it adding but repeating its looping example I typed 500 then I won 200 price It will display 700 but if I won again and the price 300 it will show 800 and forgetting about what I won before
below is the code I will really appreciate your hep thank you
import random, sys
from random import shuffle
from _ast import Num
# define global variables for the cards
suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}
playing = True
global score
score=0
class Card:
#When you create an instance of Card, you pass it a suit ("C", "D", "H", or "S") and a "pip" (2, 3, 4, 5, 6, 7, 8, 9, 10 J, Q, K, A).
#These values should be stored as instance variables for the new card object.
#I recommend you also have an instance variable "value" that stores the point value of the card.
#It should have an __str__ method that lets you print an individual card (such as "3S" for three of spades).
#Note that the __str__ method for Decks should take advantage of the __str__ method for Cards.
def __init__(self, suit, pip):
self.suit = suit
self.pip = pip
self.value = pipValues.get(pip)
def __str__(self):
return str(self.pip) + " of " + str(self.suit)
def __repr__(self):
return self.__str__()
class Player:
#When you create an instance of Player, it should have an instance variable "hand" that's set to an empty list,
#and an instance variable "handTotal" that's set to zero. These instance variables will be modified
#by Deck's "dealOne()" method.
#It should have an __str__ method that lets you print out a Player's hand.
def __init__(self, isDealer):
self.hand = []
self.isDealer = isDealer
self.name = "Dealer" if self.isDealer else "You"
self.other = "Dealer" if not self.isDealer else "You"
self.has = "has" if self.isDealer else "have"
def __str__(self):
return ", ".join(map(str, self.hand))
def __repr__(self):
return self.__str__()
def discardHand(self):
self.hand = []
#property
def handTotal(self):
while sum(card.value for card in self.hand) > 21 and \
any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
for card in self.hand:
if card.pip == 'Ace' and card.value == 11:
card.value = 1
break
return sum(card.value for card in self.hand)
def blackjack(self):
print ("%s %s %s for a total of 21" %
(self.name, self.has, str(self)))
print ("%s %s a Blackjack! %s win%s!" %
(self.name, self.has, self.name, "s" if self.isDealer else ""))
print ("Thanks for playing. Come back again soon! ")
#chips=chips+(bet*500)
score+1
return message()
def bust(self):
print ("%s hold%s %s for a total of %s" %
(self.name, "s" if self.isDealer else "", str(self), str(self.handTotal)))
print ("%s Bust%s! %s Win%s!" %
(self.name, "s" if self.isDealer else "", self.other, "s" if not self.isDealer else ""))
print ("Thanks for Playing! Come Back Soon!")
# chips=chips-2
return message()
class Deck:
#When you create an instance of Deck, it should add 52 Card objects to an instance variable "cardList".
#It should have a shuffle() method that rearranges the cards in cardList. You can do this easily by importing the
#"random" package into Python, and using the random.shuffle() method. random.shuffle(myList) rearranges the
#elements of the list "myList" into a random order.
#It should have a dealOne() method that removes the first card from your deck's cardList, and appends it to the
#hand of a specified player.
#It should have an __str__ method that lets you print out the entire deck for debugging purposes.
freshDeck = []
for i in range(len(suits)):
for j in range(len(pip)):
freshDeck.append(Card(suits[i], pip[j]))
def __init__(self):
self.cardList = self.freshDeck[:]
def shuffle(self):
random. shuffle (self.cardList)
def dealOne(self, player):
if len(self.cardList) < 4:
print("Out of cards... shuffling a new deck...")
exit
#self.cardList = self.freshDeck[:]
#self.shuffle()
(player.hand).append(self.cardList[0])
del self.cardList[0]
#print(self.cardList)
shuffle(self.cardList)
return self.cardList
def __str__(self):
printString = ""
for i in range(len(self.cardList)):
if i % 13 == 0:
printString += "\n \t"
printString += str(self.cardList[i]) + " "
else:
printString += str(self.cardList[i]) + " "
printString += "\n"
return printString
def showHands(player, opponent):
print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
print ('You show ' + str(player))
def turn(deck, player, other):
#First, check scores to see if either player has a blackjack:
if player.handTotal == 21:
return player.blackjack()
if other.handTotal == 21:
return other.blackjack()
#See if the dealer less 16
hitOrStand = 0
while hitOrStand != 2:
print (player.name + ' hold%s ' % ("s" if player.isDealer else "") + str(player) + ' for a total of ' + str(player.handTotal) + '\n')
if player.isDealer:
if player.handTotal < 16:
hitOrStand = 1
if player.handTotal >= other.handTotal:
hitOrStand = 2
else:
hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
while hitOrStand != 1 and hitOrStand != 2:
try:
hitOrStand = int(hitOrStand)
break
except ValueError:
print ("Enter a valid integer \n")
hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
print()
if hitOrStand == 1:
print('Card dealt: ' + str(deck.cardList[0]) + '\n')
deck.dealOne(player)
if player.handTotal == 21:
return player.blackjack()
if player.handTotal > 21:
return player.bust()
#if player.handTotal <16 :
#return player.bust()
if hitOrStand == 2:
if player.isDealer:
print ("Dealer stands at " + str(player.handTotal))
global price
price=bet*500*2
print (price )
print ("Dealer Wins!")
return message()
else:
print (player.name + ' stand at: ' + str(player.handTotal))
print()
print ("Now Dealer's Turn\n")
def message():
global playing
again = raw_input("Do you want to play again? (Y/N) : ")
if again.lower() == "n":
print("\n\n-------Thank you for playing!--------\n\n")
playing = False
return True
#who won
def betValidation():
global number
number=input("Enter amount: ")
number
if (number<5000):
print "Minimum amount is 5000!!! "
exit()
elif (number > 50000):
print "You Exceeding the Maximum Amount...."
exit()
elif (number==5000 , number<=50000):
if number%500==0:
print ""
else:
print "Invalid"
exit()
def main():
cardDeck = Deck()
global bet
bet1=betValidation()
while playing:
global chips
print "Score:",score
chips=number/500
print "You have", chips ,"chips!"
betchips=chips/2
global bet
bet=input("How much would you like to bet: ")
if(bet==0):
print "Invalid"
elif (bet>=betchips):
if bet%1==0:
player = Player(isDealer=False)
opponent = Player(isDealer=True)
player.discardHand()
opponent.discardHand()
#give each player 2 cards, alternating
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
#show 1 faceup card for each player
showHands(player,opponent)
#start playing
if turn(cardDeck,player, opponent):
continue
turn(cardDeck, opponent, player)
main()
I imagine your problem lies in the function blackjack() but you haven't posted that.

Not understanding the While(True) loop - Python 2.7

Having a hard time figuring out how the while(True) function is supposed to be fitted in the code. Also no idea if that is the right thing to use as I am trying to loop the game until the computer or the user hits the desired amount of points ( which the user inputs as rounds in the beginning)
import random
def main():
print
print "----------------------------------"
print "Welcome to Rock, Paper, Sciccors! "
print "----------------------------------"
rounds = input("How many points to win?: ")
user_choice = input("Choose Rock = 1 , Paper = 2 or Sciccors = 3: ")
user_score = 0
computer_score = 0
if user_choice == 1:
print "You chose Rock"
elif user_choice == 2:
print "You chose Paper"
elif user_choice == 3:
print "You chose Sciccors"
else:
print " Wrong! Choose 1, 2 or 3!"
computer_choice = random.randrange(1, 4)
if computer_choice == 1:
print "Computer chose Rock"
elif computer_choice == 2:
print "Computer chose Paper"
elif computer_choice == 3:
print "Computer chose Sciccors"
def checkResults(computer_choice, user_choice):
checkResults = computer_choice - user_choice
if computer_choice - user_choice == 0:
print("Draw!")
user_score += 1
computer_score += 1
elif computer_choice - user_choice == 1 or computer_choice - user_choice == -2:
print("Computer wins")
computer_score += 1
elif computer_choice - user_choice == -1 or computer_choice - user_choice == 2:
print("You win!")
user_score += 1
print (" Computer {} , You {}" .format(computer_score, user_score))
while(True):
if computer_score == rounds or user_score == rounds:
main()
else:
break
You can make this a bit shorter:
while computer_score == rounds or user_score == rounds:
' Your code returning computer_score and user_score
Basically a while True is an infinite loop that can only be ended using a break statement or via keyboard interrupt.
while True: is an infinite loop that can only be stopped via the command break. In your example, you have created a loop that will infinitely run the main() method (which you defined earlier, by saying def main():). The only time the loop will end is if you kill the process (i.e. using task manager on Windows), or if computer_score and user_score both become unequal to rounds (which is what your else statement is implying on the second to last line). When this happens, the program calls break which forcibly ends the loop immediately and moves on... to the end of the file (which then ends the program).
It should be noted that using a while True ... break loop is sometimes frowned upon by programmers, because it is not seen as "elegant". It is totally fine code to do, but another way to re-write the last few lines is the following:
while computer_score==rounds or user_score==rounds:
main()
This achieves the same result by running the while loop until computer_score and user_score both do not equal rounds. At that point, the while loop ends itself cleanly and ends the program by getting to the end of the file.

How to run the code from start after calculation?

What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break

Using a dictionary to choose scenes in a game, but it's not playing the correct scene. Why?

At the start, if a random integer = 1, it will play a random event. The random event should be selected (also randomly) from a dictionary containing each scene name. Instead, it doesn't try to access the other scenes. It only runs each method(function?) in the order written. What am I doing wrong? Is this a bad way to go about this?
I'm still learning, so any pointers are appreciated!
from random import randint
from time import sleep
class RandomEvent(object):
def __init__(self, wallet):
self.wallet = wallet
def old_man(self):
#insert art
print "\nExcuse me, I have an unusual request."
print "My horoscope tells me it's my lucky day,"
print "but I don't have any money."
print "\nIf you'll let me borrow some money, I"
print "promise to give you half of all the winnings."
print "Do we have a deal?"
give_money = raw_input("(y)es or (n)o? ")
if give_money.lower() == "y":
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
if how_much <= self.wallet:
how_much *= randint(2,3)
print "Haha! I won $%d! Here's your share of the money, kiddo." % (how_much*2)
self.wallet += how_much
else:
print "Eh, kids these days... no faith in their elders... (grumble grumble)..."
sleep(2)
print "\nA few moments later you see the old man hit the jackpot at a slot machine."
return self.wallet
def robber(self):
#insert art
print "\nPsssst! Hey, you!"
#sleep(1)
print "\nYou glance down to see a knife discreetly placed"
print "to your stomach."
#sleep(1)
print "\nHand over all your cash. No funny business."
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
lie_success = randint(1,3)
if how_much == self.wallet:
self.wallet = 0
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking all your money with him."
if how_much != self.wallet and lie_success == 1:
self.wallet -= how_much
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking your money with him."
else:
print "\nYou think you're a wise guy, eh?"
sleep(2)
print "\nYou are dead. GAME OVER"
sleep(2)
exit()
return self.wallet
def pretty_woman(self):
pass
###----------------------GAME CODE BELOW---------------
funds = 500
encounter = 1
while True:
if encounter == randint(1, 1): # 1,1 FOR TESTING
story = RandomEvent(funds)
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
funds = scene_list[2] #randint(1,3)] FOR TESTING
else:
print "\n\n\nWelcome to Dreams Casino."
print "Where would you like to go?"
print "(1) Slot Machines"
print "(2) Roulette Table"
print "(3) Leave the Casino"
print "\nFunds: $", funds
game_choice = int(raw_input("> "))
You're calling the functions when creating your dictionary:
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
Since you want scene_list[1] to refer to your function, pass the function:
scene_list = {1: story.old_man, 2: story.robber, 3: story.pretty_woman}