我的if / elif语句只返回if

时间:2014-04-02 15:16:15

标签: if-statement python-3.x while-loop

我只想首先说我刚刚开始编程,我只对学习感兴趣。

在一个非常简单的回合制格斗游戏中,我给我的玩家选择攻击或防守但是当我输入一个" d"为了防御,它将返回攻击代码。

import random
import time

play = 'y'

name = ' '

playerHp = 20
attack =  4
enemyHp = 0
enemyAttack = 0


def intro ():
    global name
    print('''
welcome to the scary forrest!
dangerous monsters live in this
area and you must destroy or
be destroyed! attack and defend
correctly and you may survive.''')
    time.sleep (2)

    print ('what is your name, adventurer?')

    name = input()

def randomEnemy ():
    x = random.randint (3,5)
    global enemyHp
    global enemyAttack
    enemyHp = x * 5
    enemyAttack = x
    print('''A goblin has jumped out to attack you, prepare to fight!''')


def battle ():
    global enemyHp
    global enemyAttack
    global playerHp
    global attack

    while enemyHp > 0 and playerHp > 0:
        print ('you have ' + str(playerHp) + ' health left')
        time.sleep (2)
        print ('the goblin has ' + str(enemyHp) + ' health left')
        time.sleep (2)
        print ('(a)ttack or (d)efend)

        choice = input()

        if choice == 'a' or 'attack':
            finalattack = attack + random.randint (-1,2)
            print ('you swing at the goblin and do ' + str(finalattack) + ' damage')
            time.sleep(2)
            print ('the goblin strikes you for ' + str(enemyAttack) + ' damage')
            playerHp = playerHp - enemyAttack
            enemyHp = enemyHp - finalattack
            choice = 0

        elif choice == 'd' or 'defend':
            print ('the goblin strikes at you!')
            print ('but you block his attack')
            heal = random.randint (5,6) - enemyAttack
            playerHp += heal
            print ('you heal for ' + str(heal) + ' Hp')
            choice =0

     if playerHp <= 0:
        print('you lose... noone finds your body because the \ngoblin drags you into  his cave')

    if enemyHp <= 0:
    print ('you stand victorious over your foe, but noone is \nreally impressed except yo\' momma')

intro()

randomEnemy()

battle()

我的if语句有问题吗?

如果有人可以帮助我并使用非常感激的小词。

2 个答案:

答案 0 :(得分:3)

是的,您需要测试他们的选择:

if choice == 'a' or choice == 'attack':

elif choice == 'd' or choice == 'defend':

您原来的陈述:

elif choice == 'a' or 'attack':

总是会产生True,因为字符串'attack'实际上是True(更不用说它应该是if而不是elif;感谢@chepner发现那个)。

我还没有检查过你的所有代码)。

答案 1 :(得分:0)

问题在于

elif choice == 'a' or 'attack':

没有按你的想法行事。 Python的解析器将其评估为:

elif bool(选择=='a')或bool('攻击'):

并且非空字符串的布尔值为True。你想要的是:

如果选择=='a'或选择=='攻击':

请注意,我已将elif替换为简单的if,因为它是第一个。 (elifelse if)的缩写。