加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python编程的新手,有人可以解释这个程序的错误吗?

发布时间:2020-12-20 12:39:48 所属栏目:Python 来源:网络整理
导读:我是 Python编程的新手,我正在编写一个简单的格斗游戏(基于文本)非常简单,因为我现在只是在学习基础知识. 我已经为我的游戏下面放置了代码(它还没有完成),我的问题是每次我运行程序时,当你输入哪个角色时你会发生这个错误. Traceback (most recent call last
我是 Python编程的新手,我正在编写一个简单的格斗游戏(基于文本)非常简单,因为我现在只是在学习基础知识.
我已经为我的游戏下面放置了代码(它还没有完成),我的问题是每次我运行程序时,当你输入哪个角色时你会发生这个错误.

Traceback (most recent call last):
  File "C:Python26combat.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

解决方法

first_player.attack是一个数字,因为self.attack = random.randint(30,40).我怀疑你希望以不同方式命名,以免它覆盖你的攻击方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读