import random
print("Welcome to the Dice Game!")
Balance = int(input("How much money would you like to play with?:"))
Dice_again = "yes"
while Dice_again.casefold() == "y" or Dice_again.casefold() == "yes":
Bet = int(input("How much would you like to bet?:"))
if Bet > Balance:
print("Sorry, you dont not have enough funds to bet this much.")
print(f"You have ${Balance}.")
continue
elif Balance == 0:
print("Sorry, you have $0 and cannot play the game anymore.")
break
Betnumber = int(input("What number would you like to bet on?:"))
if Betnumber > 12:
print("You have entered an invalid input.")
continue
Dice1 = random.randint(1,6)
Dice2 = random.randint(1,6)
Balance -= Bet
Numberrolled = (Dice1 + Dice2)
print("Now rolling....")
while Balance >= Bet:
if (Betnumber == 2) and (Numberrolled == 2):
Winning1 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning1}!")
Balance += Winning1
print(f"You now have ${Balance}.")
break
elif (Betnumber == 3) and (Numberrolled == 3):
Winning2 = Bet * 18
print(f"Congratulations! You rolled a 3 and won ${Winning2}!")
Balance += Winning2
print(f"You now have ${Balance}.")
break
elif (Betnumber == 4) and (Numberrolled == 4):
Winning3 = Bet * 12
print(f"Congratulations! You rolled a 4 and won ${Winning3}!")
Balance += Winning3
print(f"You now have ${Balance}.")
break
elif (Betnumber == 5) and (Numberrolled == 5):
Winning4 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning4}!")
Balance += Winning4
print(f"You now have ${Balance}.")
break
elif (Betnumber == 6) and (Numberrolled == 6):
Winning5 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning5}!")
Balance += Winning5
print(f"You now have ${Balance}.")
break
elif (Betnumber == 7) and (Numberrolled == 7):
Winning6 = Bet * 6
print(f"Congratulations! You rolled a 2 and won ${Winning6}!")
Balance += Winning6
print(f"You now have ${Balance}.")
break
elif (Betnumber == 8) and (Numberrolled == 8):
Winning7 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning7}!")
Balance += Winning7
print(f"You now have ${Balance}.")
break
elif (Betnumber == 9) and (Numberrolled == 9):
Winning8 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning8}!")
Balance += Winning8
print(f"You now have ${Balance}.")
break
elif (Betnumber == 10) and (Numberrolled == 10):
Winning9 = Bet * 12
print(f"Congratulations! You rolled a 2 and won ${Winning9}!")
Balance += Winning9
print(f"You now have ${Balance}.")
break
elif (Betnumber == 11) and (Numberrolled == 11):
Winning10 = Bet * 18
print(f"Congratulations! You rolled a 2 and won ${Winning10}!")
Balance += Winning10
print(f"You now have ${Balance}.")
break
elif (Betnumber == 12) and (Numberrolled == 12):
Winning11 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning11}!")
Balance += Winning11
print(f"You now have ${Balance}.")
break
else:
print(f"Sorry, but you rolled a {Numberrolled}.")
print(f"You now have ${Balance}.")
break
Dice_again = input("Would you like to play again (N/Y)?")
if Dice_again.casefold() == "yes" or Dice_again.casefold() == "y":
continue
elif Dice_again.casefold() == "no" or Dice_again.casefold() == "n":
print(f"You have stopped the game with ${Balance} in your hand.")
break
else:
print("You have entered an invalid input.")
break
Whenever I run the program and the bet value equals the balance, it doesn't display the else statement I have it set to display but instead, it goes down the program and outputs the other information that is supposed to be outputted later on.
Here's an example of what happens when the bet doesn't equal the balance and when they equal each other:
Welcome to the Dice Game!
How much money would you like to play with?:100
How much would you like to bet?:50
What number would you like to bet on?:12
Now rolling....
Sorry, but you rolled a 7.
You now have $50.
Would you like to play again (N/Y)?yes
How much would you like to bet?:50
What number would you like to bet on?:12
Now rolling....
Would you like to play again (N/Y)?
Like people said in comments. The issue you have is this
Balance -= Bet
...
while Balance >= Bet:
# do rest
So when you have Bet equal to Balance then it subtracts it and the condition is no longer valid. What you want is to move subtraction inside of while loop
...
while Balance >= Bet:
Balance -= Bet
# do rest
Another issue I notices is that you have two whiles loops, and second loop will always runs once. So there is no reason to even have it, it would make sense to replace it with if statement and remove break inside of if statements that are inside of this while loop.
Edited:
Answer to Author's question in the comment. You replace make second while an if:
if Balance >= Bet:
Balance -= Bet
if (Betnumber == 2) and (Numberrolled == 2):
Winning1 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning1}!")
Balance += Winning1
print(f"You now have ${Balance}.")
elif (Betnumber == 3) and (Numberrolled == 3):
Winning2 = Bet * 18
print(f"Congratulations! You rolled a 3 and won ${Winning2}!")
Balance += Winning2
print(f"You now have ${Balance}.")
elif (Betnumber == 4) and (Numberrolled == 4):
Winning3 = Bet * 12
print(f"Congratulations! You rolled a 4 and won ${Winning3}!")
Balance += Winning3
print(f"You now have ${Balance}.")
elif (Betnumber == 5) and (Numberrolled == 5):
Winning4 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning4}!")
Balance += Winning4
print(f"You now have ${Balance}.")
elif (Betnumber == 6) and (Numberrolled == 6):
Winning5 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning5}!")
Balance += Winning5
print(f"You now have ${Balance}.")
elif (Betnumber == 7) and (Numberrolled == 7):
Winning6 = Bet * 6
print(f"Congratulations! You rolled a 2 and won ${Winning6}!")
Balance += Winning6
print(f"You now have ${Balance}.")
break
elif (Betnumber == 8) and (Numberrolled == 8):
Winning7 = Bet * 7
print(f"Congratulations! You rolled a 2 and won ${Winning7}!")
Balance += Winning7
print(f"You now have ${Balance}.")
elif (Betnumber == 9) and (Numberrolled == 9):
Winning8 = Bet * 9
print(f"Congratulations! You rolled a 2 and won ${Winning8}!")
Balance += Winning8
print(f"You now have ${Balance}.")
break
elif (Betnumber == 10) and (Numberrolled == 10):
Winning9 = Bet * 12
print(f"Congratulations! You rolled a 2 and won ${Winning9}!")
Balance += Winning9
print(f"You now have ${Balance}.")
elif (Betnumber == 11) and (Numberrolled == 11):
Winning10 = Bet * 18
print(f"Congratulations! You rolled a 2 and won ${Winning10}!")
Balance += Winning10
print(f"You now have ${Balance}.")
break
elif (Betnumber == 12) and (Numberrolled == 12):
Winning11 = Bet * 36
print(f"Congratulations! You rolled a 2 and won ${Winning11}!")
Balance += Winning11
print(f"You now have ${Balance}.")
else:
print(f"Sorry, but you rolled a {Numberrolled}.")
print(f"You now have ${Balance}.")
Related
I have to create a blackjack game in python in which the user inputs the number of decks that are being used and the amount of money the user wants to bet. The rules are: o The player places his bet (should be read from the keyboard).
o The dealer and player are dealt two cards (one card of the dealer should be hidden).
o If the player has 21 he wins his bet; else if the dealer has 21 then the dealer wins and the player loses his bet.
o The player can only select to draw a new card (hit) or pass. Repeat until the player passes or busts. If the player goes above 21 then he busts.
o Then the dealer draws cards (automatically) until he either busts or reaches 17 or higher.
o Values of cards: A= 1 or 11 (the highest that does not bust you) and J=Q=K=10
o Note: in blackjack there are more actions: insurance, double, split; those are not required to be implemented as they would make the code you have to produce much, much longer and harder
I will show you my code below when I tried to run it, it said that the name "total" is not defined on the function game, but earlier on I have already defined it. I don't know how can i fix it.
import random
N=int(input("Please enter number of decks of cards used: "))
deck= [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
wins=0
losses=0
chip_pool = 100
bet = 1
def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card=deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def play_again():
again = input("Do you want to play again? (Y/N) : ").lower()
if again == "y":
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
game()
else:
print("Thank you for playing.")
exit()
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
def hit(hand):
card = deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def print_results(dealer_hand, player_hand):
clear()
print("\n WELCOME TO BLACKJACK!\n")
print("The dealer has a " + str(dealer_hand) + "for a total of" + str(total(dealer_hand)))
print("You have a" + str(player_hand) + "for a total of" + str(total(player_hand)))
def blackjack(dealer_hand, player_hand):
global wins
global losses
if total(player_hand) == 21:
print_results(player_hand,dealer_hand)
print("Congratulations! You got a blackjack.\n")
wins = wins + 1
play_again()
elif total(dealer_hand) == 21:
print_results(dealer_hand,player_hand)
print("Sorry you lose. The dealer got a blackjack.\n")
chip_pool -= bet
loses = loses + 1
play_again()
def score(dealer_hand,player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print("Congratulations! You got a blackjack1\n")
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print("Sorry you lose. The dealer go a blackjack\n")
elif total(player_hand) > 21:
print_results(dealer_hand, player_hand)
print("Sorry, you busted. You lose.\n")
elif total(dealer_hand) > 21:
print_results(dealer_hand, player_hand)
print("Dealer busts. You win!\n")
chip_pool += bet
elif total(player_hand) < total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Sorry, the score is not higher than the dealer. You lose.\n")
chip_pool -= bet
elif total(player_hand) > total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Congratulations. Your score is higher than the dealer. You win.\n")
chip_pool += bet
elif total(player_hand) == total(dealer_hand):
print_results(playe_hand, dealer_hand)
print("There is a tie. In a tie dealer always wins!\n")
chip_pool -= bet
def make_bet():
global bet
bet = 0
print("What amount of chips would you like to bet? ")
while bet == 0:
bet_comp = input()
bet_comp = int(bet_comp)
if bet_comp >= 1 and bet_comp <= chip_pool:
bet = bet_comp
else:
print("Invalid bet, you only have" + str(chip_pool) + "remaining")
def game():
choice = 0
print("Welcome to Blackjack!\n")
dealer_hand = deal(deck)
player_hand = deal(deck)
print("The dealer is showing a " +str(dealer_hand[0]))
make_bet()
print("You have a " + str(player_hand))
blackjack(dealer_hand, player_hand)
quit = False
while not quit:
choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
if choice == 'h':
hit(player_hand)
print(player_hand)
if total(player_hand) > 21:
print("You busted")
chip_pool -= bet
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
print(dealer_hand)
if total(dealer_hand) > 21:
print("Dealer busts. You win!")
chip_pool += bet
play_again()
score(dealer_hand, playe_hand)
play_again()
elif choice == "q" :
print("Thank you for playing. Hope you enjoyed!")
quit = True
exit()
if __name__ == "__main__":
game()
You have not defined the function total that you call. Try adding this to your code
def total(array):
total = 0
for card in array:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
However I see some more issues in your code that will need fixing later on! Stand or Quit do nothing currently, and on busting there is an exception thrown since chip_pool never had a value assigned to it
EDIT 1:
You defined a function
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
Similar to what I suggested. Maybe it was just a typo but you need to do the following
Rename the function from total_hand to total OR call total_hand
Change the definition from total_hand() to total_hand(hand)
I am making an investment game in which the Gold and Bitcoin prices go down and up day by day but here I am getting a problem how can I make this code easy so I can add any other crypto and share with just 2-3 lines of code but now I have to code whole if-else statement to do this
Can I use Classes and objects but how
This is the code How can I Improve
goldPrice = 63 # $ dollars per gram
bitcoinPrice = 34000 # $ dollars per bitcoin
day = 1 # life start with this day
myGold = 0 # in Grams
myBitcoin = 0.0 # in bitcoin
def newspaper():
print("GOLD: " + str(goldPrice) + '$ per gram')
print("BITCOIN: " + str(bitcoinPrice) + "$")
print("An investment in knowledge pays the best interest.")
def invest():
global balance, myGold, myBitcoin
print("====Which Thing you want to Buy====")
print("1. Gold")
print("2. Bitcoin")
print("3. Nothing, Go Back")
investInputKey = int(input())
if investInputKey == 1:
print("Gold: " + str(goldPrice) + ' per gram' +'\n')
print("1. Buy")
print("2. Sell")
print("3. Exit")
goldInput = int(input())
if goldInput == 1:
print("Enter Amount in Grams: ")
howMuch = int(input())
totalGoldBuy = howMuch * goldPrice
print(totalGoldBuy)
if totalGoldBuy > balance:
print("Insufficient Balance!")
else:
print("Thank you! Have a Nice Day")
balance -= totalGoldBuy
myGold += howMuch
elif goldInput == 2:
print("Enter Amount in Grams: ")
howMuch = int(input())
if howMuch > myGold:
print("Insufficient Gold!")
else:
print("Thank you! Have a Nice Day")
myGold -= howMuch
newGold = howMuch * goldPrice
balance += newGold
elif goldInput == 3:
print("Thank you! Have a Nice Day")
else:
print("Wrong Input!")
elif investInputKey == 2:
print("Bitcoin: " + str(bitcoinPrice) +'\n')
print("1. Buy")
print("2. Sell")
print("3. Exit")
bitcoinInput = int(input())
if bitcoinInput == 1:
print("Enter Bitcoin Amount in Dollars")
howMuch = int(input())
if howMuch > balance:
print("Insufficient Balance!")
elif howMuch > 500:
myBitcoin = howMuch / bitcoinPrice
balance -= howMuch
else:
print("You can only buy above 500$")
elif bitcoinInput == 2:
print("Enter Bitcoin Amount in Dollars")
howMuch = int(input())
if howMuch > (myBitcoin * bitcoinPrice):
print("Insufficient Bitcoin");
elif howMuch < 500:
print("You can only sale above 500 Dollars")
else:
myBitcoin -= howMuch / bitcoinPrice
balance += howMuch
elif goldInput == 3:
print("Thank you! Have a Nice Day")
else:
print("Wrong Input!")
elif investInputKey == 3:
print("Thank you! Have a Nice Day");
else:
print("Wrong Input!")
while True:
print("========HOME========" + '\n')
print("====Day-" + str(day) + "====")
print("====Balance-" + str(balance) + "$ ====")
print('\n')
print("1. Newspaper")
print("2. Invest")
print("3. My Portfolio")
print("4. Next Day")
print("5. Exit")
inputKey = int(input())
if inputKey == 1:
newspaper()
elif inputKey == 2:
invest()
elif inputKey == 3:
print("========Portfolio========" + '\n')
print("Gold: " + str(myGold) + " gram")
print("Bitcoin: " + str(myBitcoin))
elif inputKey == 4:
day += 1
print("This is day " + str(day))
# Change price of gold and bitcoin
elif inputKey == 5:
# Add sure you want to exit
break
else:
print("Wrong Input! Try Again")
Help me,
Thank You
I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
Hi all programming masters! Im working on a python guessing game and want to change the format of my print to file from "name: win 0: loss 0: guess 0", to "Name | Win or loss (not both) | number of guesses". Im not sure how to make it print the win OR loss, do i need another if statement to print to the txt file?
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
guesses = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
elif diceRoll != 1 and diceRoll != 2 and diceRoll != 3 and diceRoll != 4 and diceRoll != 5 and
diceRoll != 6:
print("Invalid input!")
number = random.randint(1, 3)
chances = 0
print("Guess a number between 1 and 100:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
guesses = guesses + 1
break
elif guess < number:
print("Your guess was too low")
guesses = guesses + 1
else:
print("Your guess was too high")
guesses = guesses + 1
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
stat = open("Statistics.txt", "a")
stat.write(name + ":" + " win: "+str(win) + " loss: " +str(loss) +" guesses: "+str(guesses)),
stat.close()
You can solve the critical part using the ternary statement, an "if-then-else" expression, like this:
result = "Win" if win == 1 else "Loss"
stat.write((name + ":" + result + " guesses: "+str(guesses))
Beyond this, I strongly recommend that you look up "Python output format", so you can improve your range of expression. You won't have to keep doing string construction for your output statements.
I am trying to code player and mob attacks for a text based RPG game I am making, I have randomint set up for player and mob hitchance and crit chance but I can't figure out how to get a new integer for them every time I restart the loop, it uses the same integer it got the first time it entered the loop.
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
roll = roll_dice()
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
while True:
roll.mobcrit
roll.mobhitchance
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
if roll.mobcrit <= 5 and roll.mobhitchance >= 25:
print("\nOrc crit for",str(orcMob.atk * 2),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk * 2
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance >= 25:
print("\nOrc hit for",str(orcMob.atk),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk
print("Your HP",str(userPlayer.hp))
break
elif roll.mobcrit <= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
elif orcMob.hp >= 1:
continue
The problem is with your roll_dice class. You have the values defined when the class initializes, but then you never update them again. Therefore self.escape or self.spawn will always be the same value after the program starts. The easiest way to solve your problem without rewriting much would be to make another instance of roll_dice() every time you want to roll the dice. Something like:
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
# roll = roll_dice() # you don't need to make an instance here
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll = roll_dice() # make a new instance with each loop
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
Use functions like
import random
for x in range(10):
print random.randint(1,101)
use a array around for a max 100 people and generate random digits to add in your code.
You can also use a array to create random umber structure and then use the numbers to be shuffled and added as you create them
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items