Python - получение ошибок в текстовом файтинге - PullRequest
1 голос
/ 29 мая 2020

Я новичок в Python и программировании в целом. Я пытаюсь сделать простой текстовый файтинг для моих детей. Это первая программа, которую я написал самостоятельно. Я продолжаю получать ошибки, и я не уверен, что это такое. Я делаю неправильно.

Вот код:

import random
print("Welcome to Sword Fight!")

#Character Stat Section
#Strength
x_strength = 8
y_strength = 7
z_strength = 4
a_strength = 2
#Speed
x_spd = 4
y_spd = 6
z_spd = 4
a_spd = 3
#Agility
x_agl = 3
y_agl = 5
z_agl = 6
a_agl = 2

#Weapon Stat Section
#Strength
katana_strength = 5
broadsword_strength = 6
spear_strength = 7
dagger_strength = 3
#Speed
katana_spd = 5
broadsword_spd = 4
spear_spd = 3
dagger_spd = 7
#Reach
katana_rch = 5
broadsword_rch = 6
spear_rch = 7
dagger_rch = 3


#Enemy Character Section
enemy = ['a goblin', 'a ninja', 'a swordfighter', 'an orc']
#Strength
goblin_strength = 2
ninja_strength = 4
swordfighter_strength = 5
orc_strength = 7
#Speed
goblin_spd = 4
ninja_spd = 7
swordfighter_spd = 5
orc_spd = 3
#Agility
goblin_agl = 3
ninja_agl = 6
swordfighter_agl = 5
orc_agl = 2

#Enemy Weapon Stat Section
#Strength
shiv_strength = 2
ninjato_strength = 4
longsword_strength = 5
axe_strength = 7
#Speed
shiv_spd = 6
ninjato_spd = 6
longsword_spd = 5
axe_spd = 3
#Reach
shiv_rch = 2
ninjato_rch = 4
longsword_rch = 5
axe_rch = 4

player = str(input("Select your character - X, Y, Z or A: "))
if player == "X" or "x":
    print("You've selected X.")
    p_strength = x_strength
    p_spd = x_spd
    p_agl = x_agl
elif player == "Y" or "y":
    print("You've selected Y.")
    p_strength = y_strength
    p_spd = y_spd
    p_agl = y_agl
elif player == "Z" or "z":
    print("You've selected Z.")
    p_strength = z_strength
    p_spd = z_spd
    p_agl = z_agl
elif player == "A" or "a":
    print("You've selected A.")
    p_strength = a_strength
    p_spd = a_spd
    p_agl = a_agl

weapon = str(input("Select your weapon - katana, broadsword, spear, or dagger: "))
if weapon == "Katana" or "katana":
    p_weap = 'katana'
    print("You've selected a katana.")
    w_strength = katana_strength
    w_spd = katana_spd
    w_rch = katana_rch
elif weapon == "Broadsword" or "broadsword":
    p_weap = 'broadsword'
    print("You've selected a broadsword.")
    w_strength = broadsword_strength
    w_spd = broadsword_spd
    w_rch = broadsword_rch
elif weapon == "Spear" or "spear":
    p_weap = 'spear'
    print("You've selected a spear.")
    w_strength = spear_strength
    w_spd = spear_spd
    w_rch = spear_rch
elif weapon == "Dagger" or "dagger":
    p_weap = 'dagger'
    print("You've selected a dagger.")
    w_strength = dagger_strength
    w_spd = dagger_spd
    w_rch = dagger_rch

print("An enemy approaches! It's", random.choice(enemy), "!")

if random.choice(enemy) == 'a goblin':
    print("It's armed with a shiv.")
    e_strength = goblin_strength
    e_spd = goblin_spd
    e_agl = goblin_agl
    ew_strength = shiv_strength
    ew_spd = shiv_spd
    ew_rch = shiv_rch
elif random.choice(enemy) == 'a ninja':
    print("He's armed with a ninjato.")
    e_strength = ninja_strength
    e_spd = ninja_spd
    e_agl = ninja_agl
    ew_strength = ninjato_strength
    ew_spd = ninjato_spd
    ew_rch = ninjato_rch
elif random.choice(enemy) == 'a swordfighter':
    print("She's armed with a longsword.")
    e_strength = swordfighter_strength
    e_spd = swordfighter_spd
    e_agl = swordfighter_agl
    ew_strength = longsword_strength
    ew_spd = longsword_spd
    ew_rch = longsword_rch
elif random.choice(enemy) == 'an orc':
    print("It's armed with a battleaxe.")
    e_strength = orc_strength
    e_spd = orc_spd
    e_agl = orc_agl
    ew_strength = axe_strength
    ew_spd = axe_spd
    ew_rch = axe_rch

