Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm made a program that calculates the current health of a player and switches between them. I need help switching between players. This is what i have so far:
class Player():
def turn(life):
players = ['Player 1', 'Player 2']
life = 100
for player in players:
while life >= 0:
print (life)
print ("+, -, or end turn")
choice = input("> ")
if choice == "+":
print ("Damage taken")
healing = int(input("> "))
life += healing
elif choice == "-":
print ("Damage taken")
damage = int(input("> "))
life -= damage
elif choice == "end turn" or "end":
return
else:
print ("You lose!")
play = Player()
play.turn()
I've been in a similar position before. I would recommend doing something a bit different than the answer you might be looking for. Instead of looking for a solution to this individual problem, I would recommend looking at resources for game design patterns.
While I think that the learning curve might be a bit high initially, I think that if you learn to work with proper design patterns for game mechanics, you will find it much easier to build what you are after.
There are a few different resources that you can choose from. I used http://gameprogrammingpatterns.com/ (I have no association with this individual), but I also have a background in c++. I would look around for what might be the most intuitive for you and give it a try.
All the best!
Here is a start:
class Player:
def __init__(self, name, health=100):
self.name = name
self.health = health
def hit(self, n):
assert n >= 0
self.health -= n
def heal(self, n):
assert n >= 0
self.health += n
#property
def is_dead(self):
return self.health <= 0
class Game:
def __init__(self):
self.players = [Player("Adam"), Player("Bert")]
def turn(self, me, him):
# fill this in!
def play(self):
a, b = self.players
while True:
self.turn(a, b)
if b.is_dead:
print("{} won!".format(a.name))
break
else:
# swap players
a, b = b, a
if __name__ == "__main__":
Game().play()
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a turn based rpg game in python. Currently i am using the list method to display and create individual values for each role. For example, the game allows player to setup a team of units for battle (minimum of 1 unit, default is 3). Each unit has a unique name and attributes like health point (HP), attack point (ATK), defence point (DEF), experience point (EXP) and a rank (default is level 1).
A unit can be either a Warrior, a Tanker or a Wizard whom have different strength in ATK and DEF point. In addition, a Wizard has special ability to cast spells that can impact friendly and enemy units (Heal, Poison, Cure, Freeze).
The suggested initial values for each unit’s attribute point are described in requirement details under Part A – Game Setup section.
The game will automatically setup either (1) player vs Artificial Intelligence (AI) or (2) two-player mode, of which both teams are made up of same number of units.
For AI team, the type of units will be assigned randomly or by specific AI algorithm. The name of units will be specified by the player, whereas AI unit names can be defined with prefix + random numbers (eg AI87). For two-player mode, each player will be able to go through the same unit selection process either through console or GUI.
For each turn, player can select an active friendly unit (non-frozen or dead) to perform an action on a target unit. Units which are severely damaged (i.e. HP equals to or less than 0) will be considered killed (or flagged as “dead”).
How do I use Object Oriented Programming method to create the 3 characters with input name for each team (can display the name keyed and the information of each character), instead of use list method.
#Menu page
print('Welcome to PSB Battle Game! \n(N)ew game\n(S)ave game\n(Q)uit')
def main():
selection = input('Choose your option then hit <ENTER> ==> ')
if selection.upper() == 'N':
new_game()
elif selection.upper() == 'S':
print('Loading save game...')
pass
elif selection.upper() == 'Q':
print('Exit game...')
pass
else:
print("I don't understand what are you typing.")
return main()
def new_game():
print('\nSetting up Player 1 team...\n')
name_list = []
for unit_name in range(1,4):
print(f'Enter a unique name for unit #{unit_name}-> ', end='')
name = input('')
repeated = False
while repeated:
if name == "":
continue
repeated = True
if name in name_list:
print('\nUnit name must be unique.\n')
return new_game()
if not name.strip():
print('\nUnit name could not be blank.\n')
return new_game()
else:
print('Name looks good!')
name_list.append(name)
print(f'Select unit #{unit_name}, type: (W)arrior, (T)anker, or Wi(Z)ard ==> ', end='')
role = input('')
if role.upper() == 'W':
print('Added ' + str(name_list))
warrior()
elif role.upper() == 'T':
print('Added ' + str(name_list))
tanker()
elif role.upper() == 'Z':
print('Added ' + str(name_list))
wizard()
else:
print("I don't understand what are you typing.")
return role()
def warrior ():
charac = [1,50,8,3,0,'True','False','False']
print ('\nWarrior Level 1: ','HP =',charac[1],',''ATK =',charac[2],',''DEF =',charac[3],',''EXP =',charac[4],',''ALIVE =',charac[5],',''POISONED =',charac[6],',''FROZEN =',charac[7])
print ()
def tanker ():
charac = [1,60,5,5,0,'True','False','False']
print ('\nTanker Level 1: ','HP =',charac[1],',''ATK =',charac[2],',''DEF =',charac[3],',''EXP =',charac[4],',''ALIVE =',charac[5],',''POISONED =',charac[6],',''FROZEN =',charac[7])
print ()
def wizard ():
charac = [1,40,3,2,0,'True','False','False']
print ('\nWizard Level 1: ','HP =',charac[1],',''ATK =',charac[2],',''DEF =',charac[3],',''EXP =',charac[4],',''ALIVE =',charac[5],',''POISONED =',charac[6],',''FROZEN =',charac[7])
print ()
main()
Your game is far from functional. I took the liberty of setting up a small sketch of a game after your design with battle functionality and character classes. From this code you can work forward to include other functionalities, such as chance, moving, changing skill points, and other stuff.
class Char:
def __init__(self, name = '', cclass = "Warrior", stats = [1,50,5,5,0,'True','False','False']):
self.c = cclass
self.name = name
self.stats = {'LVL':stats[0],
'HP':stats[1],
'ATK':stats[2],
'DEF':stats[3],
'EXP':stats[4],
'ALIVE':stats[5],
'POISONED':stats[6],
'FROZEN':stats[7]}
self.calc_level()
def __repr__(self):
outs = ''
outs+="Character Name: {0} of class {1}:\n---------------".format(self.name,self.c)
for k,v in self.stats.items():
outs+='\n {0}: {1}'.format(k,v)
return outs
def calc_level(self):
self.stats['LVL'] = int(self.stats['EXP']**.5)+1
def attack(self,other):
print("\n{0} furiously attacks {1} with {2} attack. {1} has {3} defense.".format(self.name,other.name,self.stats['ATK'],other.stats['DEF']))
if self.stats['ATK']>=other.stats['DEF']:
other.stats['HP'] -= self.stats['ATK']
print("\nThat was a hit! The HP of {0} is now {1}".format(other.name,other.stats['HP']))
else:
print("\nYou missed and only made him angrier!")
def new_char(existing):
cc = ''
accept = False
while not accept:
n = input("\nPlease input a new name: ")
accept = True
for c in existing:
if n == c.name:
accept = False
print("This name is taken, already")
while not cc in ['w','t','z']:
cc = input("\nPlease input a class, noble {0}. (W)arrior, (T)ank, Wi(z)ard: ".format(n)).lower()
cclasses = {'w':'Warrior','t':'Tank','z':'Wizard'}
newc = Char(n,cclasses[cc])
print('\nCharacter successfully created:')
print(newc)
return newc
def play(chars):
print("May the games begin. The following characters are present:\n")
for c in chars:
print(c)
print('')
game_over = False
turn = 0
while not game_over:
print("It's the turn of noble {0} {1}. Please select a player to attack:".format(chars[turn].c,chars[turn].name))
possible = []
for i in range(len(chars)):
if not i==turn:
possible.append(i)
print(" - ({0}): {1} named {2}".format(i,chars[i].c,chars[i].name))
sel = -1
while not sel in possible:
s = input('Selection: ')
try:
sel = int(s)
except:
print("That's not a valid choice")
chars[turn].attack(chars[sel])
if chars[sel].stats['HP']<=0:
game_over=True
print("That was it! {0} has died and the game is over.".format(chars[sel].name))
turn +=1
if turn==len(chars):turn=0
def main():
chars = []
entry = ''
print("Welcome to PSB Battle Game!")
while not entry.lower() in ['q','p']:
entry = input('\n(N)ew character\n(P)lay game\n(Q)uit\nSelection: ').lower()
if entry == 'p' and len(chars)<2:
print("\nYou can't play with only one character. Create characters first")
entry = '' ## You can't play with only one char
elif entry == 'n':
chars.append(new_char(chars))
entry = ''
elif entry == 'p':
play(chars)
elif entry == 'q':
print("\nOK, good bye")
main()
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Hey ya'll I'm brand new to python/programming and have been doing some online courses. I decided to take the day off of taking notes and such and try to challenge myself with some random while loops that simulate different things in dnd. I'm currently stuck on my simulated combat, and I know I'm on the right track but obviously it's not working. Some pointers would be much appreciated.
import random
monster_hp = 25
strength = 5
ac = 17
hp = 25
combat = True
current_hp = monster_hp
dmg = 0
hit = False
def roll_to_hit(hit, ac):
hit = random.randint(1, 20)
return hit
if hit >= ac:
return True
# print(roll_to_hit(hit))
def roll_4_dmg(dmg, strength):
dmg = random.randint(1, 10) + strength
return dmg
print(f"You hit and did {dmg} damage.")
# print(roll_4_dmg())
def damage(current_hp, monster_hp, dmg):
current_hp = monster_hp - dmg
return current_hp
# print(damage())
while combat:
if current_hp > 0:
inp = input(r"A monster has appeared what will you do? ").lower()
if inp == "attack":
roll_to_hit(hit, ac)
if True:
roll_4_dmg(dmg, strength)
damage(current_hp, monster_hp, dmg)
else:
print("You missed!")
inp = input(
r"A monster has appeared what will you do? ").lower()
else:
print("You have slain the beast!")
break
Ok so there are a lot of problems with your code and I will try going through them one-by-one.
In your first function -
def roll_to_hit(hit, ac):
hit = random.randint(1, 20)
return hit
if hit >= ac:
return True
The moment you return hit the function is going to end and will not check the hit against the AC. And you dont need to pass in hit as an argument. What I think you were looking for was something more like this -
def roll_to_hit(ac):
hit = random.randint(1, 20)
if hit >= ac:
return True
return False
Your second function as a similar problem where you return a value and then try to execute another command. It also takes in an unnecessary argument dmg. It should look more like this -
def roll_4_dmg(strength):
dmg = random.randint(1, 10) + strength
print(f"You hit and did {dmg} damage.")
return dmg
Your third function is fine apart from the unused argument current_hp it can simply be -
def damage(monster_hp, dmg):
current_hp = monster_hp - dmg
return current_hp
Now in your combat loop there are a whole lot of errors mainly due to the fact that you don't seem to be storing/using the values returned from your functions (I highly recommend you read up on how functions are expected to work in python) From my understanding of what you are trying to achieve here is what I think you were going for -
while current_hp > 0:
inp = input(r"A monster has appeared what will you do? ").lower()
if(inp == "attack"):
if(roll_to_hit(ac)):
damage_done = roll_4_dmg(strength)
current_hp = damage(current_hp, damage_done)
else:
print("You missed!")
print("You have slain the beast!")
Frankly its a pretty good effort for someone new to programming, you need to read up on how stuff stored in variables actually changes (given your extra arguments in the functions I have a feeling there a slight misunderstanding there)
*Also on a different note, your roll_to_hit function is only going to 'hit' 15% of the time as it is right now so it might take a few 'attack' rolls to test out the program
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm doing a battle simulator sort of thing, and I want the player to be able to use potions, which add health, a maximum of 5 times. I also want the player to be able to have the choice to choose different types of items, but those different items cannot be more than five. Here's what I have so far:
import random, sys, time
pokedex = {"Bulbasaur": [200,32,],
"Ivysaur" : [230,40],
"Venusaur" : [270,50],
"Charmander": [188,30],
"Charmeleon": [226,40],
"Charizard": [266,84],
"Squirtle": [198,48],
"Wartortle": [228,31],
"Blatoise": [268,41],
"Caterpie": [200,15],
"Metapod": [210,10],
"Butterfree": [230,22],
"Weedle": [190,17],
"Kakuna": [200,12],
"Beedrill": [240,45],
"Pidgey": [190,22],
"Pidgeotto": [236,30],
"Pidgeot": [276,40],
"Rattata": [170,28],
"Raticate": [220,40],
"Spearow": [190,30],
"Fearow": [240,45],
"Ekans": [180,30],
"Arbok": [230,42],
"Pikachu": [180,27],
"Raichu": [230,45],
"Sandshrew": [210,37],
"Sandslash": [260,50],
"Nidoran♀": [220,23],
"Nidorina": [250,32],
"Nidoqueen": [290,46],
"Nidoran♂": [202,28],
"Nidorino": [232,36],
"Nidoking": [272,51],
"Clefairy": [250,22],
"Clefable": [300,35],
"Vulpix": [186,20],
"Ninetales": [256,38],
"Jigglypuff": [340,22],
"Wigglytuff": [390,35],
"Zubat": [190,22],
"Golbat": [260,40],
}
enemy = random.choice(list(pokedex.keys()))
enemy = [enemy, pokedex[enemy][0]]
player = random.choice(list(pokedex.keys()))
player = [player, pokedex[player][0]]
print("Your pokemon is: %s" % (player[0]))
print("The enemy's pokemon is: %s" % (enemy[0]))
while(player[1] > 0 and enemy[1] > 0):
if pokedex[player[0]][1] < enemy[1]:
choice = input("What would you like to do?")
if choice in ["Attack","attack","Kill","kill"]:
print("The player has attacked the enemy's %s." % (enemy[0]))
enemy[1] -= pokedex[player[0]][1]
print("The enemy's %s has %d HP remaining!" % (enemy[0], enemy[1]))
if choice in ["potion","Potion"]:
player[1] = player[1]+20
else:
enemy[1] = 0
print("The enemy's %s has %d HP remaining!" % (enemy[0], enemy[1]))
print("The player's %s has won!" % (player[0]))
break
if pokedex[enemy[0]][1] < player[1]:
print("The enemy has attacked the player's %s." % (player[0]))
player[1] -= pokedex[enemy[0]][1]
print("The player's %s has %d HP remaining!" % (player[0], player[1]))
else:
player[1] = 0
print("The player's %s has %d HP remaining!" % (player[0], player[1]))
print("The enemy's %s has won!" % (enemy[0]))
break
The formatting is a little weird, but I assure you that it works on my end, and the only thing that need is the potion problem above. Any help is greatly appreciated!
The simple solution is to track how many potions have been used, and to use some sort of conditional (if/while) centered around comparing that value to 5. Something like:
potions_used = 0
if choice in ["potion","Potion"]:
if (potions_used <= 5):
player[1] = player[1]+20
potions_used += 1
Create a player object which has a list of items that the player owns.
Create a method for adding items to that list. In this method, you can now check the number of items before adding them to the list.
class Player(object):
__slots__ = ['items', 'potions']
MAX_POTIONS = 5
def __init__(self):
self.items = []
self.potions = Player.MAX_POTIONS
def use_potion():
# Here you can check if the number of potions you have
# has reached zero
pass
def add_item(item):
# Here you can check the number of items the player has
pass
keep track of a variable, "potionsUsed" or something similar, increment it each time a potion is used, when it hits 5, don't allow the player to use potions.
if (choice in ["potion","Potion"]) && (potionsUsed < 5):
player[1] = player[1]+20
Something like that
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Hay guise i'm new to Programming, could someone pleas help me i need to figure this out but everywhere i look i don't understand what people are saying... Could someone pleas show me what i need to do, This is the Python code i am working on...
def SpeedLimit ():
SpeedLimet = int(input("Enter Speed Limit: "))
return SpeedLimet
def DriverSpeed ():
DriverSpeed = int(input("Enter Driver Speed: "))
return DriverSpeed
def OverOrUnderSpeedLimit (number):
UnderSpeedLimet = False
if DriverSpeed(number) < int(50) ==0:
OverSpeedLimet = True
return SpeedLimet
def OverSpeedLimit (result):
if result == True:
print("You Are Over The Speed Limit")
else:
print("You Are On/Under Speed Limit")
def DemeritPoints ():
DemeritPointsGained = DriverSpeed - SpeedLimit
#Main Program
SpeedLimit()
DriverSpeed()
OverOrUnderSpeedLimit("number")
OverSpeedLimit("result")
DemeritPoints()
i am trying to make something that will ask...
"what is the speed limit"
"what speed is the car going"
...and then i want it to show me how many Demerit points you will get for speeding
e.g.
"You don't loose any Demerit points"
or
"You loose [number] meany Demerit points"
Thank you for your help :D
def DriverSpeed (): # No parameters here...
DriverSpeed = int(input("Enter Driver Speed: "))
return DriverSpeed
def OverOrUnderSpeedLimit (number):
UnderSpeedLimet = False
if DriverSpeed(number) < int(50) ==0: # you gave it a parameter here...
OverSpeedLimet = True
return SpeedLimet
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Ok I'm trying to make a program where I have a certain health and ammo for the alien and the human. I need them to go ten rounds. I want them to go the ten rounds randomly. I'm new to python, so I have some of it figured out but I don't have all of it figured out. I need to know what exactly am I doing wrong and how to do it.
class Alien(object):
"""Time to shoot the Player"""
def __init__(self,name,health,ammo):
self.name = name
name = input("What would you like to name your Alien?:")
self.health = 75
self.ammo = 50
def _str_(self):
return self.name
def blast(self,enemy):
import random
ammunition = random.randrange(5)
if ammunition >2
self.ammo(health)
print(self.name,"has shot the Player.")
print("He has",self.ammo,"ammo left.")
elif self.ammo == 0:
print(self.name,"is out of ammo.")
def health(self,health):
import random
shoot = random.randrange(10)
if shoot > 5
self.health(ammo)
if self.health >0:
print(self.name,"has been shot down. He has",self.health,"health left.")
elif self.health == 0
print("Im already dead. There's no way you can kill me again!!!")
class Player(object):
"""Time to shoot the Alien"""
def __init__(self,ammo,health,name):
self.name = name
name = input("What would you like to name your player?:")
self.ammo = 50
self.health = 75
def _str_(self):
return self.name
def blast(self,enemy):
import random
ammunition = random.randrange(5)
if ammuntion >2
self.ammo(health)
print (self.name,"has shot the alien.")
print ("He has",self.ammo,"ammo left.")
elif self.ammo == 0:
print(self.name,"is out of ammo.")
def health(self,health):
import random
shoot = random.randrange(10)
if shoot > 5
self.health(ammo)
if self.health >0:
print(self.name,"has been wounded. He has",self.health,"health left.")
elif self.health == 0:
print("I'm already dead. There's no way you can kill me again!!!")
These are my two classes for it.
I think i know what you are looking for. I remember writing a similar program for my sophomore school year and hope this helps.
class Player(object):
""" A player in a shooter game. """
def __init__(self,ammo):
self.ammo = ammo
self.lose = False
def blast(self, enemy):
if self.lose:
print "You were unsuccessful and did not kill the alien!\nNow the Earth was destroyed thanks to you."
else:
print "The player blasts an enemy."
if self.ammo > 0:
self.ammo -= 1
print "Your ammunition count is reduced by 1."
print "The alien took 1 damage! You've done it!\n"
enemy.die()
else:
if enemy.health == 0:
print "They're already dead, yo."
else:
self.lose = True
print "The alien has more health than you have ammo."
print "You run out of ammo and die!"
class Alien(object):
""" An alien in a shooter game. """
def __init__(self, health):
self.health = health
def die(self):
if self.health > 1:
self.health -= 1
print "Is that all you've got??\n"
elif self.health == 1:
self.health -= 1
print "Oh no im gonna die"
else:
print "The alien is already dead. What you're doing is unneccessary."
# main
print "\tThe Death of an Alien\n"
#same health and ammo
print "\n-----You have 6 counts of ammo.-----"
print "-----The alien has 6 health.-----\n"
hero = Player(6)
invader = Alien(6)
for i in range(6):
hero.blast(invader)
#lower health than ammo
print "\n-----You have 6 counts of ammo.-----"
print "-----The alien has 5 health.-----\n"
hero = Player(6)
invader = Alien(5)
for i in range(6):
hero.blast(invader)
#lower ammo than health
print "\n-----You have 5 counts of ammo.-----"
print "-----The alien has 6 health.-----\n"
hero = Player(5)
invader = Alien(6)
for i in range(6):
hero.blast(invader)
raw_input("\n\nPress the enter key to exit.")