我有一些python的经验,但是有一件事我不理解pickle
函数的作用。我有一个朋友的代码,我想知道pickle
的作用。
# Import Plugins
import pickle, random, os, sys, threading
from hero import Character
from enemy import Enemy
from shop import Product
from attack import Attack
from replit import clear
from time import sleep
# Player Attacks: Attack("Name", Damage, Mana Cost)
melee = Attack("Melee",20,0)
snowball = Attack("lightning bolt",30,10)
fireball = Attack("Fireball",40,15)
spear = Attack("Spear",30,10)
sword = Attack("Sword",40,15)
bowArrow = Attack("Bow & Arrow",30,10)
crossbow = Attack("Cross Bow",40,15)
# Enemy Attacks: Attack("Name", Damage, Mana Cost)
meleeEnemy = Attack("Melee",8,0)
meleeBoss = Attack("Melee",16,0)
# Characters: Character("Name", HP, Max HP, Mana, Max Mana, Attack, Attack)
wizard = Character("Wizard",125,125,125,125,melee,snowball,fireball)
knight = Character("Knight",175,175,75,75,melee,spear,sword)
archer = Character("Archer",150,150,100,100,melee,bowArrow,crossbow)
# Monsters & Bosses: Enemy("Name", HP, Max HP, Primary Attack)
monsterOne = Enemy("Monster",50,50,meleeEnemy)
monsterTwo = Enemy("Monster",75,75,meleeEnemy)
bossOne = Enemy("Boss",125,125,meleeBoss)
bossTwo = Enemy("Boss",150,150,meleeBoss)
# Food Items
apple = Product("Apple",2,20,"[Heals 20 HP]")
porkchop = Product("Porkchop",10,125,"[Heals 125 HP]")
# Lists
monsterList = [monsterOne,monsterTwo]
bossList = [bossOne,bossTwo]
# Extra
backpackVar = 0
# Bank Interest Check
def bankInterest():
sleep(600)
player.bankCoins = player.bankCoins * player.bankInterestRate
threading.Timer(1, bankInterest).start()
# Print Functions
def characterStats():
print("[Character]")
print("{}".format(player.getName()))
print("HP: ({}/{})".format(player.getHealth(),player.getMaxHealth()))
print("Mana: ({}/{})\n".format(player.getMana(),player.getMaxMana()))
# Signup
def signup():
global username, password, filename
clear()
print("Hero Legends\n")
print("[Signup]")
username = input("Username: ")
password = input("Password: ")
filename = ("{}_{}.pickle".format(username,password))
if os.path.exists(filename):
print("\nAccount Already Exists")
sleep(0.75)
gameMenu()
preGame()
# Login
def login():
global username, password, filename
clear()
print("Hero Legends\n")
print("[Login]")
username = input("Username: ")
password = input("Password: ")
filename = ("{}_{}.pickle".format(username,password))
if os.path.exists(filename):
load()
threading.Thread(target=bankInterest).start()
gameHub()
else:
print("\nAccount Does Not Exist")
sleep(0.75)
gameMenu()
# Guest
def guest():
global username
clear()
print("Hero Legends\n")
print("[Guest]")
username = input("Username: \n")
preGame()
# Load (Must Global)
def load():
global player, apple
with open(filename,'rb') as f:
player = pickle.load(f)
apple = pickle.load(f)
clear()
print("Progress Loaded")
sleep(0.5)
# Save
def save():
if guestAccess == 0:
if os.path.exists(filename):
os.remove(filename)
with open(filename,'wb+') as f:
pickle.dump(player,f)
pickle.dump(apple,f)
clear()
print("Progress Saved")
sleep(0.5)
# Main Menu
def gameMenu():
global guestAccess
while True:
clear()
print("Hero Legends")
print("Please Fork Hero Legends (Unless You're Playing as a Guest!) to Save / Load Progress!\n")
print("[Main Menu]")
print("(1) Tutorial")
print("(2) Login")
print("(3) Signup")
print("(4) Guest\n")
mainMenu = input("> ")
if mainMenu == "1":
guestAccess = 0
tutorial()
if mainMenu == "2":
guestAccess = 0
login()
if mainMenu == "3":
guestAccess = 0
signup()
if mainMenu == "4":
guestAccess = 1
guest()
# Tutorial
def tutorial():
while True:
clear()
print("Hero Legends\n")
print("[Tutorial]")
print("In Hero Legends, heroes fight monsters and bosses to level up and prestige.")
print("Once they hit level 100, they prestige and gain stat boosts.")
print("Every 5 levels, you will receive an upgrade token to use at the upgrade table.")
print("You can boost your attack, defense and also the coins and gems you get from chests.\n")
print("(1) Main Menu\n")
tutorialInput = input("> ")
if tutorialInput == "1":
gameMenu()
# Pre Game Calibration
def preGame():
global player
while True:
clear()
print("Hero Legends\n")
print("(1) Wizard \nStats: HP:{}, Mana:{}".format(wizard.getHealth(),wizard.getMana()))
print("(2) Knight \nStats: HP:{}, Mana:{}".format(knight.getHealth(),knight.getMana()))
print("(3) Archer \nStats: HP:{}, Mana:{}\n".format(archer.getHealth(),archer.getMana()))
characterInput = input("> ")
if characterInput == "1":
player = wizard
break
elif characterInput == "2":
player = knight
break
elif characterInput == "3":
player = archer
break
# Auto Calibrate
while True:
if guestAccess == 1:
break
clear()
print("Do you want to Auto Save Game on Exit? (Y/N)")
autoDetect = input("> ")
if autoDetect.lower() == "y":
player.autoSave = 1
break
if autoDetect.lower() == "n":
player.autoSave = 0
break
if guestAccess == 0:
save()
threading.Thread(target=bankInterest).start()
gameHub()
# Game Hub
def gameHub():
while True:
player.calcMaxXp()
clear()
print("Hero Legends\n")
print("[Account]")
print("{}".format(username))
print("Coins: {}".format(player.getCoins()))
print("Gems: {}\n".format(player.getGems()))
characterStats()
print("Level: {}".format(player.getLevel()))
print("XP: ({}/{})".format(player.getXp(), player.getMaxXp()))
print("\n[Game Hub]")
print("(a) Play Level")
print("(b) Upgrade Table")
print("(c) Shop")
print("(d) Casino")
print("(e) Backpack")
print("(f) Bank")
print("\n[Options]")
if guestAccess == 0:
print("(1) Save")
print("(2) Settings")
print("(3) Exit\n")
hubInput = input("> ")
if hubInput == "a":
play()
if hubInput == "b":
upgradeTable()
if hubInput == "c":
shop()
if hubInput == "d":
gamble()
if hubInput == "e":
backpack()
if hubInput == "f":
bank()
if hubInput == "1":
if guestAccess == 0:
save()
if hubInput == "2":
settings()
if hubInput == "3":
if player.autoSave == 1:
save()
sys.exit(0)
# Play
def play():
global monsterCount, bossCount, chestMonsterCount, chestBossCount
clear()
# Choose Number of Monsters and Bosses
monsterCount = random.randrange(2,6)
bossCount = random.randrange(1,3)
chestMonsterCount = monsterCount
chestBossCount = bossCount
# Level
while True:
if monsterCount > 0 or bossCount > 0:
fightMonster()
elif monsterCount == 0 and bossCount == 0:
player.healAll()
chest()
break
# Play: Monster Fight
def fightMonster():
global monsterCount, bossCount, chosenAttackWeapon, pickedMonster, backpackVar
if monsterCount > 0:
pickedMonster = random.choice(monsterList)
currentEnemy = "monster"
elif monsterCount == 0 and bossCount > 0:
pickedMonster = random.choice(bossList)
currentEnemy = "boss"
while True:
clear()
if pickedMonster.health <= 0:
print("Hero Legends\n")
print("You defeated a {}".format(pickedMonster.getName()))
# Give Xp
if pickedMonster.name == "Monster":
xpCount = (player.lvl * 5)
if pickedMonster.name == "Boss":
xpCount = (player.lvl * 10)
player.gainXp(xpCount)
print("You got {} Xp!".format(xpCount))
input("\nPress 'Enter' to Continue!")
clear()
pickedMonster.healAll()
if currentEnemy == "monster":
monsterCount -= 1
if currentEnemy == "boss":
bossCount -= 1
break
if player.health <= 0:
player.healAll()
clear()
randomCoins = random.randint(5,11)
if player.coins > randomCoins:
player.coins -= randomCoins
else:
randomCoins = player.coins
player.coins -= randomCoins
print("Hero Legends\n")
print("[Stats]")
print("You Died!")
if randomCoins > 0:
print("You Lost {} Coins!".format(randomCoins))
input("\nPress 'Enter' to Return to Hub!")
gameHub()
print("Hero Legends\n")
print("[Enemy Count]")
if monsterCount > 0:
print("Monster Count: {}".format(monsterCount))
print("Boss Count: {}\n".format(bossCount))
characterStats()
print("[Enemy]")
print("{}".format(pickedMonster.getName()))
print("HP: ({}/{})\n".format(pickedMonster.health,pickedMonster.maxHealth))
print("[Attack]")
print("(a) Default Attack [{}]".format(player.defaultAttack.getName()))
print("Damage: {}".format(player.defaultAttack.getDamage()))
if player.defaultAttack.manaCost > 0:
print("Mana Cost: {}".format(player.defaultAttack.getManaCost()))
print("(b) Primary Attack [{}]".format(player.attackOne.getName()))
print("Damage: {}".format(player.attackOne.getDamage()))
if player.attackOne.manaCost > 0:
print("Mana Cost: {}".format(player.attackOne.getManaCost()))
print("(c) Secondary Attack: [{}]".format(player.attackTwo.getName()))
print("Damage: {}".format(player.attackTwo.getDamage()))
if player.attackTwo.manaCost > 0:
print("Mana Cost: {}\n".format(player.attackTwo.getManaCost()))
print("[Options]")
print("(1) Run Away")
print("(2) Backpack\n")
attackInput = input("> ")
if attackInput == "a":
chosenAttackWeapon = player.defaultAttack
attackDamage()
if attackInput == "b":
chosenAttackWeapon = player.attackOne
attackDamage()
if attackInput == "c":
chosenAttackWeapon = player.attackTwo
attackDamage()
if attackInput == "1":
runawayChance = random.randint(0,101)
if runawayChance < 25:
player.healAll()
pickedMonster.healAll()
print("\nYou Successfully Ranaway!")
sleep(1.5)
gameHub()
else:
print("\nYou Were Unsuccessful in Running Away!")
sleep(1)
doDamage = random.randint(4,pickedMonster.attackOne.damage)
player.health -= doDamage
print("{} did {} Damage to your {}".format(pickedMonster.getName(),doDamage,player.getName()))
sleep(1)
clear()
if attackInput == "2":
backpackVar += 1
backpack()
backpackVar -= 1
clear()
if pickedMonster.health > 0:
enemyHitChance = random.randint(0,101)
if enemyHitChance < 75:
doDamage = random.randint(4,pickedMonster.attackOne.damage)
player.health -= doDamage
print("\n{} did {} Damage to your {}".format(pickedMonster.getName(),doDamage,player.getName()))
sleep(1)
clear()
else:
print("\n{} Missed Attack".format(pickedMonster.getName()))
sleep(1)
clear()
# Play: Attack
def attackDamage():
# Player Hits Enemy if Mana >= Cost
if player.mana >= chosenAttackWeapon.manaCost:
pickedMonster.health -= chosenAttackWeapon.damage
player.mana -= chosenAttackWeapon.manaCost
print("\n{} used {} and did {} Damage to the {}".format(player.getName(),chosenAttackWeapon.getName(),chosenAttackWeapon.getDamage(),pickedMonster.getName()))
sleep(1)
if chosenAttackWeapon.manaCost > 0:
print("Mana Lost: {}".format(chosenAttackWeapon.getManaCost()))
sleep(1.5)
# Enemy Hits Player
if pickedMonster.health > 0:
enemyHitChance = random.randint(0,101)
if enemyHitChance < 75:
doDamage = random.randint(4,pickedMonster.attackOne.damage)
player.health -= doDamage
print("\n{} did {} Damage to your {}".format(pickedMonster.getName(),doDamage,player.getName()))
sleep(1)
clear()
else:
print("\n{} Missed Attack".format(pickedMonster.getName()))
sleep(1)
clear()
else:
print("\nNot Enough Mana!")
sleep(1)
clear()
# Play: Chest
def chest():
chestGems = 0
# Randomize
chestMonsterCoins = random.randint(chestMonsterCount, (5*chestMonsterCount))
chestBossCoins = random.randint(chestBossCount, (10*chestBossCount))
chestGemsChance = random.randint(0,101)
# Amounts
totalChestCoins = chestMonsterCoins + chestBossCoins + player.coinBoost
if chestGemsChance < 10 + player.gemBoost:
chestGems = 1
clear()
print("Hero Legends\n")
print("[Items]")
player.coins += totalChestCoins
print("Coins Earned: {}".format(totalChestCoins))
if chestGems > 0:
player.gems += chestGems
print("Gems Earned: {}".format(chestGems))
input("\nPress 'Enter' to Close Chest!")
if player.autoSave == 1:
save()
# Upgrade Table
def upgradeTable():
while True:
clear()
print("Hero Legends")
print("Upgrade Tokens: {}\n".format(player.getUpgradeTokens()))
print("[Upgrade Table]")
print("(a) Health Cap [+20]")
print("(b) Mana Cap [+20]")
print("(c) Coin Boost [+2]")
print("(d) Gem Boost [+1%]\n")
print("[Menu]")
print("(1) Exit Upgrade Table\n")
upgradeTableInput = input("> ")
if upgradeTableInput == "1":
gameHub()
if upgradeTableInput == "a" or upgradeTableInput == "b" or upgradeTableInput == "c" or upgradeTableInput == "d":
if player.upgradeTokens > 0:
player.upgradeTokens -= 1
if upgradeTableInput == "a":
player.maxHealth += 20
player.healAll()
if player.autoSave == 1:
save()
print("\nSuccessfully Upgraded Health Cap by 20")
input("Press 'Enter' to Continue!")
if upgradeTableInput == "b":
player.maxMana += 20
player.healAll()
if player.autoSave == 1:
save()
print("\nSuccessfully Upgraded Mana Cap by 20")
input("Press 'Enter' to Continue!")
if upgradeTableInput == "c":
player.coinBoost += 2
if player.autoSave == 1:
save()
print("\nSuccessfully Upgraded Coin Boost by 2")
input("Press 'Enter' to Continue!")
if upgradeTableInput == "d":
player.gemBoost += 1
if player.autoSave == 1:
save()
print("\nSuccessfully Upgraded Gem Boost by 1%")
input("Press 'Enter' to Continue!")
else:
print("\nNot Enough Upgrade Tokens!")
input("Press 'Enter' to Continue!")
# Shop
def shop():
while True:
clear()
print("Hero Legends\n")
print("[Shop]")
print("(a) Food Menu [HP & Mana]")
# print("(b) Weapon Menu [Primary & Secondary]")
print("\n[Menu]")
print("(1) Exit Shop\n")
shopInput = input("> ")
if shopInput == "a":
shopFood()
# if shopInput == "b":
# shopWeapon()
if shopInput == "1":
gameHub()
# Shop: Food
def shopFood():
while True:
clear()
print("Hero Legends")
print("Coins: {}\n".format(player.getCoins()))
print("[Food]")
print("(a) Apple - Cost: {} Coins {}".format(apple.getCost(),apple.getBuffInfo()))
if apple.amount > 0:
print("Amount: {}".format(apple.getAmount()))
print("\n[Options]")
print("(1) Game Hub")
print("(2) Back to Shop\n")
foodInput = input("> ")
if foodInput == "a":
if player.coins >= apple.cost:
player.coins -= apple.cost
apple.amount += 1
print("\nBought 1 apple!")
sleep(0.5)
else:
print("\nNot enough money!")
sleep(0.5)
if foodInput == "1":
gameHub()
if foodInput == "2":
shop()
# Shop: Weapons
def shopWeapon():
while True:
clear()
print("Hero Legends")
print("Coins: {}".format(player.getCoins()))
print("\n[Weapons]")
print("\n[Options]")
print("(1) Game Hub")
print("(2) Back to Shop\n")
weaponInput = input("> ")
if weaponInput == "1":
gameHub()
if weaponInput == "2":
shop()
# Gamble
def gamble():
while True:
clear()
print("Hero Legends")
print("Coins: {}".format(player.getCoins()))
print("\n[Gamble]")
print("(a) Slots")
print("\n[Options]")
print("(1) Game Hub")
print("(2) Gamble Info\n")
gambleInput = input("> ")
# Slots
if gambleInput == "a":
try:
slotsAmount = input("Gamble Amount: ")
if int(slotsAmount) > 0:
if player.coins >= int(slotsAmount):
player.coins -= int(slotsAmount)
numberOne = random.randint(0,5)
numberTwo = random.randint(0,5)
numberThree = random.randint(0,5)
clear()
print("| {} | {} | {} |".format(numberOne,numberTwo,numberThree))
# 3x Money | 3 Numbers
if numberOne == numberTwo and numberOne == numberThree:
sleep(1)
print("You have won 3x your gambled money: ${}!".format(3*int(slotsAmount)))
player.coins += (3*int(slotsAmount))
sleep(2)
# 2x Money | 2 Numbers
elif numberOne == numberTwo or numberTwo == numberThree or numberOne == numberThree:
sleep(1)
print("You have won 2x your gambled money: ${}!".format(2*int(slotsAmount)))
player.coins += (2*int(slotsAmount))
sleep(2)
# 0x Money | 1 or 0 Numbers
else:
sleep(1)
print("You lost all your gambled money!")
sleep(2)
elif player.coins < int(slotsAmount):
clear()
print("You don't have enough money to gamble!")
sleep(0.75)
else:
clear()
print("Please enter a number greater than 0!")
sleep(0.75)
except:
clear()
print("That is not a number, please type a number!")
sleep(0.75)
if gambleInput == "1":
gameHub()
if gambleInput == "2":
clear()
print("[Slots]")
print("Three numbers are rolled from 1 to 5.")
print("If three numbers are the same, you win 3x your gambled money.")
print("If two numbers are the same, you win 2x your gambled money.")
print("If no numbers are the same, you lose all your gambled money.")
print("\n[Options]")
print("(1) Gamble Menu\n")
gambleOptionsInput = input("> ")
if gambleOptionsInput == "1":
gamble()
# Backpack
def backpack():
while True:
clear()
print("Hero Legends\n")
print("[Backpack]")
print("(a) Apples: {} {}".format(apple.getAmount(),apple.getBuffInfo()))
print("\n[Options]")
if backpackVar == 0:
print("(1) Game Hub")
if backpackVar == 1:
print("(2) Exit")
backpackInput = input("\n> ")
if backpackInput == "a":
if apple.amount > 0:
if player.health == player.maxHealth:
clear()
print("You already have max health!")
sleep(0.75)
elif player.health <= player.maxHealth - apple.buff:
player.health += apple.buff
apple.amount -= 1
clear()
print("You healed {} health!".format(apple.getBuff()))
sleep(0.75)
break
elif player.health >= player.maxHealth - apple.buff:
healthVar = player.maxHealth - player.health
player.health += healthVar
apple.amount -= 1
print("You healed {} health!".format(healthVar))
sleep(0.75)
break
else:
clear()
print("You have no apples!")
sleep(0.75)
if backpackInput == "1":
if backpackVar != 1:
gameHub()
if backpackInput == "2":
if backpackVar == 1:
break
# Bank
def bank():
while True:
clear()
print("Hero Legends\n")
print("Coins: {}".format(player.getCoins()))
if player.bankAccount == 1:
print("Bank Balance: {}".format(int(player.getBankCoins())))
print("\n[Bank]")
if player.bankAccount == 0:
print("(a) Create Bank Account")
if player.bankAccount == 1:
print("(a) Deposit")
print("(b) Withdraw")
print("\n[Options]")
print("(1) Game Hub\n")
bankInput = input("> ")
if bankInput == "a":
if player.bankAccount == 0:
clear()
print("Hero Legends\n")
print("Coins: {}".format(player.getCoins()))
print("Gems: {}\n".format(player.getGems()))
print("[Bank Accounts]")
print("(a) Basic Account [Interest: 2%] [Cost: 100 Coins & 5 Gems]")
print("(b) Standard Account [Interest: 5%] [Cost: 250 Coins & 10 Gems]")
print("(c) Premium Account [Interest: 10%] [Cost: 500 Coins & 20 Gems]\n")
bankAccountChoice = input("> ")
if bankAccountChoice == "a":
if player.coins >= 100 and player.gems >= 5:
print("\nSuccessful Purchase of Basic Account!")
player.coins -= 100
player.gems -= 5
player.bankInterestRate += 0.02
player.bankAccount += 1
sleep(2)
else:
print("Not Enough Money and Gems!")
sleep(0.75)
if bankAccountChoice == "b":
if player.coins >= 250 and player.gems >= 10:
print("\nSuccessful Purchase of Standard Account!")
player.coins -= 250
player.gems -= 10
player.bankInterestRate += 0.05
player.bankAccount += 1
sleep(2)
else:
print("Not Enough Money and Gems!")
sleep(0.75)
if bankAccountChoice == "c":
if player.coins >= 500 and player.gems >= 20:
print("\nSuccessful Purchase of Premium Account!")
player.coins -= 500
player.gems -= 20
player.bankInterestRate += 0.1
player.bankAccount += 1
sleep(2)
else:
print("Not Enough Money and Gems!")
sleep(0.75)
elif player.bankAccount == 1:
try:
depositAmount = input("Deposit Amount: ")
if int(depositAmount) > 0:
if player.coins >= int(depositAmount):
player.bankCoins += int(depositAmount)
player.coins -= int(depositAmount)
print("\nSuccessfully Deposited!")
sleep(0.75)
else:
print("\nYou do not have enough coins!")
sleep(0.75)
else:
print("\nPlease type a positive number!")
sleep(0.75)
except:
print("\nPlease type a number!")
sleep(0.75)
if bankInput == "b":
if player.bankAccount == 1:
try:
withdrawAmount = input("Withdraw Amount: ")
if int(withdrawAmount) > 0:
if player.bankCoins >= int(withdrawAmount):
player.coins += int(withdrawAmount)
player.bankCoins -= int(withdrawAmount)
print("Successfully Withdrawn!")
sleep(0.75)
else:
print("\nYour bank does not have that many coins!")
sleep(0.75)
else:
print("\nPlease type a positive number!")
sleep(0.75)
except:
print("\nPlease type a number!")
sleep(0.75)
if bankInput == "1":
gameHub()
# Settings
def settings():
while True:
# Auto Save
if player.autoSave == 1:
autoSaveSetting = "On"
elif player.autoSave == 0:
autoSaveSetting = "Off"
clear()
print("Hero Legends\n")
print("[Settings]")
print("(a) Auto Save: {}".format(autoSaveSetting))
print("\n[Settings Menu]")
print("(1) Game Hub\n")
settingsMenu = input("> ")
if settingsMenu == "1":
gameHub()
if settingsMenu == "a":
toggleAutoSave()
# Settings: Toggle Auto Save
def toggleAutoSave():
clear()
if player.autoSave == 1:
print("Auto Save: On")
elif player.autoSave == 0:
print("Auto Save: Off")
print("Do you want to turn Auto Save ON or OFF (ON/OFF)")
changeAutoSave = input("> ")
if guestAccess == 1:
clear()
print("Error!\nYou are using guest access!")
elif changeAutoSave.lower() == "on" and autoSave == 0:
autoSave += 1
clear()
print("Turned on Auto Save!")
elif changeAutoSave.lower() == "off" and autoSave == 1:
autoSave -= 1
clear()
print("Turned off Auto Save!")
else:
clear()
print("Error!")
sleep(1)
save()
# Run Game
gameMenu()
您的代码不使用pickle(除了导入pickle),而且您的问题没有说明您为什么对此感兴趣。请添加一些详细信息,并让我们了解您在阅读文档后仍然不了解的内容:https://docs.python.org/3/library/pickle.html