我對Python編程非常陌生,現在我正在編寫一個簡單的格鬥遊戲(基於文本),這非常簡單,因爲我現在正在學習基礎知識。 我在下面放置了我的遊戲的代碼(它沒有完成),我的問題是每次運行程序時,當你輸入你想玩的角色,因爲這個錯誤發生。Python編程新手,有人能解釋一下這個程序的錯誤嗎?
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
這裏是我的遊戲的代碼(不要擔心它不是很大!)。
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)
我知道有喜歡追加人物列表後玩家挑選名字,但我想有類進一步理解,並且想知道爲什麼這是行不通的解決方法!如果可能的話,請有人解釋錯誤,以及我如何解決它?我一直在看這個爲期三天,我可以做不同的工作,並使其工作,但我想明白爲什麼這不起作用!
在此先感謝! -Charlie
這不是codereview.stackexchange.com的問題嗎? – tzot 2011-05-21 09:45:35