Repeating a block of "If" statement - python

I'm trying to make a text based game, and to make my fighting mechanics I have to repeat an if statement until you or the monster dies.
Here it is --
Ph would stand for Player health, str is player strength, mdam is monster damage, mstr is monster strength, monsterh is monsterhealth, the random.random() is the attack bonus you receive (Adding onto this, is there any way to round the number to one or no decimal places?) Thank you! :D
if fight == "A" and ph > 0:
damage = (str) + (random.random())
monsterh = 6
mstr = 0.9
monsterh = (monsterh) - (damage)
print(damage)
print(damage - str)
print('You attack the monster. You deal %s damage.' % damage )
time.sleep(3)
if monsterh > 0:
mstr = 0.9
mdam = (mstr) + (random.random())
print('The monster attacks you!')
ph = ph - mstr
print("You get hit %s" % mdam )
else:
xpgain = damage + 5
print("You won! You've gained %s XP!" % xpgain)

I would wrap your combat seen in a while loop. For example:
while (ph > 0 or monsterh > 0)
# combat rules
# Check who died and move on from there
if (ph > 0)
# next thing the player does
else
# print "You died"
In regards to rounding, there are multiple options depending on exactly what you want to do: python: getting only 1 decimal place

To round the value you get from
random.random()
you can do
round(random.random(),1)
to round to 1 decimal place, or if you want to get rid of decimals, replace
random.random()
with
int(random.random())
As for repeating the if statement, you can put it into a loop which will break when a condition is met
while true:
if fight == "A" and ph > 0:
damage = (str) + (int(random.random()))
monsterh = 6
mstr = 0.9
monsterh = (monsterh) - (damage)
print(damage)
print(damage - str)
print('You attack the monster. You deal %s damage.' % damage )
time.sleep(3)
elif ph<=0 or fight!="A":
print("You lose!")
break
if monsterh > 0:
mstr = 0.9
mdam = (mstr) + (int(random.random()))
print('The monster attacks you!')
ph = ph - mstr
print("You get hit %s" % mdam )
else:
xpgain = damage + 5
print("You won! You've gained %s XP!" % xpgain)
break
Although you wouldn't need the fight!="A" since I don't think you change the value of fight at all.
Also you don't have to do
mdam = (mstr) + (int(random.random()))
You can just do
mdam = mstr+int(random.random())
This above ^ applies to other places in your code as well. If you have any questions please feel free to ask.

Related

I'm trying to get specific results from my Lucky Sevens program, but I'm not sure where to go from here

I'm trying to calculate the number of rolls it takes to go broke, and the amount of rolls that would have left you with the most money. The program is split into several functions outside of main (not my choice) so that makes it more difficult for me.
I'm very new to python, and this is an exercise for school. I'm just not really sure where to go from here, and I realize I'm probably doing some of this wrong. Here's the code I have so far:
import random
def displayHeader(funds):
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
funds = int(input("How many dollars do you have? "))
def rollDie(newFunds):
#this function is supposed to simulate the roll of two die and return results
while funds > 0:
diceRoll = random.randint(1,6)
totalRoll = (diceRoll + diceRoll)
if totalRoll == 7:
funds = funds + 4
else:
funds = funds - 1
if funds == 0:
newFunds = funds
def displayResults():
#this function is supposed to display the final results.
#the number of rolls, the number of rolls you should have stopped at, and the max amount of money you would have had.
def main():
#everything gathered from the last function would be printed here.
main()
import random
maxmoney = []
minmoney = []
def displayHeader():
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
funds = int(input("How many dollars do you have? "))
return funds
def rollDie():
#this function is supposed to simulate the roll of two die and return results
funds = displayHeader()
while funds > 0:
diceRoll1 = random.randint(1,6)
diceRoll2 = random.randint(1,6)
totalRoll = (diceRoll1 + diceRoll2)
if totalRoll == 7:
funds = funds + 4
maxmoney.append(funds)
else:
funds = funds - 1
minmoney.append(funds)
def displayResults():
#this function is supposed to display the final results.
#the number of rolls, the number of rolls you should have stopped at, and the max amount of money you would have had.
rollDie()
numOfRolls = len(maxmoney) + len(minmoney)
numOfRolls2Stop = (len(maxmoney) - 1 - maxmoney[::-1].index(max(maxmoney))) + (len(minmoney) - 1 - minmoney[::-1].index(max(maxmoney)-1)) + 1 if maxmoney and minmoney else 0
maxAmount = max(maxmoney) if maxmoney else 0
return numOfRolls, numOfRolls2Stop, maxAmount
def main():
#everything gathered from the last function would be printed here.
a, b, c = displayResults()
print('The number of total rolls is : ' + str(a))
print("The number of rolls you should've stopped at is: " + str(b))
print("The maximun amount of money you would've had is: $" + str(c))
main()
Your program use variables that can only be accessed in certain scopes, so I think that the most recommended thing is that you use a class.
displayHeader input method it could stop the execution of the program since if you do not introduce a numerical value it will raises an exception called ValueError, if this does not help you much, I advise you to read the code carefully and add missing variables such as the input amount and the final amount and others...
class rollDiceGame():
def __init__(self):
self.funds = 0
self.diceRollCount = 0
def displayHeader(self):
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
self.funds = int(input("How many dollars do you have? "))
def rollDice(self):
while self.funds > 0:
diceRoll = random.randint(1,6)
totalRoll = (diceRoll + diceRoll)
self.diceRollCount += 1
if totalRoll == 7:
self.funds += 4
else:
self.funds -= 1
def displayResult(self):
print('Roll count %d' % (self.diceRollCount))
print('Current funds %d' % (self.funds))
def main():
test = RollDiceGame()
test.displayHeader()
test.rollDice()
test.displayResult()
main()

