How can I short this code with class and object - python

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

Related

Python Score Issues with Money in Negatives

I have game I'm making. Have a question. My current code is this:
import random
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
bankbalance = 100
def main():
global bankbalance
print()
print("These cards are open on the table:")
print()
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = input("Enter your bet: ")
playerinput = int(playerinput)
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print("The card you drew was", (dealercard), "!")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance = bankbalance + playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit
elif playerinput > (bankbalance):
print("You cannot bet more than you have!")
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit
elif bankbalance == (0):
print("Oh no! You have no more money to bid.")
exit
else:
print("You lost!")
bankbalance = bankbalance - playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit
main()
The problem is that you can have negative amount of money. How do I fix this? I've tried this:
elif bankbalance == (0):
print("Oh no! You have no more money to bid.")
exit
But that doesn't seem to work either. Any answers? I've tried to fix that issue, but my console doesn't follow it. It just says "You currently have $ 0".
You need to check if balance is equal to 0 whenever call your function. So, before proceeding any further, you need to add that if statement under global bankbalance:
import random
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
bankbalance = 100
def main():
global bankbalance
if bankbalance == 0:
print("Oh no! You have no more money to bid.")
return
print()
print("These cards are open on the table:")
print()
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = input("Enter your bet: ")
playerinput = int(playerinput)
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print("The card you drew was", (dealercard), "!")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance = bankbalance + playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
return
elif playerinput > (bankbalance):
print("You cannot bet more than you have!")
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
return
else:
print("You lost!")
bankbalance = bankbalance - playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
return
main()
Result when you reach 0 bank balance:
...
First card:
2
Second card:
2
Enter your bet: 100
The card you drew was 3 !
You lost!
You currently have $ 0
Would you like to play again y/n: y
Oh no! You have no more money to bid.
import random
print("\n\tWelcome to Python Acey Ducey Card Game\t\n")
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
bankbalance = 100
def main():
global bankbalance
print("\nThese cards are open on the table:\n")
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = int(input("Enter your bet: "))
if playerinput > (bankbalance):
print("You cannot bet more than you have!")
play_again()
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print(f"The card you drew was {dealercard} !")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance += playerinput
print(f"You currently have $ {bankbalance}")
play_again()
elif bankbalance <= 0:
print("Oh no! You have no more money to bid.")
exit()
else:
print("You lost!")
bankbalance -= playerinput
print(f"You currently have $ {bankbalance}")
play_again()
def play_again():
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit()
main()
I rewrite your code a little bit.
import random
bank_balance = 100
play_again = True
def random_card() -> int:
return random.randint(1,13)
def set_bet():
try:
bet = int(input("Enter your bet: "))
except ValueError:
bet = 0
return bet
def play():
global bank_balance
print("These cards are open on the table:")
first_card = random_card()
second_card = random_card()
print(f"First card: {first_card}")
print(f"Second card: {second_card}")
bet = set_bet()
while (bet < 0) or (bet > bank_balance):
if bet > bank_balance:
print("You cannot bet more than you have!")
elif bet < 0:
print("You cannot bet <= 0 ")
bet = set_bet()
player_card = random_card()
print(f"The card you drew was {player_card}!")
if sorted([first_card, second_card, player_card])[1] == player_card:
bank_balance += bet
print('you win!')
else:
bank_balance -= bet
print('you lost!')
def main():
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer)"
" deals two cards faced up and you have an option to bet or not bet"
" depending on whether or not you feel the card will have a value"
" between the first two. If you do not want to bet, enter a $0 bet.")
global play_again, bank_balance
while play_again:
print(f"You currently have $ {bank_balance}")
play()
if bank_balance <= 0:
print("Oh no! You have no more money to bid.")
play_again = False
else:
play_again = input("Would you like to play again y/n: ") == 'y'
main()

Program not performing the elif statement when balance equals bet

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}.")

Display error message when negative number entered. Should I use try statement and how?

