2011-04-27 31 views
3

我對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

+0

這不是codereview.stackexchange.com的問題嗎? – tzot 2011-05-21 09:45:35

回答

8

__init__()在對象上陰影attack()方法。使用不同的名稱。

+0

非常感謝!如果可以的話,我會給你所有積極的聲譽,儘管我首先需要15個聲望,但你會因爲你剛剛幫助某人入門而感到高興。 (對不起,複製此評論給其他兩個答案,這三個答案都非常有幫助!) – Hypertypical 2011-04-28 17:31:55

9

first_player.attack是一個數字,因爲self.attack = random.randint(30,40)。我懷疑你要的是不同的命名,以免它覆蓋你的attack方法。

+0

非常感謝!如果可以的話,我會給你所有積極的聲譽,儘管我首先需要15個聲望,但你會因爲你剛剛幫助某人入門而感到高興。 (對不起,將此評論複製到另外兩個答案,這三個答案都非常有幫助!) – Hypertypical 2011-04-28 17:30:58

2

每個玩家攻擊強度的變量與攻擊函數具有相同的名稱,所以當你調用first_player.attack()時,它試圖調用一個int,就像它是一個函數一樣。將函數重命名爲「attack_player()」或攻擊評級爲「attack_value」等,並且它應該起作用。

+0

非常感謝!如果可以的話,我會給你所有積極的聲譽,儘管我首先需要15個聲望,但你會因爲你剛剛幫助某人入門而感到高興。 (對不起,將此評論複製到其他兩個答案中,這三個答案都非常有幫助!) – Hypertypical 2011-04-28 17:32:04

相關問題