Error with a player turn ending loop in the Zombie Dice game

I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=

Python 2.7.3 Code Loops Without a While Loop

I am relatively new to programming, so don't be surprised if there are some minor hiccups in the code, but the problem that is happening is that this code seems to loop itself, the whole thing and I don't understand why. I looked at the actual code that runs this function but it seemed fine. So I cannot find any error in this code that makes it loop itself. (If the problem isn't in this code then the looping code it beneath it)
def thebeast(yourhp):
foe = "Thisisirrelevant"
enemy = int(random.randint(1,4))
if enemy == 1:
foe = "skeleton"
elif enemy == 2:
foe = "man with crazy eyes"
else:
foe = "dog, a big and scary dog"
monsteract = 1
dmg = 0
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print " C O M B A T"
time.sleep(0.1)
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print "You encounter a " + foe
time.sleep(0.5)
while monsteract == 1:
comb = str(input("What do you do to the " + foe + "?" + " Do you feel like jabbing it or stabbing it?"))
if comb in ["s", "S", "Stab", "STAB", "stab"]:
if spear == 1:
dmg = int(random.randint(1,4))
elif sword == 1:
dmg = int(random.randint(1,3))
else:
dmg = int(random.randint(1,5))
elif comb in ["j", "J", "Jab", "JAB", "jab"]:
if spear == 1:
dmg = int(random.randint(1,3))
elif sword == 1:
dmg = int(random.randint(1,4))
else:
dmg = int(random.randint(1,5))
if dmg == 1:
print "You slay the " + foe + " with graceful ease"
time.sleep(0.5)
monsteract = 0
else:
enemydmg = int(random.randint(1,3))
print "The " + foe + " strikes you for " + str(enemydmg) + " damage"
time.sleep(0.3)
print "That didn't work out as planned, but you pull yourself together and prepare to strike the " + foe
time.sleep(0.3)
yourhp = yourhp - enemydmg
if yourhp < 0:
yourhp = 0
print "You have " + str(yourhp) + " health left"
time.sleep(0.3)
if yourhp < 1:
print "The " + foe + " has slain you, well done, you're dead, on the bright side the innocent "
print foe + " is still alive! Every life counts, even that of a " + foe + "."
monsteract = 0
return thebeast(yourhp)
Looping code:
def randomevents(yourhp):
turn = 10
while turn > 0:
time.sleep(0.1)
happening = int(random.randint(1,6))
time.sleep(0.1)
if yourhp < 1:
turn = 0
print "You managed to escape the dungeon, by dying that is"
elif happening == 1:
turn = turn - 1
thebeast(yourhp)
elif happening == 2:
item(sword, spear)
turn = turn - 1
elif happening in [3, 4, 5]:
friend()
turn = turn - 1
print "Well done! You escaped the dungeon! (Either by running out of it, or by having your soul sent to another world)"
useless = str(input("Are you satsified with yourself?: "))
Thank you!
Look at your return statement at the end of thebeast. At the end of the function, you call the function again! Since this happens every time you call it, you will never stop calling it (until you hit the maximum recursion depth). Considering that you don't capture the return value of thebeast in randomevents, you should consider it not returning anything.

Local variable referenced before assignment (don't want to use global)

I'm learning Python using "Learn Python the hard way" and am currently making a simple game
Following the book's guidelines, each "room" is to be it's own function and herein lies my problem, I have some variables that need to be accessed by all functions. e.g. Current_health, armor, strength stat.
I have looked at the previous questions on here (that I actually understood) and the only solution seems to be to declare it as a global variable within the function, but as I'm going to have 20+ rooms (functions) it seems a bit silly to declare them all every time
The other option is to pass the variable when calling the function, but as I need to put through 8 variables each time that also seems impractical. Any help would be greatly appreciated. I'll paste the code below in case it helps (the game is far from finished so some may not make sense)
Right now the start() works because of my global variables but I'll run into the error as soon as it tries to run shadow_figure() because of the wep_dam reference
from sys import exit
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
def shadow_figure():
print "\n\nYou approach the figure, who remains silent."
print "As you get closer you realise he has bag at his feet."
print "Mysterious figure: \"You may choose only one.\""
print "You look into the bag, and see a shiny sword on top of a large steel shield."
ans = raw_input("Do you: \n1. Take the sword \n2. Take the shield \n3. Take the whole bag and run \n4. Walk away without taking anything\n> ")
if ans == "1":
print "The sword gives you an extra 3 damage"
wep_dam += 3
exit_beach()
elif ans == "2":
print "The shield gives you 3 armor, but it's so heavy it reduces your sneak by 1"
arm += 3
sne -= 1
def beach():
print "\n\nYou wake up on a beach with no idea how you got there. \nYou see a shadowy figure close to the water."
ans = raw_input("Do you: \n1. Approach him \n2. Go the other way\n> ")
if ans == "1":
shadow_figure()
elif ans == "2":
exit_beach()
else:
print "Please enter either 1 or 2"
def reset_stats():
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 10
print "\n\n\n\nGame Reset\n\n\n\n"
def start():
global str
global wep_dam
global dam
global cha
global sne
global arm
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
print "You are an adventurer, your stats are currently:"
print "Strength: %d \nCharisma: %d \n Sneak: %d" % ( str, cha, sne)
print "Strength determines your damage, charisma determines your chance of pursuasion, \nand sneak determines whether or not you can go get past enemies without being detected"
print "you have 10 points available to spend, to spend a point, simply type the number which corresponds\nwith the skill and hit enter"
print "\n\n1. Strength \t2. Charisma \t3. Sneak\n"
points_remaining = 10
while points_remaining > 0:
ans = raw_input("Choose a skill: ")
if ans == "1":
str += 1
points_remaining -= 1
print "Strength is now %d" % ( str)
print "%d points remaining\n" % ( points_remaining)
elif ans == "2":
cha += 1
points_remaining -= 1
print "Charisma is now %d" % ( cha)
print "%d points remaining\n" % ( points_remaining)
elif ans == "3":
sne += 1
points_remaining -= 1
print "Sneak is now %d" % ( sne)
print "%d points remaining\n" % (points_remaining)
else:
print "Error, please enter a number from 1 to 3\n"
print "Your stats are now: "
print "Strength: %d \nCharisma: %d \n Sneak: %d\n\n" % ( str, cha, sne)
print "Is this OK? Or would you like to restart?\n"
ans = raw_input("1. Continue \n2. Restart\n> ")
if ans == "1":
print "Game will now begin...."
beach()
elif ans == "2":
ans = raw_input("Are you sure? Yes/No\n> ")
ans = ans.lower()
if ans == "yes":
reset_stats()
start()
else:
beach()
else:
print "Error, please enter 1 or 2"
start()
You may wrap your globals in class:
class Player:
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
and access its fields in rooms like this: Player.arm += 3

Why is Int() conversion not working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Post can be closed. Turns out I messed up something unknown, because now I retried and the int() function is working as I wanted.
`
`
This is a small piece of code that I wrote:
def damagecalculating(self):
self.damage = random.randrange(1,100) * self.weapondamage / 5
self.damage = int(self.damage)
(used long words here to make clear what I am doing)
So what I'm doing is calculating the damage a player does in an attack. but I want an integer and not a float so had to add the extra line.
This returns a float for some reason:
self.damage = int((random.randrange(1,100) * self.weapondamage) / 5)
I don't understand that, because what I see is that random.randrange(1,100) is calculated, then self.wepdamage is found and thus the formula becomes, for example: 55 * 10 / 5.
Why would this return a float in the first place (I found it has something to do with the /)? And why does int() not work? because int(55*10/5) does return an integer.
I did already find http://www.stackoverflow.com/questions/17202363/int-conversion-not-working but this does not answer my question as to why or if this can be done in one line.
Edit:
I don't really see why this would be needed but this is the full code as some requested. Please note that I'm very new to programming and there is probably a bunch of stuff that can be done better. Also it's far from done.
import random
class playerstats:
def usepotion(self):
heal = random.randrange(100,500)
self.health = self.health + heal
self.pots -= 1
print('The potion healed', str(heal) +'!')
print(self.name, 'now has', str(self.health), 'health.')
def minushealth(self, amount):
self.health = self.health - amount
def damagecalc(self): ### HERE IS THE PROBLEM ###
self.damage = random.randrange(1,100) * self.wepdamage / 5
self.damage = int(self.damage)
name = ''
health = 0
weapon = ''
wepdamage = 5
damage = 0
pots = 0
def printdata():
print(player.name, 'health =', player.health)
print(player.name, 'potions =', player.pots)
print()
print(opp.name, 'health =', opp.health)
print(opp.name, 'potions =', opp.pots)
print()
def setgamedata():
player.name = input('Set player name: ')
player.health = int(input('Set player health (1000): '))
player.weapon = input('Set player weapon name: ')
player.wepdamage = int(input('Set player damage multiplier (5 = normal): '))
player.pots = int(input('Set number of potions for player: '))
print()
opp.name = input('Set opponent name: ')
opp.health = int(input('Set opponent health (1000): '))
opp.weapon = input('Set opponent weapon name: ')
opp.wepdamage = int(input('Set opponent damage multiplier (5 = normal): '))
opp.pots = int(input('Set number of potions for opponent: '))
print()
def resetgamedata():
player.name = input('Player name currently is: ' + player.name + '. Set player name: ')
player.health = int(input('Player health currently is: ' + str(player.health) + '. Set player health (1000): '))
player.weapon = input('Player weapon currently is', player.weapon, 'Set player weapon name: ')
player.wepdamage = int(input('Player damage multiplier currently is: ' + str(player.wepdamage) + '. Set player damage multiplier: '))
player.pots = int(input('Player currently has ' + str(player.pots) + ' potions. Set player potions: '))
print()
opp.name = input('Opponent name currently is: ' + opp.name + '. Set opponent name: ')
opp.health = int(input('Opponent health currently is: ' + str(opp.health) + '. Set opponent health (1000): '))
opp.weapon = input('Opponent weapon currently is', opp.weapon, 'Set opponent weapon name: ')
opp.wepdamage = int(input('Opponent damage multiplier currently is: ' + str(opp.wepdamage) + '. Set opponent damage multiplier: '))
opp.pots = int(input('Opponent currently has ' + str(opp.pots) + ' potions. Set opponent potions: '))
print()
def menuoptions():
print('1. Start new game')
print('9. Quit')
print()
def battleoptions():
print('1. Attack')
print('2. Use potion')
print('3. Change stats')
print('9. Abandon game')
print()
### ACTUAL GAME CODE STARTS HERE ###
# Set objects
player = playerstats()
opp = playerstats()
print('- - - - - - - - - - - - - - - -\n')
print('Welcome to the game!\n\n')
print('Entering main menu\n')
while True:
menuoptions()
choice=int(input('Enter number: '))
print()
while True:
if choice == 1:
setgamedata()
print('Starting game now!')
while player.health > 1 and opp.health > 1:
battleoptions()
choice = int(input('Enter number: '))
print()
# Execute player move
if choice == 1:
printdata()
elif choice == 2:
player.usepotion()
elif choice == 3:
resetgamedata()
elif choice == 9:
print('Quit game')
input('Press enter to return to main screen')
break
else:
print('No valid choice made')
# Execute opponent move
if opp.health < 200:
oppmove = 1
else:
oppmove = 0
if oppmove == 1:
opp.usepotion()
else:
print('nothing here')
##### ATTACK PLAYER
### SOMETHING HERE WHEN PERSON REACHED < 0 HEALTH
if choice == 9:
print('\nQuit?! Okay fine\n')
print('Your stuff was not saved, good luck with that.\n')
input('Press enter to close screen')
import sys
sys.exit()
input('')
The issue you are experiencing is that in Python 3.x the division operator / performs true division - that is, the returned value is float. If you want the behaviour of Python 2.x, that is integer division use the // operator. Note, that the // division result will be int if the dividend and divisor are integers.
>>> 5 / 10
0.5
>>> 5 // 10
0
>>> type(5 // 10)
<class 'int'>
For floats, the // operator still returns a float:
>>> 5.0 // 10
0.0
>>> 5 // 10.0
0.0

Categories

Resources