I am new to Python. I created a program that calculates shipping and total cost. I have it loop the user input based on user selecting y or n. I am struggling figuring out how to display a message if the user enters a negative number. I tried the if statement but the console error message displays. I want it to just display the error message I supplied. I believe I need to add a try statement?
print ("Shipping Calculator")
answer = "y"
while answer == "y":
cost = float(input("Cost of item ordered: "))
if cost <0:
print ("You must enter a positive number. Please try again.")
elif cost < 30:
shipping = 5.95
elif cost > 30 and cost <= 49.99:
shipping = 7.95
elif cost >= 50 and cost <= 74.99:
shipping = 9.95
else:
print ("Shipping is free")
totalcost = (cost + shipping)
print ("Shipping cost: ", shipping)
print ("Total cost: ", totalcost)
answer = input("\nContinue (y/n)?: ")
else:
print ("Bye!")
Try adding a continue.
With the continue statement you are going to go to the next loop iteration directly
print ("Shipping Calculator")
answer = "y"
while answer == "y":
cost = float(input("Cost of item ordered: "))
if cost <0:
print ("You must enter a positive number. Please try again.")
continue
elif cost < 30:
shipping = 5.95
elif cost > 30 and cost <= 49.99:
shipping = 7.95
elif cost >= 50 and cost <= 74.99:
shipping = 9.95
else:
print ("Shipping is free")
totalcost = (cost + shipping)
print ("Shipping cost: ", shipping)
print ("Total cost: ", totalcost)
answer = input("\nContinue (y/n)?: ")
else:
print ("Bye!")
You can also control that cost should be a number and possitive with this:
print ("Shipping Calculator")
answer = "y"
while answer == "y":
cost_string = input("Cost of item ordered: ")
if not cost_string.isdigit():
print ("You must enter a positive number. Please try again.")
continue
cost = float(cost_string)
if cost < 30:
shipping = 5.95
elif cost > 30 and cost <= 49.99:
shipping = 7.95
elif cost >= 50 and cost <= 74.99:
shipping = 9.95
else:
print ("Shipping is free")
totalcost = (cost + shipping)
print ("Shipping cost: ", shipping)
print ("Total cost: ", totalcost)
answer = input("\nContinue (y/n)?: ")
else:
print ("Bye!")

List Index Out of Range, Why Is This Happening?

