New to Python programming, could somebody please explain the fault with this program?
I am very new to Python programming, I am writing a simple fighting game at the moment (text based) that is extremely simple as I'm just learning the basics at the moment. I have placed the code for my game below (it is not finished), my problem is that 开发者_运维技巧every time I run the program, when you enter which character you'd like to play as this error occurs.
Traceback (most recent call last):
File "C:\Python26\combat.py", line 60, in <module>
first_player.attack(second_player)
TypeError: 'int' object is not callable
Here is the code for my game (don't worry it's not very big!).
import time
import random
class player(object):
def __init__(self, name):
self.account = name
self.health = random.randint(50,100)
self.attack = random.randint(30,40)
self.alive = True
def __str__(self):
if self.alive:
return "%s (%i health, %i attack)" % (self.account, self.health, self.attack)
else:
return self.account, "is dead!"
def attack(self, enemy):
print self.account, "attacks", enemy.account, "with %s attack!" % self.attack
enemy.health -= self.attack
if enemy.health <= 0:
enemy.die()
def die(self):
print self.account, "dies!"
alive_players = 2
name1 = raw_input("Enter a name: ")
name2 = raw_input("Enter another name: ")
player_list = {"a":player(name1), "b":player(name2)}
while alive_players == 2:
print
for player_name in sorted(player_list.keys()):
print player_name, player_list[player_name]
print
player1 = raw_input("Who would you like to play as? (a/b): ").lower()
try:
first_player=player_list[player1]
except KeyError, wrong_name:
print wrong_name, "does not exist!"
continue
if first_player==player(name1):
second_player=player(name2)
else:
second_player=player(name1)
time.sleep(1)
print
print "*" * 30
first_player.attack(second_player)
second_player.attack(first_player)
I know There are workarounds like appending the characters to the list AFTER the player picks the names, although I would like to have a further understanding of classes and want to know why this does not work! If possible could somebody please explain the fault and how I can fix it? I have been looking at this for three days, I could do it differently and make it work, but I would like to understand why THIS doesn't work first!
Thanks in advance! -Charlie
first_player.attack
is a number because of self.attack = random.randint(30,40)
. I suspect that you want that named differently so that it doesn't overwrite your attack
method.
__init__()
shadows the attack()
method on the object. Use a different name.
The variable for each players attack-strength has the same name as the function for attack, so when you call first_player.attack(), it's trying to call an int as if it was a function. Rename the function to something like "attack_player()" or the attack rating as "attack_value", or something, and it should work.
精彩评论