Python代码文本游戏

时间:2015-07-17 16:19:45

标签: python python-3.x

player_health = 100

power = 10

enemy_health = 50

player_name = input('What is your name, Guardian? ')

print('Hello ' + player_name + ' the Guardian')

player_element = input('Would you like to be the Guardian of Air, Earth, Fire or Water? ')

if player_element == 'Air':
    print('You have been granted the powers of the Air, Guardian.\
          You now have the powers of the Wind and Sky.')

if player_element == 'Earth':
    print('You have been granted the powers of the Earth, Guardian.\
          You now have the powers of the Earth.')

if player_element == 'Fire':
    print('You have been granted the powers of Fire, Guardian.\
          You now have the powers of Fire. Do not destroy as you wish.')

if player_element == 'Water':
    print('You have been granted the powers of Water, Guardian.\
          You now have the powers to control the oceans and water.')

print('There is an enemy in the distance! What do you do?')

player_action = input('What do you do ' + player_name + '? ' + 'Type A to attack ')

if player_action == 'A':
    print('The enemy\'s health is at ' + enemy_health + '! ' 'Keep attacking Guardian!')

enemy_health = print(enemy_health - power) 

在最后一段代码中,我希望它打印出The enemy's health is at 40!(因为power - enemy_health = 40Keep attacking Guardian!' 有小费吗? 它隐含地得到cant convert int object to str的错误。

3 个答案:

答案 0 :(得分:0)

您不能将字符串与整数连接,而是可以使用format

print('The enemy\'s health is at {}! Keep attacking Guardian!'.format(enemy_health))

为了使用+运算符并执行连接,首先必须先创建一个字符串

print('The enemy\'s health is at ' + str(enemy_health) + '! Keep attacking Guardian!'

你还需要实际修改他们的健康状况,我不确定你认为这是做什么

enemy_health = print(enemy_health - power) 

您应该将其更改为

enemy_health = enemy_health - power

答案 1 :(得分:0)

enemy_health = enemy_health - power

将您的enemy_health变量重新指定为其当前health-power。然后,您可以通过使用str(enemy_health)显式转换,在任何地方重用此整数。 PythonMaster& CoryKramer拥有使用.format()的最新实现。这些{}表示应放置格式列表中的变量的位置。

print(str(enemy_health))

答案 2 :(得分:0)

您可以使用.format()代替,因为您无法将字符串与整数连接。请尝试改为:

print('The enemy\'s health is at {}! Keep attacking Guardian!'.format(enemy_health))

或不那么复杂的方式:

enemy_health -= power  #This is short for enemy_health = enemy_health - power
print("The enemy's health is at", enemy_health,"! Keep attacking Guardian!")

最后一行毫无意义。您无法将print()分配给变量。这是一个函数,您不需要为变量赋值。您只能将类分配给变量。这也应该是您的错误的一部分,因为print(enemy_health - power)实际上是有效的。输出为40。