Я изучал Python в течение нескольких дней и решил начать писать текстовые приключения. У меня все хорошо, но я зашел в тупик. Полный код на данный момент выглядит следующим образом:
import random
import sys
#PLAYER STATS#
hp=random.randint(1,1)
mp=random.randint(5,10)
streetsmarts=0
streetcred=0
cash=0
#Yes or No Q's#
yn1="a"
yn2="a"
yn3="a"
#NPCS"
Nick="npc"
#Initial spell positions#
castfire=False
castlightning=False
castshrink=False
castbolster=False
castheal=False
castmindcontrol=False
casttele=False
castenlarge=False
castspeed=False
castalert=False
cancelspell=False
#GAME MECHANICS#
def spellcasting(): #Enters
#the spellcasting phase,where you may pick a spell and cast it#"
print ("You may choose to cast a spell.")
print ("The usable spells are:")
print (spelloff)
print ("Your spellbook contains: ")
print (spellbook)
spell=input("Which spell will you cast: ")
if spell ==("Fire") and ("Fire") in spellbook and ("Fire") in spelloff:
confirm=input("This will consume 2 Magic Points. Are you sure?")
if confirm == ("y"):
castfire=True #Sets castfire to True, ready to be cast
#This seems to work fine, and changes castfire to True
return
elif spell ==("Lightning") and ("Lightning") in spellbook and ("Lightning") in spelloff:
confirm=input("This will consume 2 Magic Points. Are you sure?")
if confirm == "y":
castlightning=True
return
elif spell ==("Shrink") and ("Shrink") in spellbook and ("Shrink") in spelloff:
confirm=input("This will consume 3 Magic Points. Are you sure?")
if confirm == "y":
castshrink=True
return
elif spell ==("Bolster") and ("Bolster") in spellbook and ("Bolster") in spelloff:
confirm=input("This will consume 2 Magic Points. Are you sure?")
if confirm == "y":
castbolster=True
return
elif spell ==("Enlarge") and ("Enlarge") in spellbook and ("Enlarge") in spelloff:
confirm=input("This will consume 3 Magic Points. Are you sure?")
if confirm == "y":
castenlarge=True
return
elif spell ==("Heal") and ("Heal") in spellbook and ("Heal") in spelloff:
confirm=input("This will consume 4 Magic Points. Are you sure?")
if confirm == "y":
castheal=True
return
elif spell ==("Mind Control") and ("Mind Control") in spellbook and ("Mind Control") in spelloff:
confirm=input("This will consume 4 Magic Points. Are you sure?")
if confirm == "y":
castmindcontrol=True
return
elif spell ==("Alert") and spellbook == ("Alert"):
confirm=input("This will consume 2 Magic Points. Are you sure?")
if confirm == "y":
castalert=True
return
elif spell ==("Speed") and spellbook == ("Speed"):
confirm=input("This will consume 2 Magic Points. Are you sure?")
if confirm == "y":
castspeed=True
return
elif spell ==("Telekenesis") and ("Telekenesis") in spellbook:
confirm=input("This will consume 3 Magic Points. Are you sure?")
if confirm == "y":
casttele=True
return
else:
print ("Spell not recognised, try again")
another_spell()
def another_spell():
spellyn=input("Would you like to choose another spell? ")
if spellyn=="y":
spellcasting()
else:
print ("You decide to save your Magic Points")
cancelspell=True
print ("Welcome adventurer")
name=input("Enter your name: ")
print ("Hello", name,".","\nI have made a game for you to play. \nYour stats are randomly generated each playthrough. \nThis time around you start with", hp, "health, and", mp, "magic points. \nGood luck!")
item_list=["Machete","Tactical Helmet","Suitcase full of Cash","Grenadesx3","Sniper Rifle","Mobile Phone,"]
gamespells_list=["Lightning","Fire","Shrink","Enlarge", "Bolster", "Heal", "Alert", "Speed", "Mind Control", "Telekenesis",]
playerinventory_list=[] spellbook=random.sample(gamespells_list, 2)
spellbook.append("Fire")
print ("Your starting spells
are", spellbook)
print (item_list)
pick=input("Pick an item to
start with")
while pick != "Machete" and pick != "Tactical Helmet" and pick!="Suitcase full of Cash" and pick !="Grenadesx3" and pick!="Sniper Rifle" and pick != "Mobile Phone":
print ("Try again")
pick=input("Pick an item")
if pick == "Machete" or pick == "Tactical Helmet" or pick=="Suitcase full of Cash" or pick =="Grenadesx3" or pick=="Sniper Rifle" or pick == "Mobile Phone": playerinventory_list.append(pick)
print ("Your inventory now contains:")
print (playerinventory_list)
pick=("empty")
print ("The adventure begins...")
if hp == 1:
print ("You wake up and are immediately thrown into deep discomfort.Your whole body aches. You have fallen off the side of the bed and broken some ribs. As you lie crumpled in agony, you hear heavy footsteps on the wooden floor in the next room.")
if ("Mobile Phone") in playerinventory_list:
yn1=input("Would you like to use the Mobile Phone?")
elif ("Grenadesx3") in playerinventory_list:
yn2=input("Would you like to use the Grenadesx3?")
else:
print ("The footsteps approach your room, and the door slowly opens. A bald man in a red denim jacket enters, and as he sees your situation he smiles. He raises a pistol with a silencer attached to your head and pulls the trigger")
print ("THE END")
sys.exit()
if yn1 == ("n"):
print ("The footsteps approach your room, and the door slowly opens. A bald man in a red denim jacket enters, and as he sees your situation he smiles. He raises a silenced pistol to your head and pulls the trigger")
print ("THE END")
sys.exit()
elif yn1 ==("y"):
print ("Scared for your life you scramble to reach your mobile phone. You get hold of it and ring Nick from next door", "Hello? Whats going on",name,"?", "Nick, I need you to break into my apartment right now, my life is in danger HURRY!","As you hang up the phone your bedroom door slowly opens, and a bald man in a red denim jacket steps in. He eyes you like a vulture as he draws a silenced pistol. You close your eyes and anticipate death, but when you open them again Nick is wrestling with the intruder.")
streetsmarts=streetsmarts+1
pathway=1
Nick="alive"
if yn2==("n"):
print ("The footsteps approach your room, and the door slowly opens. A bald man in a red denim jacket enters, and as he sees your situation he smiles. He raises a silenced pistol to your head and pulls the trigger")
print ("THE END")
sys.exit()
elif yn2 ==("y"):
print ("Refusing to go out without a bang, you grab a grenade from the stash under your bed. Unable to get up, you pull the pin and hold it to your chest as the intruder enters. He eyes you up and moves forward drawing his weapon. You close your eyes, accepting your fate. Moments later the grenade blasts the room apart, and both of you are torn to pieces. " )
print ("THE END")
sys.exit()
if pathway == 1 and mp >=5:
spelloff=["Lightning","Fire","Shrink", "Heal", "Mind Control"] #This sets the available spells
spellcasting() #This enters the spell casting function
if castfire: #This is the code that isnt working. After a choosing a spell in the spell casting function, all of this code is skipped and the program prints the last line "The end?"
print ("You light the intruders denim jacket on fire, and he begins to dance about. Unfortunately though Nick is still tangled up with the intruder and also catches alight. The pair crash through a chest of drawers sending embers splashing around the room and onto you! You try to brush off the flames but to no avail. Soon they cover your whole body, and shortly after the entire apartment. " )
print ("You are dead")
sys.exit()
#I cant work out why this code is not working. Its as if Python is not recognising castfire as true
if castlightning:
print("You summon a bolt of lightning that blows open the ceiling, blasting the intruder to pieces in a flash of light. As your eyes adjust and the pieces settle you realise that Nick was blown away too. You didnt know Nick very well but he seemed a good guy, so you mourn him for a second and then wipe the bits off while staring through the hole in the ceiling. The sun is shining through")
pathway=2
Nick="dead"
mp=mp-2
if castheal is True:
print ("You heal your wounds and immediately feel better. (Your HP goes up to 5.) You leap up and with the help of Nick restrain the intruder.")
pathway=3
Nick="alive"
mp=mp-3
if castshrink is True:
print ("You shrink the intruder, and Nick stomps on the miniscule man, scraping the remains from his shoe onto your rug.")
pathway=4
Nick="alive"
mp=mp-4
if castmindcontrol is True:
print ("You hypnotize the intruder. Nick backs off and you pilot the intruder into the living room..")
pathway=3
Nick="alive"
mp=mp-4
if cancelspell is True:
print ("Spell cancelled")
print ("the end?")
Извинения за огромную стену кода, но я не думаю, что смогу сойти с рук, пропустив что-либо. Основное внимание здесь уделяется определению заклинаний def (), которое должно изменить Castfire на True, а затем, если Castfire имеет значение True, разыграть заклинание. Однако вместо наложения заклинания игра заканчивается. После запуска функции заклинания и нажатия клавиши y для подтверждения заклинания игра печатает последнюю строку кода («конец?»), Вместо того, чтобы принять usefire как True и распечатать продолжение истории. Чтобы выполнить те же шаги, что и я, вы должны запустить игру и выбрать следующие опции в этом порядке. Это чувствительно к регистру.
Имя может быть любым. Предмет должен быть мобильным телефоном. Используйте мобильный телефон (у). Используйте Огонь. Вы уверены (у). После этого игра заканчивается внезапно, когда не должно. Теоретически это не должно быть заклинание огня, но это то, над чем я работал. Я даже пытался изменить значения castfire = True и False на переменные, содержащие слова «неактивный» или «активный», и пытался использовать: if castfire == «active», но там тоже не повезло. Кто-нибудь может помочь вообще? Надеюсь, кто-нибудь может это решить.
Ps Я знаю, что на данный момент я плохой программист. Я, вероятно, расскажу о нескольких вещах, которые сложнее, чем необходимо. Пожалуйста, укажите, где вы можете видеть возможности для улучшения, не стесняйтесь разрывать его на части :)