#python #list #save
#python #Список #Сохранить
Вопрос:
Итак, я создаю текстовую Rpg (очень похожую на Progress Quest). Единственные списки, которые стоит сохранить, — это списки оружия и предметов, а также ваше имя и класс. В начале игры вы удаляете эти два списка, а ваше имя сбрасывается на 0.
weapons = []
Вот как это начинается.
weapons = ["sword", "bow", "staff"]
На этом все заканчивается.
Я хочу, чтобы иметь возможность запускать ту же или копию программы с сохраненными элементами. Как мне это сделать? Ниже приведен весь сценарий … и, пожалуйста, обратите внимание, я делаю это просто для развлечения, и поэтому я знаю способы сделать его лучше и больше; пожалуйста, просто прокомментируйте тему, о которой я публикую.
import time
import random
allThings = ["gold coin", "Silver Coin", "Copper Coin", "Twinkies",
"Human Tissue", "Stuffed Bear", "Hulk Toy", "Pen", "Bobblehead",
"Charger", "Lenovo Thinkpad Modle T420",
"Stephen King Book: Full Dark, No Stars", "Toy Laser Gun",
"Car Keys", "Alarm Clock", "Casio Watch", "Python Manual",
"Tissues", "Screws", "Spare CDs", "USB Flash Drive", "Spoon",
"Fork", "Kitchen Knife", "BasketBall", "Paper Bag",
"Crubled Paper", "Water Bottle", "Technical Document",
"Plastic Glove", "Toy Bus", "Gas Canister", "Bracelet",
"Space Suit", "Nuclear Bomb", "Test Tubes", "Light Bulb",
"Mirror", "Gun Powder", "Arrow", "Human Brain", "Human Heart",
"Human Kidney", "Human Lung", "Human Stomach"]
Enemies = ["a Corrupted Police Officer", "A Half-Lizard", "A Dog",
"A Failed Surgery Client"]
inv = []
Equip = []
EquipAll = ["Sharp Stick", "Sharp Metal Scrap", "Pin", "Pencil", "Raw Thick
Stick", "Moddified Stick", "Grandpa's Axe", "Cursed Axe", "Fine
Blade", "Wooden Sword", "BB Gun", "Nerf Gun", "Human Arm", "22.
Caliber Pistol", "45. Caliber Pistol", "Colt 45.", "9mm Pistol",
"Ice Staff", "Fire Staff", "5.66mm Bullpup Rifle", "7.22 Assault
Rifle", "357. Magnum", "44. Magnum", "FAL Rifle", "7.62mm Rifle",
"308. Rifle", "Laser Kilo Gun", "Laser Mega Gun",
"Laser Deca Gun", "Laser Hecto Gun", "Laser Giga Gun",
"Laser Tera Gun", "Laser Peta Gun", "Laser Exa Gun",
"Laser Zeta Gun", "Laser Yotta Gun", "Inferno Blade",
"Blade of the Red Dragon", "Frag Granade", "Spear", "Shotgun",
"308. Sniper Rifle", "Bow", "Attack Dog", "Rolling Pin"]
chance = ["1", "2", "3", "4", "5"]
debt = 1000000
name = 0
c = 0
x = 0
y = 0
def Start():
global debt
if len(inv)<10:
x = random.choice(allThings)
print "*********************************************************************"
print("You came across and executed " random.choice(Enemies) " ...")
time.sleep(5)
print "--------------------------------------------------------------------"
print("You found " x " ...")
inv.append(x)
c = random.choice(chance)
if c == ("1"):
print "----------------------------------------------------------------"
y = random.choice(EquipAll)
print("You found " y " as a weapon...")
Equip.append(y)
print "****************************************************************"
print "n"
print "////////////////////////////////////////"
print("Name: " name " Race: " race)
print"____________________________"
print("Debt due: " str(debt))
print"____________________________"
print "Items: n"
print inv
print "___________________________"
print "Weapons: n"
print Equip
print "////////////////////////////////////////"
time.sleep(7)
print "n"
print "n"
print "n"
print "n"
print "n"
print "n"
print "n"
print "n"
print "n"
print "n"
Start()
elif len(inv)>9:
print " "
print " Going to pawn shop... "
print " "
time.sleep(5)
print("Selling " str(inv) " ...")
inv[:] = []
time.sleep(13)
print "n"
print "Items sold. You got $10"
debt = debt - 10
time.sleep(5)
print "Heading back to the world"
time.sleep(10)
print "n"
print "n"
print "n"
print "n"
Start()
print "-------------------THE 2017 Executioner------------------------"
print"Select your name:"
name = raw_input()
print "n"
print "Select your race: Half-Lizard, Octopus, etc (You can even make one up):"
race = raw_input()
print "n"
print "One last thing... are you a man or a woman?"
sex = raw_input()
print "n"
print "******************************************************************************"
print "****************************Your Story Begins Here****************************"
print "******************************************************************************"
print "n"
print "n"
print "Underground Medical Files:"
print "n"
print("Our latest client, " name ", has suffered a terrible accident..."
name " was brought here by some friends... We set up a 'full body "
"surgery' for this " sex " ..." name " decided to become a "
race ".... this is the most expensive surgery we have ever done"
"... We thought " name " would be able to pay for it... But after "
"we said that they were in debt.... well, the client went full-on "
"beserk .... Now this " race " is going around the world doing "
"who-knows-what...." "n" " Signed, /\@..... Director of the "
"illegal underground Hospital and Surgeries")
xcv = raw_input("Press Enter to Begin...")
print "n"
print "n"
print "Loading..."
time.sleep(30)
print "n"
Start()
Комментарии:
1. Запишите свой список в файл, и когда скрипт запустится, загрузите файл снова.
Ответ №1:
Канонический способ сделать это в Python — с pickle
помощью модуля. Для Python 3 документация находится здесь . Пример из этой документации:
import pickle
# An arbitrary collection of objects supported by pickle.
data = {
'a': [1, 2.0, 3, 4 6j],
'b': ("character string", b"byte string"),
'c': {None, True, False}
}
with open('data.pickle', 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
Этот пример сохраняет вложенную структуру данных (dict с некоторыми списками, наборами и кортежами в нем) в файл с именем data.pickle
. Вот как его можно загрузить обратно:
import pickle
with open('data.pickle', 'rb') as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
data = pickle.load(f)