Here's the error I'm getting:
Traceback (most recent call last):
File "E:\python\cloud.py", line 34, in <module>
c = Cloud()
File "E:\python\cloud.py", line 18, in __init__
self.cweaponAttack = self.weaponAttack[0]
IndexError: list index out of range
I'm having trouble with my code and I have checked for spelling errors everywhere but I haven't found any.
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
self.sp = 1
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.cweapon = self.weapon
self.money = 10000
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
addaps = self.cweaponAttack * self.attackPower
self.dmg = self.cweaponAttack + addaps
self.hp = 100
self.mhp = 100
self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
The lines above is where i'm positive that the error is coming from, but just in case, here's the rest of the code. Warning: It's very long.
import random
import time
import sys
def asky():
ask = input("Would you like to check you player stats and inventory or go to the next battle? Say inventory for inventory or say next for the next battle: ")
if "inventory" in ask:
inventory()
elif "next" in ask:
user()
def Type(t):
t = list(t)
for a in t:
sys.stdout.write(a)
time.sleep(.035)
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
self.sp = 1
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.cweapon = self.weapon
self.money = 10000
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
addaps = self.cweaponAttack * self.attackPower
self.dmg = self.cweaponAttack + addaps
self.hp = 100
self.mhp = 100
self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
class Soldier:
def __init__(self):
dmg = random.randint(5,20)
self.lvl = 0
self.attackPower = dmg
self.hp = 100
self.mhp = 100
self.name = "Soldier"
s = Soldier()
def enemy():
ad = random.randint(0,2)
if ad >= 1: #Attack
Type("Soldier attacks!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
hm = random.randint(0, 2)
if hm == 0:
Type("Miss!")
print("")
elif hm > 0:
crit = random.randint(0,10)
if crit == 0:
print("CRITICAL HIT!")
crithit = int((s.attackPower) * (.5))
c.hp = c.hp - (s.attackPower + crithit)
elif crit >= 1:
c.hp = c.hp - s.attackPower
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
asky()
c.exp = c.exp + 100
else:
user()
elif ad == 0:#Defend
Type("Soldier Defends!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if s.hp == s.mhp:
print("")
elif s.hp > (s.mhp - 15) and s.hp < s.mhp:
add = s.mhp - s.hp
s.hp = add + s.hp
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
elif s.hp < (s.mhp - 15):
s.hp = s.hp + 15
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
asky()
c.exp = c.exp + 100
else:
user()
def user():
User = input("attack or defend? ")
if "attack" in User:#attack
Type("Cloud attacks!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
hm = random.randint(0,4)
if hm == 0:
Type("Miss!")
print("")
elif hm > 0:
crit = random.randint(0,7)
if crit == 0:
print("CRITICAL HIT!")
crithit = int((c.dmg) * (.5))
s.hp = s.hp - (c.dmg + crithit)
elif crit >= 1:
s.hp = s.hp - c.dmg
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
c.exp = c.exp + 100
asky()
else:
enemy()
elif "defend" in User:#defend
Type("Cloud Heals!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp == c.mhp:
Type("You are at the maximum amount of health. Cannot add more health.")
print("")
elif c.hp > (c.mhp - 15) and c.hp < c.mhp:
add = c.mhp - c.hp
c.hp = add + c.hp
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
elif c.hp <= (c.mhp - 15):
c.hp = c.hp + 15
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("Congratulations!")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
c.exp = c.exp + 100
asky()
else:
enemy()
else:
Type("The option you have entered is not in the game database. Please try again")
print("")
user()
def inventory():
if c.exp == c.mexp:
print("LEVEL UP!")
c.exp = 0
adde = int((c.mexp) * (.5))
c.mexp = c.mexp + adde
c.sp = c.sp + 1
c.lvl = c.lvl + 1
if c.lvl > s.lvl:
s.lvl = s.lvl + 1
print("")
print("")
print("Level: ", c.lvl)
print("")
nextlvl = c.lvl + 1
print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
print("")
print("Amount of Skill Points:", c.sp)
print("")
for i in range(0, len(c.weapon)):
print(i)
print("Weapon: ", c.weapon[i])
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for j in range(0, len(c.armor)):
print("Armor: ", c.armor[j])
print("Armor Damage Reduction: ", c.armorReduction[j])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("")
print("Maximum Health: ", c.mhp)
print("")
print("Current Health: ", c.hp)
print("")
dtop = 100 * c.attackPower
print("Attack Power: Adds", dtop, "% of sword damage")
print("")
print("Overall Damage: ", c.dmg)
print("")
print("Your Name: ", c.name)
print("")
print("")
sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), or say, *help* for help: ")
print("")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "weapon" in sn:
weapChange()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
def helpp():
Type("The goal of this game is to fight all the enemies, kill the miniboss, and finally, kill the boss! each time you kill an enemy you gain *crystals*, currency which you can use to buy weapons, armor, and health. You can spend these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to defeat. Once you level up, you gain one skill point. This skill point is then used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack power.")
print("")
continu = input("Say, *back*, to go back to your inventory screen. ")
if "back" in continu:
inventory()
else:
Type("The word you have entered is invalid. Please try again.")
print("")
helpp()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
else:
print("Level: ", c.lvl)
print("")
nextlvl = c.lvl + 1
print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
print("")
print("Amount of Skill Points:", c.sp)
print("")
for i in range(0, len(c.weapon)):
print("Weapon:", c.weapon[i])
print("")
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for i in range(0, len(c.armor)):
print("Armor: ", c.armor[i])
print("")
print("Armor Damage Reduction: ", c.armorReduction[i])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("")
print("Maximum Health: ", c.mhp)
print("")
print("Current Health: ", c.hp)
print("")
dtop = 100 * c.attackPower
print("Attack Power: Adds", dtop, "% of sword damage")
print("")
print("Your Name: ", c.name)
print("")
print("")
sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), say, *weapon* to switch your current weapon, or say, *help* for help: ")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "weapon" in sn:
weapChange()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
def helpp():
Type("The goal of this game is to fight all the enemies, kill the miniboss, and finally, kill the boss! each time you kill an enemy you gain *crystals*, currency which you can use to buy weapons, armor, and health. You can spend these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to defeat. Once you level up, you gain one skill point. This skill point is then used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack power. To switch out your weapons, type in, *weapon*.")
print("")
continu = input("Say, *back*, to go back to your inventory screen. ")
if "back" in continu:
inventory()
else:
Type("The word you have entered is invalid. Please try again.")
print("")
helpp()
helpp()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
def weapChange():
for i in range(0, len(c.weapon)):
print("Weapon:", "To equip", c.weapon[i], ",say", i)
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
weapchoice = input("Enter the weapon ID to the sword you would like to equip, or say, *cancel*, to go back to your inventory. ")
print("")
if "0" in weapchoice:
c.cweapon = c.weapon[0]
c.cweaponAttack = c.weaponAttack[0]
print("Success!", c.weapon[0], "is now equipped!")
inventory()
elif "1" in weapchoice:
c.cweapon = c.weapon[1]
print("Success!", c.weapon[1], "is now equipped!")
inventory()
c.cweaponAttack = c.weaponAttack[1]
elif "2" in weapchoice:
c.cweaponAttack = c.weaponAttack[2]
c.cweapon = c.weapon[2]
print("Success!", c.weapon[2], "is now equipped!")
inventory()
elif "3" in weapchoice:
c.cweaponAttack = c.weaponAttack[3]
c.cweapon = c.weapon[3]
print("Success!", c.weapon[3], "is now equipped!")
inventory()
elif "4" in weapchoice:
c.cweaponAttack = c.weaponAttack[4]
c.cweapon = c.weapon[4]
print("Success!", c.weapon[4], "is now equipped!")
inventory()
elif "5" in weapchoice:
c.cweaponAttack = c.weaponAttack[5]
c.cweapon = c.weapon[5]
print("Success!", c.weapon[5], "is now equipped!")
inventory()
elif "6" in weapchoice:
c.cweaponAttack = c.weaponAttack[6]
c.cweapon = c.weapon[6]
print("Success!", c.weapon[6], "is now equipped!")
inventory()
elif "7" in weapchoice:
c.cweaponAttack = c.weaponAttack[7]
c.cweapon = c.weapon[7]
print("Success!", c.weapon[7], "is now equipped!")
inventory()
elif "8" in weapchoice:
c.cweaponAttack = c.weaponAttack[8]
c.cweapon = c.weapon[8]
print("Success!", c.weapon[8], "is now equipped!")
inventory()
elif "9" in weapchoice:
c.cweaponAttack = c.weaponAttack[9]
c.cweapon = c.weapon[9]
print("Success!", c.weapon[9], "is now equipped!")
inventory()
elif "cancel" in weapchoice:
inventory()
else:
Type("The word or number you have entered is invalid. Please try again.")
print("")
print("")
weapChange()
def skills():
print("")
print("You have", c.sp, "skill points to use.")
print("")
print("Upgrade attack power *press the number 1*")
print("")
print("Upgrade maximum health *press the number 2*")
print("")
skill = input("Enter the number of the skill you wish to upgrade, or say, cancel, to go back to your inventory screen. ")
print("")
if "1" in skill:
sure = input("Are you sure you want to upgrade your character attack power in return for 1 skill point? *yes or no* ")
print("")
if "yes" in sure:
if c.sp == 0:
Type("I'm sorry but you do not have sufficient skill points to upgrade your attack power. ")
print("")
skills()
elif c.sp >= 1:
c.sp = c.sp - 1
c.attackPower = float(c.attackPower + .1)
addsap = int(100 * c.attackPower)
print("Your attack power has been upgraded to deal", addsap, "% more damage")
skills()
else:
Type("How the fuck did you get negative skill points?! ")
print("")
skills()
if "no" in sure:
skills()
elif "2" in skill:
sure = input("Are you sure you want to upgrade your maximum health in return for 1 skill point? *yes or no* ")
print("")
if "yes" in sure:
if c.sp == 0:
Type("I'm sorry but you do not have sufficient skill points to upgrade your maximum health. ")
print("")
skills()
elif c.sp >= 1:
c.sp = c.sp - 1
c.mhp = c.mhp + 30
skills()
else:
Type("How the fuck did you get negative skill points?! ")
print("")
skills()
if "no" in sure:
skills()
elif "cancel" in skill:
inventory()
else:
Type("The word or number you have entered is invalid. Please try again.")
print("")
skills()
def shop():
print("")
Type("Welcome to Andrew's Blacksmith! Here you will find all the weapons, armor, and health you need, to defeat the horrid beast who goes by the name of Murlor! ")
print("")
print("")
print("Who's Murlor? *To ask this question, type in the number 1*")
print("")
print("Can you heal me? *To ask this question, type in the number 2*")
print("")
print("What weapons do you have? *To ask this question, type in the number 3*")
print("")
print("Got any armor? *To ask this question, type in the number 4*")
print("")
ask1 = input("Enter desired number here or say, cancel, to go back to your inventory screen. ")
print("")
if "1" in ask1:
def murlor():
Type("Murlor is a devil-like creature that lives deep among the caves of Bricegate. He has been terrorising the people of this village for centuries.")
print("")
print("")
print("What is Bricegate? *To choose this option, type in the number 1*")
print("")
print("Got any more information about this village? *To choose this option, type in the number 2*")
print("")
print("Thank you! *To choose this option, type in the number 3*")
print("")
ask3 = input("Enter desired number here, or say, cancel, to go back to the main shop screen. ")
print("")
if "1" in ask3:
def questionTown():
Type("That's the name of this town.")
print("")
print("")
town = input("Go back? *Say, yes, to go back to the previous screen*")
print("")
if "yes" in town:
murlor()
else:
Type("I'm sorry but the word you have entered is invalid. Please try again.")
print("")
print("")
questionTown()
questionTown()
elif "2" in ask3:
def askquest1():
Type("Well I DO know that there's this secret underground dungeon. It's VERY dangerous but it comes with a huge reward. If you ever consider it, could you get my lucky axe? I dropped it down a hole leading to the dungeon and i was too afraid to get it back. *If you accept the quest, say yes, if you want to go back, say, no.*")
quest1 = input(" ")
print("")
if "yes" in quest1:
quest1()
elif "no" in quest1:
murlor()
else:
Type("The option you have selected is not valid. Please try again")
print("")
print("")
askquest1()
askquest1()
elif "3" in ask3:
shop()
else:
Type("The number or word you have entered is invalid. please try again.")
print("")
print("")
murlor()
murlor()
elif "2" in ask1:
def heal():
if c.hp == c.mhp:
Type("I can't heal you because there's nothing to heal.")
print("")
print("")
shop()
elif c.hp > 10 and c.hp < c.mhp:
Type("Sure! That'll be 30 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
print("")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
print("")
heal()
elif c.hp > 0 and c.hp <= 10:
Type("How are you still alive?!")
print("")
print("")
Type("That'll be 50 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
print("")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
print("")
heal()
else:
Type("HELP!! IT'S THE WALKING DEAD!!")
print("")
print("")
shop()
heal()
user()
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
You set self.weaponAttack to be an empty list, and then try to assign cweaponAttack to be the element at index 0 in weaponAttack - empty lists don't have anything at index 0, as they are empty. I'm guessing you want self.cweaponAttack to be nothing when a new Cloud instance is created, in which case if you need it to be nothing you can set it to be None, else you can just assign to it when needed.
self.cweaponAttack = None
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
At the time of the second line, self.weaponAttackis an empty list, and therefore doesn't have any elements. Hence, an index of 0 is out of range for self.weaponAttack.
At the time the instance of the class is first created with Cloud(), self.weaponAttack is an empty list, and there will be no such thing as an index 0.
You may consider passing a non-empty list to self.weaponAttack as an argument via the class constructor:
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c = Cloud(weaponAttacks)
And your class becomes:
class Cloud:
'''This is the Cloud class etc.'''
weaponAttack = list()
def __init__(self, weaponAttacks):
self.weaponAttack = weaponAttacks
self.cweaponAttack = self.weaponAttack[0]

How can I make Python 3.4 subtract from a score?

I am making a small gambling game in Python where you start off with 500 dollars, but I want to subtract your money when you use it. I have money += irand (irand being the money you make from gambling) but I don't know how to subtract the money from the string money. Any help? Thank you.
Here's my code:
import sys
import os
import time
import math
from random import randrange, uniform
#CLS
def cls():
os.system('cls')
#Main Game
def casino():
money = 500
print ("You have $500 dollars to start with.")
time.sleep(3)
while True:
bet = input ("How much money do you wish to bet?: ")
if bet >= '1' or bet <= '50':
irand = randrange(0, 101)
print ("Your earnings are $%s" % irand + "!")
time.sleep(3)
money += irand
print ("You now have $%s" % money + "!")
time.sleep(4)
cls()
continue
if bet >= '51' or bet <= '100':
irand = randrange(0, 201)
print ("Your earnings are $%s" % irand + "!")
time.sleep(3)
money += irand
print ("You now have $%s" % money + "!")
time.sleep(4)
cls()
continue
if bet >= '101' or bet <= '150':
irand = randrange(0, 301)
print ("Your earnings are $%s" % irand + "!")
time.sleep(3)
money += irand
print ("You now have $%s" % money + "!")
time.sleep(4)
cls()
continue
if bet >= '151' or bet <= '200':
irand = randrange(0, 401)
print ("Your earnings are $%s" % irand + "!")
time.sleep(3)
money += irand
print ("You now have $%s" % money + "!")
time.sleep(4)
cls()
continue
if bet >= '201' or bet <= '250':
irand = randrange(0, 501)
print ("Your earnings are $%s" % irand + "!")
time.sleep(3)
money += irand
print ("You now have $%s" % money + "!")
time.sleep(4)
cls()
continue
#Intro to Game - Optional
def intro():
print ("CMD Casino is a small CMD game that simulates a gambling game.")
time.sleep(4)
print ("Just type in a money value and the game will determine if you make or lose out on your bet.")
time.sleep(4)
cls()
#Main Code
def main():
print ("Please select an option when prompted!")
while True:
time.sleep(0.5)
print ("[1] Casino")
time.sleep(0.5)
print ("[2] How-To")
time.sleep(0.5)
print ("[3] Exit")
time.sleep(1)
menu = input ("Please Choose: ")
cls()
time.sleep(1)
if menu == '1':
casino()
if menu == '2':
intro()
if menu == '3':
print ("Exiting the game...")
time.sleep(2)
break
SystemExit
#Launch Code
if __name__ == "__main__":
print ("CMD Casino")
time.sleep(2)
print ("By: Oiestin")
time.sleep(2)
print ("In hand with: oysterDev")
time.sleep(4)
cls()
print ("Version Beta 1.0.0")
time.sleep(4)
cls()
main()
Your code is not going to work, because you are trying to use mathematical operators like >=, etc. to compare string values, which will result in unexpected (for you) results. Instead, all monetary values should either be ints or floats to begin with, and you should cast your input() values to ints or floats as well, in order for the math to work correctly.
Just to illustrate:
>>> "20" > "1000" # because 50 (ord("2")) is > 49 (ord("1"))
True

Categories

Resources