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
Related
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()
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 *=
NOTE:
This is not a duplicate of
Python integer incrementing with ++
I triedw_sword += 1 and it still showed up as 0.
Okay so this is my code as of now.
#creates random monsters with xp points, leveling up player, and adding upgrades
#imports
from clint.textui import colored, puts
import random
def game():
sticks = 2
stumps = 2
stone = 0
iron = 0
gold = 0
diamond = 0
platinum = 0
w_sword = 0
w_shield = 0
items = ('sticks:' + str(sticks) + ' stumps:' + str(stumps) + ' stone:' + str(stone) + ' iron:' + str(iron) + ' gold:' + str(gold) + ' diamond:' + str(diamond) + ' platinum:' + str(platinum) + ' Wooden sword(s):' + str(w_sword) +
' wooden shield(s):' + str(w_shield))
#start of the game
def start_game():
print(' Hello player! Welome to a text based game involving killing monsters, leveling up, crafting weapons, and upgrading weapons!!!')
print(' To get started enter in (i)inventory (c)craft items (d)description of items (m)types of monsters or (f)fight monsters.')
print(' ENTER (help) FOR HOW THE GAME WORKS')
print(' ENTER(?) FOR TO PRINT THIS AGAIN')
print(' WHILE YOU ARE IN A CATEGORY SUCH AS (i)inventory PRESS (?) CAN BE USED TO GO BACK AND GO TO ANOTHER CATEGORY')
start_game()
main_In = input()
level = 0
Pxp = 0
gold = 0
if main_In == ('c'):
ws_sticks = 2
ws_stumps = 1
def craft():
print('Would you like to craft an item??')
print('( Red = uncraftable )')
print('( Green = craftable )')
print('( Type items in lowercase )')
if sticks < ws_sticks:
puts(colored.red('Wooden sword'))
else:
puts(colored.green('Wooden sword'))
if stumps < ws_stumps:
puts(colored.red('Wooden shield'))
else:
puts(colored.green('Wooden shield'))
craft()
C_item = input()
def re_craft():
print('press ENTER to go back to the start screen, or enter c to craft an(other) item.')
cor_go = input()
if cor_go == ('c'):
craft()
C_item = input()
else:
game()
if C_item == ('no'):
print('press ENTER to go back to the start screen')
input()
game()
if C_item == ('wooden sword') and sticks >= ws_sticks:
print('Wooden sword added to your inventory')
re_craft()
if C_item == ('wooden sword') and sticks < ws_sticks:
print('You need ' + str(ws_sticks - sticks) + ' stick(s) to craft a wooden sword')
re_craft()
if C_item == ('wooden shield') and stumps >= ws_stumps:
print('Wooden shield added to your inventory')
re_craft()
if C_item == ('wooden shield') and stumps < ws_stumps:
print('You need' + str(ws_stump - stumps) + ' stumps to craft a wooden shield.')
re_craft()
while ('Wooden shield added to your inventory'):
w_shield = +1
while ('Wooden sword added to your inventory'):
w_sword = +1
if main_In == ('i'):
puts(colored.yellow('Level: ' + str(level)))
puts(colored.yellow('xp: ' + str(Pxp)))
puts(colored.yellow('gold:' + str(gold)))
puts(colored.yellow('Items: ' + str(items)))
puts(colored.yellow('press ENTER to return to the start screen'))
input()
game()
if main_In == ('?'):
game()
game()
Now as you can see, w_sword and w_shield are both = to 0 correct?
Right around where it says w_sword = +1 and w_shield = +1 is where I think the problem is.
When you run the program, enter c, and then craft a wooden sword/shield, it should automatically add 1 to w_sword/w_shield once you go to your (i)inventory. But for some reason when you go back to your (i)inventory, w_sword/w_shield (depending on which one you crafted) comes up as 0.
I thought this code would work mostly because in the items assignment, it contains str(w_sword) and str(w_shield) and the others. So when you craft and item like a wooden sword or wooden shield then it str(w_shield) or str(w_sword) should come up as 1.
Does anyone know what my problem is??
I use python 3.3 as said in the title.
The syntax is w_sword += 1 , not w_sword =+ 1.
I've got a piece of code I'm working on for a school project and the basic idea is that there's a battle between two characters where the user can input 2 attributes to each character: Strength and Skill. Now there are also modifiers for skill and strength which is the difference of the player's skill and strength attributes, divided by 5 and then rounded down respectively. Then each player has a dice roll, depending on who got the higher roll, that player gets the skill and strength modifiers added to their given attributes whilst the one that lost gets the modifiers deducted from their score. This then repeats until the strength attribute of one of them reaches 0 where that player then dies and the game ends.
In my code, the dice rolling function runs twice, and then crashes for an unknown reason I cannot identify.
import random
import time
import math
import sys
strength_mod = 0
skill_mod = 0
def delay_print(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.05)
def str_mod(charone_str,chartwo_str):
if charone_str > chartwo_str:
top = charone_str
bottom = chartwo_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif chartwo_str > charone_str:
top = chartwo_str
bottom = charone_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif charone_str == chartwo_str:
top = charone_str
bottom = chartwo_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
def skl_mod(charone_skl, chartwo_skl):
if charone_skl > chartwo_skl:
top = charone_skl
bottom = chartwo_skl;
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif chartwo_skl > charone_skl:
top = chartwo_skl
bottom = charone_skl
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif charone_skl == chartwo_skl:
top = charone_skl
bottom = chartwo_skl
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
def mods():
global strength_mod
global skill_mod
strength_mod = str_mod(charone_strength, chartwo_strength)
skill_mod = skl_mod(charone_skill, chartwo_skill)
print "\nFor this battle, the strength modifier is:",strength_mod
time.sleep(0.20)
print "For this battle, the skill modifier is: ",skill_mod
time.sleep(0.20)
diceroll(charone, chartwo)
print "\n"+str(charone)+"'s","dice roll is:",player1
time.sleep(1)
print "\n"+str(chartwo)+"'s","dice roll is:",player2
def diceroll(charone, chartwo):
print "\n"+str(charone)+" will roll the 6 sided dice first!"
time.sleep(0.5)
global player1
player1 = random.randint(1,6)
delay_print("\nRolling dice!")
global player2
player2 = random.randint(1,6)
time.sleep(0.5)
print "\nNow",chartwo,"will roll the 6 sided dice!"
time.sleep(0.5)
delay_print("\nRolling dice!")
def battle(charone_str, chartwo_str, charone_skl, chartwo_skl, str_mod, skl_mod):
global charone_strength
global charone_skill
global chartwo_strength
global chartwo_skill
if player1 == player2:
print "\nThis round is a draw! No damage done"
elif player1 > player2:
charone_strength = charone_str + str_mod
charone_skill = charone_skl + skl_mod
chartwo_strength = charwo_skl - str_mod
chartwo_skill = chartwo_skl - skl_mod
print "\n"+charone+" won this round"
print "\n"+"Character 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
elif player2 > player1:
chartwo_strength = chartwo_str + str_mod
chartwo_skill = chartwo_skl + skl_mod
charone_strength = charone_str - str_mod
charone_skill = charone_skl - skl_mod
print "\n"+chartwo+" won this round"
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skilll
time.sleep(1)
print "\n"+"Character 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
if charone_skill >= 0:
charone_skill = 0
elif chartwo_skill >= 0:
chartwo_skill = 0
if charone_strength <= 0:
print charone,"has died!",chartwo,"wins!"
elif chartwo_strength <= 0:
print chartwo,"has died!",charone,"wins!"
charone = raw_input("Enter the name of character one: ")
chartwo = raw_input("Enter the name of character two: ")
time.sleep(1.5)
print "\n",charone,"encounters",chartwo
delay_print("\nBattle Initiated!")
charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
while charone_strength > 100 or charone_strength < 50:
print "That number is not between 50-100"
charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
else:
pass
charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
while charone_skill > 100 or charone_skill < 50:
print "That number is not between 50-100"
charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
else:
pass
time.sleep(1.0)
chartwo_strength = int(raw_input("\nEnter the strength score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_strength > 100 or chartwo_strength < 50:
print "That number is not between 50-100"
chartwo_strength = int(raw_input("\n Enter the strength score for "+str(chartwo)+" (between 50 and 100): "))
else:
pass
chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_skill > 100 or chartwo_skill < 50:
print "That number is not between 50-100"
chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
else:
pass
time.sleep(2)
print "\nCharacter 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
time.sleep(1)
while charone_strength != 0 or chartwo_strength != 0:
ent = raw_input("Press Enter to roll! ")
mods()
diceroll(charone,chartwo)
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
else:
play = raw_input("\nWould you like to play again?")
if play in ["yes","y","Yes","Y"]:
execfile("gcse.py")
else:
print "Goodbye"
This code is an excellent example of how not to program:
heavy use of global variables
multiple variables with very similar names (ie charone_strength, charone_str)
reuse of names in different contexts (in global scope, str_mod is a function, but in function battle it is supposed to be an integer
Your immediate problem: in line 182, you call
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
which should be
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, strength_mod, skill_mod)
but is confused because in the function strength_mod is referred to as str_mod.
Here is a greatly cleaned-up version. (Further suggestions for improvement are welcome).
from __future__ import division, print_function
from random import randint
import sys
from time import sleep
# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
PRINT_DELAY = 0.02
PAUSE_DELAY = 0.2
TF_VALUES = {
'y': True, 'yes': True, 't': True, '': True,
'n': False, 'no': False, 'f': False
}
def get_int(prompt="Enter an integer: ", lo=None, hi=None):
while True:
try:
i = int(inp(prompt))
if (lo is None or lo <= i) and (hi is None or i <= hi):
return i
except ValueError:
pass
def get_tf(prompt="Yes or no? ", tf_values=TF_VALUES):
while True:
s = inp(prompt).strip().lower()
tf = tf_values.get(s, None)
if tf is not None:
return tf
def pause(delay=PAUSE_DELAY):
sleep(delay)
def roll(die_sides=6):
return randint(1, die_sides)
def slow_print(s, delay=PRINT_DELAY):
for ch in s:
print(ch, end='', flush=True)
sleep(delay)
print('') # end of line
def wait_for_enter(prompt):
inp(prompt)
class Fighter:
#classmethod
def get_fighter(cls, prompt):
print(prompt)
name = inp ("Name: ")
health = get_int("Health: (50-100) ", 50, 100)
skill = get_int("Skill: (50-100) ", 50, 100)
return cls(name, health, skill)
def __init__(self, name, health, skill):
self.name = name
self.health = health
self.skill = skill
def is_alive(self):
return self.health > 0
def health_mod(self, other_fighter):
delta = abs(self.health - other_fighter.health)
return int(delta / 5)
def skill_mod(self, other_fighter):
delta = abs(self.skill - other_fighter.skill)
return int(delta / 5)
def attack(self, other_fighter):
wait_for_enter("Hit Enter to fight!")
# figure out mod values
health_mod = self.health_mod(other_fighter)
skill_mod = self.skill_mod (other_fighter)
self_roll = roll()
other_roll = roll()
slow_print(
"Health mod: {} Skill mod: {} {} rolls {} {} rolls {}"
.format(
health_mod, skill_mod,
self.name, self_roll,
other_fighter.name, other_roll
)
)
# figure out who won this round
if self_roll == other_roll:
print("Draw! No damage done.")
else:
winner, loser = (self, other_fighter) if self_roll > other_roll else (other_fighter, self)
print("{} hits {}!".format(winner.name, loser.name))
winner.health += health_mod
winner.skill += skill_mod
loser.health -= health_mod
loser.skill -= skill_mod
# show results
print('')
print(self)
print(other_fighter)
print('')
def __str__(self):
return "{}: health {}, skill {}".format(self.name, max(self.health, 0), max(self.skill, 0))
def fight():
f1 = Fighter.get_fighter("\nFirst fighter:")
pause()
f2 = Fighter.get_fighter("\nSecond fighter:")
pause()
slow_print("\n{} encounters {}\nBattle Initiated!".format(f1.name, f2.name))
while f1.is_alive() and f2.is_alive():
f1.attack(f2)
winner, loser = (f1, f2) if f1.is_alive() else (f2, f1)
print("{} has died; {} wins!".format(loser.name, winner.name))
def main():
while True:
fight()
if not get_tf("Would you like to play again? (Y/n)"):
print("Goodbye!")
break
if __name__=="__main__":
main()
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.