print("The battle begins!")

p_hp = 10
e_hp = 10

while p_hp > 0 or e_hp > 0:
    print = ("Which attack will you use?")
    if p_weap == 'katana':
        attack = str(input("Slice, Stab, or Spinning Slash?: "))
    if attack == 'Slice' or 'slice':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Spinning slash' or 'spinning slash' or 'Spinning Slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")    
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'broadsword':
        attack = str(input("Overhead chop, Stab, or Slash?: "))
    if attack == 'Overhead chop' or 'overhead chop' or 'Overhead Chop':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Slash' or 'slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'spear':
        attack = str(input("Slam, Swipe, or Thrust?: "))
    if attack == 'Slam' or 'slam':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Swipe' or 'swipe':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'dagger':
        attack = str(input("Slash, Stab, or Thrust?: "))
    if attack == 'Slash' or 'slash':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

if p_hp == 0:
    print("You have been defeated...")
if e_hp == 0:
    print("You are victorious!")

Я уверен, что есть более простые способы делаю все это, но я еще не изучил более сложные команды или техники.

Первая ошибка, с которой я столкнулся, заключается в том, что независимо от того, что пользователь вводит для выбора своего персонажа, программа выбирает только символ X.

Вторая ошибка - независимо от того, какое оружие выбирает пользователь, программа выбирает катану.

Третья ошибка - когда программа выбирает врага, иногда она выбирает правильное вражеское оружие, иногда неправильное вражеское оружие, а иногда и вовсе не выбирает вражеское оружие.

Четвертая ошибка - если программа выбирает врага и правильное вражеское оружие, я получаю ошибку отслеживания, когда пользователь вводит атаку :

line 171, in <module>
    print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $

Пятая ошибка - когда программе не удается выбрать вражеское оружие, и пользователь начинает атаку, я получаю другую ошибку отслеживания:

line 168, in <module>
    e_atk = (e_strength + ew_strength)
NameError: name 'e_strength' is not defined
1|:/ $

Шестая ошибка - когда программа выбирает врага и неправильное вражеское оружие, и пользователь переходит в атаку, появляется другая ошибка отслеживания:

line 174, in <module>
    print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $

Любая помощь приветствуется. Спасибо!

Ответы [ 2 ]

1 голос
/ 29 мая 2020
  1. Первая проблема заключается в том, что ваше или утверждение неверно. if player == "X" является правильным, однако or player "x": всегда будет возвращать истину, поскольку вы, по сути, спрашиваете, «существует ли следующая строка 'x'?» если вы собираетесь продолжать делать это таким образом, вам нужно изменить все ваши if или операторы на if player == "X" or player == "x":

    • , теперь более простой способ сделать это - изменить все ваши входные данные (в качестве примера я буду использовать выбрать символ )

    от: player = str(input("Select your character - X, Y, Z or A: "))

    до: player = str(input("Select your character - X, Y, Z or A:")).lower()

    теперь самое интересное в том, что вводимые пользователем данные будут строчными. Все, что вам нужно сделать, это проверить, соответствует ли она строчной строке. Если игрок набирает «HeLlow WoRlD» lower(), он преобразуется в «hello world».

  2. То же, что и в первом случае, вам нужно изменить все операторы if, подобные этому if weapon == "Katana" or "katana": на if weapon == "Katana" or weapon == "katana":

    • снова, если вы сделаете ввод строчными буквами, вам нужно будет только проверить, если weapon == "katana".
  3. e_strength определяется в нескольких операторах if , но никогда не выходит за их пределы, вам нужно поместить его во внешнюю область. см. это объяснение объема в python для получения дополнительной информации. в основном ответ заключается в том, что вам нужно сначала определить e_strength вне операторов if, возможно, в строке 123, и присвоить ему любое значение, которое вы хотите, поскольку идея состоит в том, что его следует перезаписать. Кажется, это повторяющаяся проблема, после ее исправления стали очевидны несколько других ошибок, связанных с областью видимости.

  4. Вау, это было забавно. строка 163 вы написали print = ("Which attack will you use?") это должно быть print("Which attack will you use?") это полностью сломало весь код после него.

  5. та же проблема из 4.

  6. та же проблема из 4.

1 голос
/ 29 мая 2020

Третья проблема заключается в том, что каждый раз, когда вы запускаете random.choice (враг), он каждый раз случайным образом выбирает нового врага. Вы должны поместить random.choice (враг) в переменную, а затем выполнить инструкции if / else.

Что касается четвертой проблемы, я бы предложил вместо этого использовать .format.

до

print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")

после

print("You slice the enemy and do {} points of damage.".format(p_atk - e_atk))

Пятая и шестая ошибки должны быть исправлены при помещении random.choice (врага) в переменную.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...