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 1 year ago.
Improve this question
Basically, the assignment is to create code that will allow a game to run.
the code that I have written is:
class Character(object):
def __init__(self, name, health):
self.name = name
self.health = health
def take_damage(self, damage):
self.damage = damage
self.health = self.health - damage
return self.health
def __str__():
return self.name, "(health = " + self.health + ")"
class Hero(Character):
def __init__(self, name, health):
super().__init__(name, health)
self.__inventory = list()
def restore_health(self, heal):
self.heal = heal
self.health = self.health + heal
def add_inventory(self, inventory):
self.__inventory.append(inventory)
def remove_inventory(self, inventory):
self.__inventory.remove(inventory)
def get_inventory(self, inventory):
return self.__inventory
class Enemy(Character):
def __init__(self, name, health, damage):
super().__init__(name, health)
self.damage = damage
def main():
han = 'Han'
zombie = 'Zombie'
werewolf = 'Werewolf'
print(Hero(han, 40))
print(Enemy('Zombie', 20, 15))
print(Enemy('Werewolf', 15, 10))
if __name__ == '__main__':
main()
For reference, the code that of the game is this, but I know there's nothing wrong with it:
HW9 is the title of my code seen above
from HW9 import *
import random
def check_for_health_elixir(hero):
random_chance = random.randint(0,5)
if random_chance == 5:
health_amt = random.randint(2,5)
print("You have found a health elixir.")
print("Drinking it restores your health by " \
+ str(health_amt) + ".")
hero.restore_health(health_amt)
print("Your current health is " + str(hero.health) + ".\n")
def run(hero, enemy):
damage = random.randint(0, enemy.damage//2)
print("The " + enemy.name + " inflicted a damage of " \
+ str(damage) + " as you ran away.")
health = hero.take_damage(damage)
print("Your current health is " + str(health) + ".\n")
def fight(hero, enemy):
winner = random.randint(0,1)
if winner == 0:
print("You have defeated the " + enemy.name + ".")
else:
print("You have lost the fight. The " \
+ enemy.name \
+ " has inflicted a damage of " \
+ str(enemy.damage) + ".")
health = hero.take_damage(enemy.damage)
print("Your current health is " + str(hero.health) + ".\n")
def main():
hero = Hero('Elsa', 40)
goblin = Enemy('Goblin', 10, 5)
dragon = Enemy('Dragon', 30, 10)
ogre = Enemy('Ogre', 20, 8)
wizard = Enemy('Wizard', 20, 10)
enemies = {goblin, dragon, ogre, wizard}
print("You are the hero " + hero.name + ". Your current health is " \
+ str(hero.health) + ".\n")
game_over = False
while not game_over:
health = check_for_health_elixir(hero)
enemy = random.sample(enemies, 1)[0]
print("You have encountered a " + enemy.name + ".")
action = input("Do you want to run or fight? ").strip()
while action != "run" and action != "fight":
action = input("Do you want to run or fight?").strip()
if action == "run":
run(hero, enemy)
elif action == "fight":
fight(hero, enemy)
if hero.health <= 0:
print("You are dead!\nGame over.")
game_over = True
if __name__ == '__main__':
main()
What my code is supposed to print out is:
Start:
Han (health=40)
Zombie (health=20)
Warewolf (health=15)
Battle 1:
Han (health=30)
Warewolf (health=5)
Battle 2:
Han (health=15)
Zombie (health=0)
Restore Health:
Han (health=20)
Inventory:['gold coin', ‘candle']
The problem I am encountering is that it says:
print(Hero(han, 40))
TypeError: __str__() takes 0 positional arguments but 1 was given
This comes from the def main() at the end of my code, but I'm not sure what I'm doing wrong, there's still more code to write in but I want to figure out what I'm doing wrong here first.
The issue is that you forgot to add the self argument in your _str_ function. All functions not marked as #staticmethod
in classes must have the self argument. So to correct it, you just need to change it to:
def __str__(self):
Related
I am trying to make it so that the user can input the name of another pokemon class so that I can use the attack function. Is there any way I could do this from user input? It seems as though even when I put in a valid name it returns an error. I would love to know as to how I can do this so that I can finish my game.
import random
class Pokemon(object):
def __init__(self, name, level, pokemon_type, max_health, current_health, is_knocked_out):
self.name = name
self.level = level
self.pokemon_type = pokemon_type
self.current_health = current_health
self.max_health = max_health
self.is_knocked_out = is_knocked_out
#knock out function
def knock_out(self):
self.is_knocked_out = True
print(self.name + " is now knocked out")
#lose health func, takes in one parameter which is damage
def lose_health(self, amount):
if amount > self.current_health:
print(self.name + " has been knocked out and now has 0 hp")
self.current_health = 0
self.is_knocked_out = True
else:
self.current_health -= amount
print(self.name + " now has " + str(self.current_health) + " HP")
#hp regen function, takes in one parameter which is the amount of hp to be regained, wont allow you to go above the max
def regain_health(self, amount):
if amount > self.max_health:
print("You cannot heal past your max HP")
else:
self.current_health += amount
print(self.current_health)
#function to revive dead mons
def revive(self):
if self.is_knocked_out == True:
self.is_knocked_out = False
print(self.name + " has been revived and half of his hp has been restored!")
self.current_health = self.max_health / 2
else:
print("This pokemon is still alive ")
return
#attack function, in progress
def attack(self, pokemon_name, move_number):
if self.current_health > 0 and self.is_knocked_out == False:
if move_number == 1:
pokemon_name.lose_health(random.randint(1,150)) #Here is where the issue is, how can I make user input determine the name of the pokemon which is being attacked and sequentially make it lose HP?
print(pokemon_name + " was attacked")
elif move_number == 2:
pass
elif move_number == 3:
pass
elif move_number == 4:
pass
else:
print("You are knocked out!")
Lucario = Pokemon("Lucario", 12, "fighting", 200, 200, False)
Blastoise = Pokemon("Blastoise", 12, "water", 200,200, False)
Blastoise.attack("Lucario", 1)
just use:
if move_number == 1:
globals()[pokemon_name]
what is globals()? it's a built-in function that load all global variable (predefined or user-defined), it's a dictionary
data = 5
globals()["data"]
every variable you defined, it will be added to globals() as
globals()[name] = value
def attack(self, pokemon, move_number):
if self.current_health > 0 and self.is_knocked_out == False:
if move_number == 1:
pokemon.lose_health(random.randint(1,150)) #Here is where the issue is, how can I make user input determine the name of the pokemon which is being attacked and sequentially make it lose HP?
print(pokemon.name + " was attacked")
elif move_number == 2:
pass
elif move_number == 3:
pass
elif move_number == 4:
pass
else:
print("You are knocked out!")
Characters = dict()
Characters["Lucario"] = Pokemon("Lucario", 12, "fighting", 200, 200, False)
Characters["Blastoise"] = Pokemon("Blastoise", 12, "water", 200,200, False)
Characters["Blastoise"].attack(Characters["Lucario"], 1)
you also can use dictionary. what is dictionary? a dictionary is a collection of named variable, like list, but you can add to it by name...
how to define dictionary?
Characters = dict()
and add your variables:
Characters["<name>"] = value
like:
Characters["Blastoise"] = Pokemon("Blastoise", 12, "water", 200,200, False)
and use variables:
Characters["<name>"].<your-method>
like:
Characters["Blastoise"].attack(Characters["Lucario"], 1)
just one point: if you use dictionary, so you send variable (Pokemon object, not it's name), so attack's second parameter is pokemon and use:
print(pokemon.name + " was attacked")
This question already has answers here:
How to sort a list of objects based on an attribute of the objects in descending order?
(9 answers)
Closed 2 years ago.
Yes, I have looked at other posts but I am still a bit confused, some use lambda or make multiple methods and I am confused.
I have this class, and I want to create multiple instances (members of the team) and before I call my function to start a fight, I want to arrange a list so that the person with the highest self.full_speed goes first, etc. (I have a full_speed and speed attributes for debuffs/buffs)
class Player:
"""Describes the main player."""
def __init__(self, level, health, will, speed):
"""Initializes stats"""
self.level = level
self.health = health
self.full_health = health
self.will = will
self.full_will = will
self._cheat = "cheat" # Protected instance attribute has a leading underscore
# Private starts with two leading underscores
self.speed = speed
self.full_speed = speed
def level_up(self, skill):
"""Choose where to distribute skill points."""
pass
def default_attack(self, enemy):
"""Normal attack that damages enemy target."""
damage = 0
if random.randint(1,100) <= 95:
damage = (self.level * 2)
critical_hit = random.randint(1,10)
if critical_hit == 1:
damage += int(self.level * 0.5)
print("Critical hit!")
enemy.health -= damage
print("The enemy took " + str(damage) + " damage.")
def special_attack(self, enemy):
"""Deals more damage but uses will, more likely to miss."""
damage = 0
if random.randint(1,100) <= 90:
damage = (self.level * 3)
critical_hit = random.randint(1, 10)
if critical_hit == 1:
damage += self.level
print("Critical hit!")
enemy.health -= damage
self.will -= 2
print("The enemy took " + str(damage) + " damage.")
def heal(self):
"""Heals self by 10%."""
self.will -= 2
recovered = int(self.full_health * 0.10)
self.health += recovered
if self.health > self.full_health:
self.health = self.full_health
print("Recovered " + str(recovered) + " HP.")
I've started here but I am unsure where to go at this point..
def team_by_speed(team):
new_team = []
for member in team:
# member.full_speed
return new_team
Used Sorted() function
Call sorted(iterable, key: NoneType=None) with a list of objects as iterable
I'm following a Python course on Udemy.com and we are practicing Python by building an RPG game. So far the game was working fine for a single player but as soon as we added 3 players the game seems to just get stuck after executing all 3 players attacks.
The concept is that there are 3 players or so, as the game starts the player stats are shown, after all the players have attacked each other this includes the enemy as well, the player stats are printed as shown below in the picture and the game asks for input from all the three players again, but it's just running once as shown below in the picture.
I followed the code for word to word and also posted a question regarding it. So I thought I should try StackoverFlow.
Below is my code kindly see why is it not going in loop as it should.
Mainfile
# -*- coding: utf-8 -*-
from game_class.invin import Item
from game_class.game import player
from game_class.magic import Spell
import time
# Player and Enemies magic create
Fire_Shot = Spell('Fire Shot', 10, 45, "Black Magic")
Thunder_Storm = Spell("Thunder Storm",25,65,"Black Magic")
Ninja_Summon = Spell("Ninja Summon",45,75,"Ninjustu")
The_End = Spell("THE END",80,300,"Finisher")
Heal = Spell("HEAL ME",60,140,'Heal')
player_magic = [Fire_Shot,Thunder_Storm,Ninja_Summon,Heal,The_End]
enemy_magic = [
{'Name': "Big Punch", 'cost': 30, "DMG": 45},
{'Name': "Slap", 'cost': 15, "DMG": 25},
{'Name': "Rock Throw", 'cost': 20, "DMG": 30},
{'Name': "Kick", 'cost': 45, "DMG": 60}
]
boss_magic = [
{'Name': "STORM", 'cost': 10, "DMG": 45},
{'Name': "DARK BACK-BITTING", 'cost': 10, "DMG": 25},
{'Name': "D.D.T", 'cost': 10, "DMG": 30}
]
# Items create
potion = Item("Potion", 'Potion', 'Heals for 50 HP', 50)
high_potion = Item("Potion+", 'Potion', 'Heals for 120 HP', 120)
super_potion = Item("Ultra Potion", 'Potion', 'Heal for 250 HP', 250)
elixir = Item("Elixir", 'Elixir', 'Give 1 EVERYTHING BACK', 9000)
high_elixir = Item("Omega Elixir", 'Elixir', 'Give all EVERYTHING BACK', 9000)
bomb = Item("Bomb",'Attack','Deals 350 Damage',350)
player_items = [ {"item":potion,"quantity":3},
{'item':high_potion,"quantity":2}
,{"item":super_potion,"quantity":1}
,{'item':elixir,"quantity":2}
,{'item':high_elixir,"quantity":1}
,{"item": bomb, "quantity": 2} ]
# PLAYER CREATE
Player1 = player('Night Man ',1000, 100, 145, 140, player_magic, player_items)
Player2 = player('Ray Wills ', 1000, 100, 155, 135, player_magic, player_items)
Player3 = player("Randy Orton",1000, 100, 150, 120, player_magic, player_items)
Enemy1 = player("Door Keeper",1500, 200, 250, 150, enemy_magic, None)
BOSS = player("Boss Man",1200, 200, 45, 300, boss_magic, None)
players = [Player1,Player2,Player3]
# Game starts
run = True
i = 1
while run is True:
print ("=======================================")
print("\n\n")
print(" NAME HP MP\n")
for player in players:
player.get_stats()
for player in players:
print("\n")
player.chose_action()
print("=========\n")
print (player.name)
print ("=============")
choice = input("CHOSE ACTION: ")
index = int(choice) - 1
if index == 0:
dmg = player.gen_dmg()
Enemy1.get_dmg(dmg)
print(player.name+ " attacked for " + str(dmg) + " damage points")
elif index == 1:
player.chose_magic()
magic_choice = (int(input("Chose Spell: ")) - 1)
spell = player.magic[magic_choice]
magic_dmg = spell.gen_spell_dmg()
current_mp = player.get_mp()
if magic_choice == -1:
continue
if spell.cost > current_mp:
print ("\nNOT ENOUGH MANA")
continue
if spell.stype == "Heal":
player.heal(magic_dmg)
print (str(magic_dmg) +' HP restored')
print("Remaining Magic Points: " + str(player.get_mp()) +
"/" + str(player.get_max_mp()))
elif spell.stype == "Black Magic" or spell.stype == "Ninjustu" or spell.stype == "Finisher":
player.reduce_mp(spell.cost)
Enemy1.get_dmg(magic_dmg)
print (str(spell.name) + ' did damage of '+ str(magic_dmg) +" points")
print ("Remaining Magic Points: " + str(player.get_mp()) +"/" +str(player.get_max_mp()))
elif index == 2:
player.chose_item()
item_choice = (int(input("Chose Spell: ")) - 1)
if item_choice == -1:
continue
item = player.items[item_choice]['item']
if player.items[item_choice]['quantity'] == 0:
print("No Item...")
continue
player.items[item_choice]['quantity'] -= 1
if item.itype == 'Potion':
player.heal(item.prop)
print("\n"+ str(item.name) + " used and healed for "+ str(item.prop) + " HP")
elif item.itype == "Elixir":
player.hp = Player1.maxhp
player.mp = Player1.maxmp
print ("\n"+"STATS RESTORED BECASUE OF " +str(item.name))
elif item.itype == "Attack":
Enemy1.get_dmg(item.prop)
print ("You used a Bomb & that dealt damage of: " + str(item.prop))
enemy_choice = 1
enemy_dmg = Enemy1.gen_dmg()
Player1.get_dmg(enemy_dmg)
print("========================================")
print("\n")
print ("ENEMY ATTACKED YOU FOR " + str(enemy_dmg) + " POINTS")
print ("ENEMY HP: "+str(Enemy1.get_hp()) +'/'+ str(Enemy1.get_maxhp()))
if Enemy1.get_hp() == 0:
print('')
print ('ENEMY DEAD')
run = False
elif Player1.get_hp() == 0:
print('')
print('YOU DIED')
run = False
elif index == 3:
print("Arigato Gozaimasu for playing")
time.sleep(1)
print ("BYE BYE")
run = False
invin.py
class Item:
def __init__(self, name,itype,desc,prop):
self.name = name
self.itype = itype
self.desc = desc
self.prop = prop
magic.py
import random
class Spell():
def __init__(self, name, cost,dmg,stype):
self.name = name
self.cost = cost
self.dmg = dmg
self.stype = stype
def gen_spell_dmg(self):
low = self.dmg - 15
high = self.dmg + 10
return random.randrange(low,high)
game.py
# -*- coding: utf-8 -*-
from .magic import Spell
import random
class player:
def __init__(self,name, hp , mp , atk ,df ,magic,items):
self.hp = hp
self.name = name
self.items = items
self.mp = mp
self.magic = magic
self.df = df
self.maxhp = hp
self.atkH = atk + 25
self.atkL= atk - 10
self.actions=['Attack',"Magic","Items"]
self.maxmp = mp + 10
def gen_dmg(self):
return random.randrange(self.atkL,self.atkH)
def get_dmg(self,dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_maxhp(self):
return self.maxhp
def get_max_mp(self):
return self.maxmp
def get_mp(self):
return self.mp
def reduce_mp(self,cost):
self.mp -= cost
def spell_cost(self, i):
return self.magic[i]["cost"]
def chose_action(self):
print ("Actions")
print ("===========")
i = 1
for item in self.actions:
print(" " + str(i)+":" + str(item))
i += 1
def chose_magic(self):
print ("Spells")
print ("===========")
i = 1
for spell in self.magic:
print (" " + str(i) + ": " + str(spell.name) + str( " (Cost: " + str ( spell.cost ) +")" ) )
#the 3rd str helps to print it without the brackets
i += 1
def chose_item(self):
print ("Items")
print ("===========")
i = 1
for item in self.items:
print(" " + str(i) + ": " +
str(item['item'].name) + str(" (" + str(item['item'].desc) + ") ") + " (x"+str(item['quantity'])+")")
#the 3rd str helps to print it without the brackets
i += 1
def heal(self,dmg):
self.hp += dmg
def get_stats(self):
hp_bar = ''
bar_ticks = ( (self.hp/self.maxhp) * 100 ) / 4
mp_bar = ''
mp_bar_ticks = ( (self.mp/self.maxmp) * 100 ) / 10
while bar_ticks > 0:
hp_bar += '█'
bar_ticks -= 1
while len(hp_bar) < 25:
hp_bar = " "
while mp_bar_ticks > 0:
mp_bar += '▒'
mp_bar_ticks -= 1
while len(mp_bar) < 10:
mp_bar = " "
hp_string = str(self.hp) + "/"+str(self.maxhp)
current_hp = ''
if len(hp_string) < 9:
decreased = 9 - len(hp_string)
while decreased > 0:
current_hp += ' '
decreased -= 1
current_hp += hp_string
else:
current_hp = hp_string
mp_string = str(self.mp) +"/"+str(self.maxmp)
current_mp = ''
if len(mp_string) < 9:
mp_decreased = 9 - len(mp_string)
while mp_decreased > 0:
current_mp += ' '
mp_decreased -= 1
current_mp += mp_string
else:
current_mp = mp_string
print(" _________________________ __________")
print(str(self.name) + " " + str(hp_string) +
" |"+ hp_bar+"| " + str(mp_string) + " |"+mp_bar+"|")
The game is an RPG replica and it works by using while loop.
Each player gets a turn and then the player stats are shown after all 3 players have attacked.
This is how the loop should show player stats after all 3 players attacked
But I'm getting this
If we compare the "This is how the loop should show player stats after all 3 players attacked" and "But I'm getting this" screenshots, we can see, by looking at the code, that the issue is caused on the second run of player.get_stats(). This method is defined in the game.py file.
Inside the method we can see the following 2 lines of code:
while len(hp_bar) < 25:
hp_bar = " "
If the while-loop ever gets to run, it will be stuck forever. This is because if len(hp_bar) < 25 is True, the code does hp_bar = " ", which in turns makes len(hp_bar) to be equal to 1 now. This now gets the while loop to check if len(hp_bar) < 25 again, which returns True (as len(hp_bar) is 1) so the while-loop runs again. This creates an endless loop.
The title is terrible, but hopefully I can explain in my post. Creating a little game as my pet project for python, and I'm currently creating the inventory. Everything was... ok when developing the game until it came to making the function that will show all of the player's inventory.
elif (prompt == "examine"):
print(inventory[1].name)
gameprompt()
Ok, so I created a list that basically has a bunch of classes from Items in it. To call on the name element of these classes I have to do something like this, otherwise I just get its memory location which is largely useless to the player. I've tried
elif (prompt == "examine"):
print(inventory[].name)
gameprompt()
Thought that this above example would print only the name of all the Item objects, but there's a compilation error instead because I didn't specify which one. So I then tried~
elif (prompt == "examine"):
print(inventory[1:1000].name)
gameprompt()
Thinking that it would print all of the Item objects names up to 1000, but I obviously don't have that so I thought it would print the names up to the latest object that was there and stop but there was another compilation error from this...
If there is anyway to print out an element of a class for all class objects in a list please let me know. The full code of this game is here, although I don't think you'll need it to help me solve my problem (it is also very large.)
playername = input("What is your name?")
zone = 1
movement = 0
restcounter = 0
searchcounter = 0
class Player:
def __init__(self, name, hp, mp, atk, xp, dodgerate, atkrate):
self.name = playername
self.hp = hp
self.mp = mp
self.atk = atk
self.xp = xp
self.dodgerate = dodgerate
self.atkrate = atkrate
class Enemy(Player):
def __init__(self, name, gold, maxhp, hp, mp, atk, xp):
self.name = name
self.gold = gold
self.maxhp = maxhp
self.hp = hp
self.mp = mp
self.atk = atk
self.xp = xp
class Items:
def __init__(self, name, quantity, description, price, weight):
self.name = name
self.quantity = quantity
self.description = description
self.price = price
self.weight = weight
Player = Player(playername, 1, 1, 1, 1, 25, 3)
print(Player.name + " has been created. ")
def raceselection():
raceinput = input("Do you float towards the TEMPLE, CAVE or FOREST?")
if raceinput == "TEMPLE":
print("You are now a high elf. High elves utlize a lot of magical power at the cost of being very frail.")
Player.hp = Player.hp + 24
Player.mp = Player.mp + 100
Player.atk = Player.atk + 50
print("You awaken from your slumber. Your room's walls are gold plated, and you rested on a flat board.")
print("Out the door, you see many elves with robes praying to some goddess.")
print("You walk out of your door and into the praying area. You are immediately greeted by a tall man.")
elif raceinput == "CAVE":
print("You are now an orc.")
Player.hp = Player.hp + 1000
Player.mp = Player.mp + 15
Player.atk = Player.atk + 50
print("cave")
elif raceinput == "FOREST":
print("You are now a human.")
Player.hp = Player.hp + 50
Player.mp = Player.mp + 25
Player.atk = Player.atk + 25
else:
print("You can't float there!")
raceselection()
raceselection()
inventory = []
def gameprompt():
global inventory
global zone
global movement
global restcounter
global searchcounter
if (movement == 5):
movement = movement - movement
zone = zone + 1
print("You have advanced to zone",zone,"!!!")
gameprompt()
if (zone == 1):
print("Welcome to the first zone! Easy enemies are here with not very good loot./fix grammar, add description of zone/")
elif (zone == 2):
print("Hey, it actually travelled to the second zone, awesome!")
elif (zone == 3):
print("No way would this actually work!")
prompt = input("Would you like to walk, search or rest?: ")
if (prompt == "walk"):
encounterchance = random.randint(1, 3)
if (encounterchance == 2):
if (zone == 1):
mobspawnrate = random.randint(1,3)
if (mobspawnrate == 1):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
elif (mobspawnrate == 2):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
elif (mobspawnrate == 3):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
else:
movement = movement + 1
print("You have walked a step. You are now at ",movement," steps")
gameprompt()
elif (prompt == "search"):
if (searchcounter == 3):
print("You cannot search this area anymore! Wait until you reach the next zone!")
gameprompt()
else:
searchchance = random.randint(1, 5)
if (searchchance == 1 or 2 or 3 or 4):
searchcounter = searchcounter + 1
print(searchcounter)
print("You have found something!")
searchchance = random.randint(1,4)
if (searchchance == 1 or 2):
inventory.append(Items("Old Boot", 1, "An old smelly boot. It's a mystery as to who it belongs to...", 5, 50))
print("You have found a Boot!")
print(inventory)
elif(searchchance == 3):
inventory.append(Items("Shiny Boot", 1, "Looks like a boot that was lightly worn. You could still wear this.", 5, 50))
print(inventory)
print("You have found a Shiny Boot!")
elif(searchchance == 4):
inventory.append(Items("Golden Boot", 1, "It's too heavy to wear, but it looks like it could sell for a fortune!", 5, 50))
print("You have found a Golden Boot?")
print(inventory)
else:
searchcounter = searchcounter + 1
print(searchcounter)
print("You did not find anything of value")
gameprompt()
elif (prompt == "rest"):
if (restcounter == 1):
print("Wait until you reach the next zone to rest again!")
gameprompt()
else:
# Add a MaxHP value to the player later, and the command rest will give 25% of that HP back.
Player.hp = Player.hp + (Player.hp / 5)
print("You have restored ",(Player.hp / 5)," hit points!")
restcounter = restcounter + 1
gameprompt()
elif (prompt == "examine"):
print(inventory[1].name)
gameprompt()
gameprompt()
A list comprehension or map would work perfectly here:
print([item.name for item in inventory])
The comprehension iterates the list, and "replaces" each element in the list with whatever the part before for evaluates to. In this case, it's item.name.
° It actually doesn't replace the element in the original list. It evaluates to a new list full of replaced items.
So I have to create a game of craps that takes into account bets for an assignment. So far, my code works in that the dice rolls are correct and other little tidbits the assignment called for. But now I don't know how to record each game as a win / lose for the player or computer so that the pot can be added to the winner's money. I realize that my code is half doe, isn't finished, and doesn't run as is, but I just seriously need some help from someone. Please and thank you. Here are more specific directions on my assignment:
http://www.ics.uci.edu/~kay/courses/i42/hw/labA.html
import random
def craps():
print("Welcome to Sky Masterson's Craps Game")
handle_commands()
def handle_commands(): # Collection -> Collection (plus interaction)
""" Display menu to user, accept and process commands
"""
playerInitial = 500
compInitial = 500
MENU = "How much would you like to bet?: "
while True:
bet = float(input(MENU))
if bet <= playerInitial:
human_game()
elif bet > playerInitial:
print("Sorry, you can't bet more than you have")
def handle_commands2():
MENU2 = "Would you like to play again? (y or n): "
while True:
response = input (MENU2)
if response=="y":
counter = counter + multipleGames()
elif response=="n":
while ( counter < 2000):
roll = random.randint(1, 6) + random.randint(1,6)
updateCount(roll)
counter += 1
print ("Thank you for playing." + "\n" + "\n" + "Distribution of dice rolls: " + "\n")
return
else:
invalid_command(response)
def invalid_command(reponse):
"""print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
def play_game():
"""prints shooters roll results
"""
diceRoll = 0
roll = random.randint(1, 6) + random.randint(1, 6)
updateCount(roll)
diceRoll = diceRoll + 1
point = 0
print("The roll is " + str(roll))
response = (roll)
if response== 7 or response== 11:
print("Natural; shooter wins" + "\n" + "Thank you for playing")
handle_commands2()
elif response== 2 or response== 3 or response== 12:
print("Crapped out; shooter loses" + "\n" + "Thank you for playing")
handle_commands2()
else:
print("The point is " + str(roll))
point = roll
secondRoll = 0
handle_commands()
while (secondRoll !=point) and (secondRoll != 7):
secondRoll = random.randint(1, 6) + random.randint(1, 6)
updateCount(secondRoll)
diceRoll += 1
print("The roll is " + str(secondRoll))
handle_commands()
if secondRoll== point:
print ("Made the point; shooter wins." + "\n" + "Thank you for playing")
handle_commands2()
elif (secondRoll == 7):
print ("Crapped out; shooter loses." + "\n" + "Thank you for playing")
handle_commands2()
return diceRoll
def multipleGames():
gameCounter = 0
while (gameCounter <= 2000):
print("Your game: ")
gameCounter += play_game()
print("\n")
print("Computer's game: ")
gameCounter += play_game()
print( "\n")
return gameCounter
def updateCount(point):
count =List[point] + 1
List[point] = count
List = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
def human_game():
playerInitial = 500
compInitial = 500
while True:
play_game()
if
playerInitial += bet
compInitial += bet
counter = 0
counter = counter + multipleGames()
playerInitial -= bet
craps()
for point in List:
print("%2d" %(point) + ": " + "%3d" %(List[point]) + " " + "(" + ("%2d" % (int((List[point])/2000*100)))+ "%" + ")" + " " + ("*" *(int((List[point])/2000*100))))
Use classes:
import random
class Human:
def __init__(self):
self.name = 'Human'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Computer:
def __init__(self):
self.name = 'Computer'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Game:
def __init__(self):
self.rolls = []
self.currentPlayer = None
def roll(self):
self.rolls.append(random.randint(1, 6))
if __name__ == '__main__':
human = Human()
computer = Computer()
game = Game()
game.roll()
print games.rolls
I won't code all of it for you, but using classes will make things much simpler.