So here's my code, and "name 'player' is not defined" pops up when playing the game. This is only a practice project so the entire code is attached. I've been trying to finish the code posted in 100 Days of Complete Python Pro Boot Camp, and got stuck on day 11. Someone plz help me XD.
......
def main():
player = [random.choice(cards), random.choice(cards)]
comp = [random.choice(cards), random.choice(cards)]
player_total = player[0] + player[1]
comp_total = comp[0] + comp[1]
ace_count = 0
ace_position = []
comp_ace = 0
comp_ace_position = []
no = False
print_deck(player, comp, player_total)
if player_total == 21:
print_final(player, comp, player_total, comp_total)
print("Win with a Blackjack 😎")
return
elif comp_total == 21:
print_final(player, comp, player_total, comp_total)
print("Lose, opponent has Blackjack 😱")
return
def deal():
global player, player_total, comp, comp_total, ace_count, ace_position, comp_ace, comp_ace_position, no
deal = input("Type 'y' to get another card, type 'n' to pass: ")
if deal == 'y':
new_card = random.choice(cards)
player.append(new_card)
player_total += new_card
if new_card == 11:
ace_count += 1
ace_position.append(len(player - 1))
while player_total > 21:
if ace_count > 0:
player_total -= 10
player[ace_position[0]] -= 10
ace_position.remove(ace_position[0])
else:
print_deck(player, comp, player_total)
comp_move()
print("You went over. You lose ðŸ˜")
break
print_deck(player, comp, player_total)
else:
comp_move()
if player_total == comp_total:
print("Draw 🙃")
elif player_total > comp_total:
print("You win 😃")
else:
print("You lose 😤")
no = True
......
This is to do with the scope of where player exist. Notice the nested function definition. - When you nest a function inside another all the local variable of the parent function are global of the child.
What you have done here is declared a global variable within deal() which is not needed, this raises the error as python is expecting a value to be assigned to that new global variable.
To fix: simply remove the variable that declares them all as globals.
p.s. I feel this may not be the best explanation feel free to ask questons.
Related
im new in Python and i'm self learner. Actually im trying to create easy word game.
Currently im in stage when im adding monster/player damage and I have three problems which i can't figure out.
I want every room to have a chance for a random monster to appear from "Monster" dictionary. However, after meeting a monster for the first time, the value of his life after the fight is overwritten in the dictionary. This causes the monster to have a negative life when you meet it again. How to fix it?
When i'll find monster in any room, I have set two options "run" and "fight". When someone will type any other command, the loop returns to the draw whether a monster or a chest will appear in the room. I want the return to occur until after the event is randomly selected
I have problem with placing command
if playerLife <= 0:
print("You died, your body will lay in chambers forever")
break
I want to end game immidiatly after players dead.
import random
from enum import Enum
playerDamage = 4
playerLife = 100
def find_aprox_value(value):
lowestValue = 0.9 * value
highestValue = 1.1 * value
return random.randint(lowestValue, highestValue)
def weapon_hit(chance):
if_hit = random.uniform(1, 100)
if if_hit < chance:
monsterLife[drawnMonster] = monsterLife[drawnMonster] - playerDamage
print("You hit a monster and you dealt 4 damage. It has", monsterLife[drawnMonster], " life")
else:
print("You missed")
def monster_hit():
global playerLife
monsterHit = monsterDamage[drawnMonster]
print("Monster did", monsterDamage[drawnMonster], "damage")
playerLife = playerLife - monsterHit
print("You have ", playerLife, "life")
Event = Enum('Event', ['Chest', 'Monster'])
Chest = Enum('Chest', {'greenChest': 'zielonÄ… skrzyniÄ™',
'blueChest': 'niebieskÄ… skrzyniÄ™',
'violetChest': 'fioletowÄ… skrzyniÄ™',
'orangeChest': 'pomarańczową skrzynię'
})
Monster = Enum('Monster', {'Rat': 'Szczura',
'Bat': 'Nietoperza',
'GiantSpider': 'Ogromnego PajÄ…ka',
'Wolf': 'Wilka',
})
Color = Enum('Color', ['greenChest', 'blueChest', 'violetChest', 'orangeChest'])
MonsterKind = Enum('MonsterKind', ['Rat', 'Bat', 'GiantSpider', 'Wolf'])
eventDictionary = {
Event.Chest: 0.4,
Event.Monster: 0.6
}
eventList = list(eventDictionary.keys())
eventProbability = list(eventDictionary.values())
chestDictionary = {
Chest.greenChest: 0.5,
Chest.blueChest: 0.3,
Chest.violetChest: 0.15,
Chest.orangeChest: 0.05
}
PremiumChestDictionary = {
Chest.blueChest: 0.5,
Chest.violetChest: 0.35,
Chest.orangeChest: 0.15
}
MonsterDictionary = {
Monster.Rat: 0.5,
Monster.Bat: 0.3,
Monster.GiantSpider: 0.15,
Monster.Wolf: 0.05
}
chestList = list(chestDictionary.keys())
chestProbability = list(chestDictionary.values())
MonsterList = list(MonsterDictionary.keys())
MonsterProbability = list(MonsterDictionary.values())
PremiumChestList = list(PremiumChestDictionary.keys())
PremiumChestProbability = list(PremiumChestDictionary.values())
colorValue = {
Chest.greenChest: 1000,
Chest.blueChest: 4000,
Chest.violetChest: 9000,
Chest.orangeChest: 16000
}
monsterLife = {
Monster.Rat: 5,
Monster.Bat: 10,
Monster.GiantSpider: 15,
Monster.Wolf: 30
}
monsterDamage = {
Monster.Rat: 3,
Monster.Bat: 5,
Monster.GiantSpider: 8,
Monster.Wolf: 12
}
gameLength = 10
Gold = 0
while gameLength > 0:
gameAnswer = input("Do you want to move forward? \n")
if gameAnswer == "yes":
print("Great, lets see what is inside")
drawnEvent = random.choices(eventList, eventProbability)[0]
if drawnEvent == Event.Chest:
drawnChest = random.choices(chestList, chestProbability)[0]
goldAcquire = find_aprox_value(colorValue[drawnChest])
print("You have find ", drawnChest.value, "inside was", goldAcquire, "gold")
Gold = Gold + goldAcquire
gameLength = gameLength - 1
elif drawnEvent == Event.Monster:
drawnMonster = random.choices(MonsterList, MonsterProbability)[0]
print("Oh no, you have find", drawnMonster.value, "which has", monsterLife[drawnMonster],
"life .If you will defeat him, you will find great treasure.")
eventAnswer = input(" What is your choice?(fight, run)")
if eventAnswer == "fight":
while monsterLife[drawnMonster] > 0:
weapon_hit(70)
if monsterLife[drawnMonster] > 0:
monster_hit()
if playerLife <= 0:
print("You died, your body will lay in chambers forever")
break
drawnPremiumChest = random.choices(PremiumChestList, PremiumChestProbability)[0]
goldAcquire = find_aprox_value(colorValue[drawnPremiumChest])
print("Congratulations, you have defeat a monster, and you found", drawnPremiumChest.value,
", inside was", goldAcquire, " gold")
Gold = Gold + goldAcquire
gameLength = gameLength - 1
elif eventAnswer == "run":
gameLength = gameLength - 1
print("you have successfully run")
else:
print("Only options is run or fight")
continue
else:
print("Your only options is move forward")
continue
print("Congratulations you have acquired", Gold, "gold")
As I mentioned at the beginning, I am just starting to learn python and this is my first post on this forum, so please be understanding and thank you for your help in advance.
There are many solutions to your problem (at least five). Here are the simplest:
The simplest: Instead of break, you can end the program with sys.exit (0) (with code 0 because it's not an error).
More elegant:
# Outer loop:
while gameLength > 0 and playerLife > 0:
# Inner loop:
while monsterLife[drawnMonster] > 0 and playerLife > 0:
# Statement 'if playerLife <= 0' becomes redundant
# Outside the loop:
if playerLife > 0:
print("Congratulations ...")
else:
print("You died, ...")
or:
# Outer loop:
while gameLength > 0 and playerLife > 0:
# Inner loop:
while monsterLife[drawnMonster] > 0:
if playerLife <= 0:
break
# Outside the loop:
if playerLife > 0:
print("Congratulations ...")
else:
print("You died, ...")
More advanced: instead of using break statement, an exception can be thrown. The exception must be handled by the try ... catch statement.
BTW: both continue statements are completely unnecessary - these are the last statements of the loop, so they don't change anything about the execution of the loop.
Have fun with Python.
I'm having an issue when trying to modify a variable in my script with a function.
def damage(x):
""" This function will determine the amount of damage you will take """
""" hit_c is the chance the enemy has to hit you """
from random import randint
global User_HP
global Enemy_HP
hit_c = randint(1,5)
User_damage = randint(1,4)
if hit_c >= 2:
Enemy_HP -= User_damage
lcd_print(textscroll(f"You dealt {User_damage} damage!"))
lcd_clear()
lcd_print(textscroll(f"The enemy has {Enemy_HP} HP")
sleep(1)
elif hit_c == 1:
lcd_print("You missed!")
if Enemy_HP <= 0:
pass
else:
hit_c = randint(1,5)
Enemy_damage = randint(1,3)
if hit_c >= 2:
User_HP -= Enemy_damage
lcd_print(textscroll(f"You took {Enemy_damage} damage!"))
lcd_clear()
lcd_print(User_HP)
elif hit_c == 1:
lcd_print(textscroll("The enemy missed!"))
The function won't read the global variable Enemy_HP when I try to modify it in this line.
Enemy_HP -= User_damage
note, I have defined Enemy_HP = 10 at the start of the script.
Help is much appreciated!
Error -
File "D:\Desktop\Python Scripts\Lab Project\Lab_Project_Functions.py", line 41, in damage
Enemy_HP -= User_damage
NameError: name 'Enemy_HP' is not defined`
EDIT:
Here is the full code sorry for not including this earlier, I'm also importing several functions
from time import sleep
from random import randint
from operator import itemgetter
from engi1020.arduino import *
User_HP = 10
Enemy_HP = 10
wait_1 = True
def loading(wait_time):
if wait_1 == True:
sleep(1)
lcd_clear()
lcd_print('.')
sleep(1)
lcd_clear()
lcd_print('..')
sleep(1)
lcd_clear()
lcd_print('...')
sleep(1)
lcd_clear()
lcd_print('.')
sleep(1)
lcd_clear()
lcd_print('..')
sleep(1)
lcd_clear()
lcd_print('...')
sleep(1)
lcd_clear()
inventory = []
from Lab_Project_Functions import *
#Get some basic gameplay information
lcd_print("starting the game")
lcd_clear()
loading(wait_1)
lcd_print(textscroll("Hello!, What speed would you like the dialogue to play at? ('slow, normal, fast')"))
Dia_Spd = input()
if Dia_Spd == "slow":
DiaSpd = 4
elif Dia_Spd == "normal":
DiaSpd = 3
elif Dia_Spd == "fast":
DiaSpd = 2
elif Dia_Spd == "test":
DiaSpd = 0
lcd_clear()
lcd_print()
loading(wait_1)
'''
name = input("What is your name?")
class_ = "Knight"
sleep(1)
class_ = input("Which class is befitting you young adventurer?"
" A noble 'Knight'?"
" A Studious 'Wizard'?"
" Or a Mystifying 'Warlock'?")
'''
loading(wait_1)
#lcd_print(f"What ho {class_} {name}, welcome to the game!!")
lcd_print(textscroll("What ho brave knight, welcome to the game!!"))
sleep(DiaSpd)
lcd_clear()
lcd_print(textscroll("Let's start with a some basics"))
sleep(DiaSpd)
lcd_clear()
#Start by creating a basic combat system.
lcd_print(textscroll("An enemy approaches you! Learn to fight!"))
sleep(DiaSpd)
lcd_clear()
#Create more combat elements.
while User_HP > 0:
lcd_print(textscroll("Pick a fighting option."))
lcd_print("FIGHT--ITEM--DEF")
fight_option = input()
if fight_option == 'FIGHT' or 'fight' or 'Fight':
damage(1)
elif fight_option == 'ITEM' or 'item' or 'Item':
item_pickup(1)
else:
defend(1)
if Enemy_HP <= 0:
lcd_print(textscroll("THE ENEMY WAS SLAIN!"))
break
sleep(DiaSpd)
lcd_print(textscroll("Good job you're learning the basics!"))
sleep(DiaSpd)
lcd_print(textscroll("To reward you for your efforts, here is an item that the enemy dropped!"))
sleep(DiaSpd)
item_pickup(1)
#remember to redefine enemy hp before next fight
lcd_print(textscroll("Hi ho yee noble knight, welcome to your humble abode. You can perform all sorts of actions here."))
sleep(DiaSpd)
lcd_clear()
lcd_print(textscroll("What would you like to do?"))
sleep(DiaSpd)
lcd_clear()
lcd_print(textscroll("Look through inventory----Rest (Heal)----Go adventuring"))
home_option = input() #change this to accept input from button & joystick
while True:
if home_option == 1:
pass
if home_option == 2:
pass
if home_option == 3:
pass
the function imports are from here
from engi1020.arduino import *
#Looting // Item Pickup Function def item_pickup(enemy_num):
""" This Function will determine the items the user picks up """
'''
enemy_num is the variable deciding which enemy you are fighting
'''
from random import randint
rand_item = randint(1,4)
global inventory
if enemy_num == 1:
if rand_item <= 3:
inventory.append('IRON_SWORD')
print(textscroll("You picked up the IRON SWORD!"))
elif rand_item == 4:
inventory.append('STEELY_VENGANCE')
lcd_print(textscroll("You found a rare item! 'STEELY VENGANCE' was added to your inventory!"))
else:
'no item found'
if enemy_num == 2:
pass
#Combat Function def damage(x):
""" This function will determine the amount of damage you will take """
""" hit_c is the chance the enemy has to hit you """
from random import randint
global User_HP
global Enemy_HP
hit_c = randint(1,5)
User_damage = randint(1,4)
if hit_c >= 2:
Enemy_HP -= User_damage
lcd_print(textscroll(f"You dealt {User_damage} damage!"))
lcd_clear()
lcd_print(textscroll(f"The enemy has {Enemy_HP} HP")
sleep(1)
elif hit_c == 1:
lcd_print("You missed!")
if Enemy_HP <= 0:
pass
else:
hit_c = randint(1,5)
Enemy_damage = randint(1,3)
if hit_c >= 2:
User_HP -= Enemy_damage
lcd_print(textscroll(f"You took {Enemy_damage} damage!"))
lcd_clear()
lcd_print(User_HP)
elif hit_c == 1:
lcd_print(textscroll("The enemy missed!"))
#Item Select Function def item_select(item_number):
from operator import itemgetter
while True:
lcd_print(textscroll("What item would you like to use?"))
lcd_clear()
sleep(1)
lcd_print(textscroll("note you need to select items numerically, i.e. 0, 1, 2, 3,...,etc. "))
lcd_clear()
sleep(1)
lcd_print(textscroll(inventory))
item_choice = int(input())
lcd_clear()
lcd_print("Which item?:")
num_items = len(inventory)
if item_choice < num_items:
item = itemgetter(item_choice)(inventory)
if item == potion:
global User_HP
User_HP += 5
lcd_print(User_HP)
break
else:
lcd_print(textscroll("ERROR! ITEM CHOICE IS AN INVALID OPTION!"))
#Defend Function def defend(User):
Enemy_damage = randint(1,3)
lcd_print(textscroll(f"The user blocked {Enemy_damage} damage"))
#Text Scrolling Function def textscroll(text):
from time import sleep
i = 0
j = 15
while True:
lcd_print(text[i:j])
i += 1
j += 1
sleep(0.2)
lcd_clear()
if j >= len(text) + 15:
break
The error you have is because you didn't assign a value to it (even tho you said):
exception NameError: Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.
Source: https://docs.python.org/3/library/exceptions.html#bltin-exceptions
The problem in your code is that you are trying to access variables from one file without importing them.
Global variables only exist inside the file they are defined.
Just import them like they were functions:
import Enemy_HP
I have just starting learning Python and I am writing a rudimentary Blackjack game. I have got the basic stuff working but I want to add a little bit of finesse here and there. I am looking for a way in which my introduction function at the beginning of my while loop is substituted for my new_round function.
My idea was that I could have a round counter running at the top which would dictate which function would run through and if/elif statement.
Suffice it to say, it doesn't work. Firstly, I would like to know why it doesn't and secondly would like a way to do it!
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
player_name = ''
playing = True
class Card:
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'{self.rank} of {self.suit}'
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = ''
for card in self.deck:
deck_comp += '\n '+card.__str__()
return 'The deck has:' + deck_comp
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self,card):
self.cards.append(card)
self.value += values[card.rank]
if card.rank == 'Ace':
self.aces += 1
def adjust_for_ace(self):
#if value of players hand is over 21 and includes an ace then the player will automatically have the ace value reduced to 1
#also track ace counter will revert to 0
while self.value > 21 and self.aces > 0:
self.value -= 10
self.aces -= 1
class Chips:
def __init__(self,total):
self.total = total
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
player_chips.bet = int(input('How many chips would you like to bet?: '))
except ValueError:
print('\nSorry, the number of chips must be a number!')
else:
if player_chips.bet > player_chips.total:
print(f"\nSorry guy, your bet can't exceed {player_chips.total} chips.")
else:
print(f"\nYour bet of {player_chips.bet} chips has been accepted - good luck!")
break
def introduction():
global player_name
print("\nWelcome to BlackJack! Get as close to 21 as you can without busting.\n\nThe Dealer will hit up to 17, Face cards count as 10 and Aces are 1/11.")
player_name=input("The first round is about to begin, what is your name friend?: ")
def next_round():
global player_name
print("Hey ho, let's go another round!")
def chip_count():
global player_name
print(f"{player_name}, your current chip count stands at {player_chips.total}")
def play_again():
global player_name
global playing
while True:
replay = input(f"{player_name}, would you like to play another round?: ").upper()
if replay[0] == 'Y':
return True
elif replay[0] == 'N':
print(f"\nThanks for playing - you leave the table with {player_chips.total} chips.")
break
else:
print("Sorry, I don't understand what you are saying, do you want to play the next round, or not? Y or N!: ")
continue
def total():
global player_name
while True:
try:
total = int(input(f'Hello {player_name}, how many chips will you be using this game?: '))
except ValueError:
print('\nSorry, the number of chips must be a number!')
else:
return total
print(f"\nWelcome to the table - you currently have {total} chips to play with.")
def hit(deck,hand):
#run the add card function within the Hand Class with the card argument being generated by the deal function within the Deck Class.
hand.add_card(deck.deal())
hand.adjust_for_ace()
def hit_or_stand(deck,hand):
global player_name
global playing
while True:
response = input(f"{player_name}, Would you like to hit or stand?: ")
if response[0].upper() == 'H':
hit(deck,hand)
elif response[0].upper() == 'S':
print(f"{player_name} stands. It is the Dealer's turn")
playing = False
else:
print("\nI can't understand what you are saying - are you hitting or standing?!")
continue
break
def show_some(player,dealer):
print("\nDealer's Hand:")
print("<card hidden>")
print(dealer.cards[1])
print("\nPlayer's Hand: ",*player.cards, sep='\n')
print("Value of your cards: ",player.value)
def show_all(player,dealer):
print("\nDealer's Hand: ",*dealer.cards, sep='\n')
print("Dealer's Hand = ",dealer.value)
print("\nPlayer's Hand: ",*player.cards, sep='\n')
print("Player's Hand = ",player.value)
def player_busts(player,dealer,chips):
global player_name
print(f"{player_name} busts!")
chips.lose_bet()
def player_wins(player,dealer,chips):
global player_name
print(f"{player_name} wins the round!")
chips.win_bet()
def dealer_busts(player,dealer,chips):
print("Dealer busts!")
chips.win_bet()
def dealer_wins(player,dealer,chips):
print("Dealer wins!")
chips.lose_bet()
def push(player,dealer,chips):
print("You have tied with the Dealer! It's a push, your chips have been refunded.")
############################################################################################################################################################
while True:
counter = 0
if counter > 0:
next_round()
elif counter == 0:
introduction()
#Create & shuffle the deck, deal 2 cards to each player.
deck = Deck()
deck.shuffle()
player_hand = Hand()
player_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand = Hand()
dealer_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
#Set up Player's chips
player_chips = Chips(total())
#Prompt the Player for their bet
take_bet(player_chips)
#Show cards (keep one dealer card hidden)
show_some(player_hand,dealer_hand)
while playing == True:
#Prompt for player hit or stand
hit_or_stand(deck,player_hand)
#show cards (keep one dealer card hidden)
show_some(player_hand,dealer_hand)
#if player's hand exceeds 21, player busts - break loop
if player_hand.value > 21:
player_busts(player_hand,dealer_hand,player_chips)
break
#if player hasn't bust, play dealer's hand until dealer reaches 17 or busts.
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck,dealer_hand)
#show all cards
show_all(player_hand,dealer_hand)
#run different winning scenarios
if dealer_hand.value > 21:
dealer_busts(player_hand,dealer_hand,player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand,dealer_hand,player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand,dealer_hand,player_chips)
else:
push(player_hand,dealer_hand,player_chips)
#inform player of their current chip count.
chip_count()
counter += 1
#play another round?
if play_again() == True:
continue
else:
break
You are resetting counter to 0 at the start of every loop.
You probably meant to set it to 0 before the loop started, then have it increase every loop.
Instead of:
while True:
counter = 0
if counter > 0:
try:
counter = 0
while True:
if counter > 0:
The issue in your code is that each time you loop through your While True: loop, you are setting the variable counter back to zero.... So even though you increment counter at the end of your loop, it is then immediately set back to zero as the loop restarts.
A different way to accomplish what you are looking for would be to run your introduction() function just before your While True: loop, and then edit the final lines of your code to call the next_round() function, as such:
if play_again() == True:
next_round()
continue
I'm trying to call a class function player.Decide() in another function where it wasn't declared. Im getting the error 'player is not defined. How would I go about fixing this?
def BattleLogic():
global enemy, enemy_race, name, level, strength, dexterity, cunning, enemy_speed, player_speed, type_speed
global move, turn, prefix
if enemy in ['deer']:
enemy_race = 'animal'
if enemy_race == 'animal':
chance = random.randint(1,1000)
if chance <= 10:
prefix = 'crippled'
elif chance > 10 and chance <= 50:
prefix = 'old'
elif chance >50 and chance <= 250:
prefix = 'young'
elif chance > 250 and chance <= 750:
prefix = None
elif chance > 750 and chance <= 950:
prefix = 'strong'
elif chance > 950 and chance <= 990:
prefix = 'alpha'
elif chance > 990 and chance <= 999:
prefix = 'possessed'
elif chance == 1000:
prefix = '*CONVERTED*'
else:
prefix = 'error'
opponent = Enemy(str(prefix),str(enemy),str(enemy_race))
player = Player(str(name),level,strength,dexterity,cunning)
player.Initiative()
opponent.Initiative()
if enemy_speed > player_speed:
move = 0
elif player_speed > enemy_speed:
move = 1
else:
move = random.randint(0,1)
turn = 0
Battle()
def Battle():
global turn, move, prefix, enemy, type_speed, enemy_title
if turn == 0:
print('\n\n')
if prefix == None:
enemy_title = enemy.capitalize()
else:
enemy_title = prefix.capitalize()+' '+enemy.capitalize()
SlowPrint('A '+enemy_title+' gets into position for battle',type_speed,0.5)
if move == 1:
SlowPrint(enemy_title+' makes the first move',type_speed,0.25)
else:
SlowPrint('You make the first move',type_speed,0.25)
if move == 0:
turn += 1
move = 1
player.Decide()
else:
turn += 1
move = 0
opponent.Decide()
Just pass a player object into the function. The you are free to use player.Decide().
The major problems with your coding, which is my personal opinion, is that you do not have the habit of passing something into the function, which as a result forces you to declare too many global variables.
A simple example (in your case, you want the object to be a player)
def Battle(obj):
return obj.Decide()
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.