我创建了一个基于文本的RPG。
import random
import os
import items
from maps import mappa
import pickle
class Player:
def __init__(self, name):
self.name = name
self.lvl = 1
self.points = 5
self.attributepoints = 2
self.str = 5
self.agy = 5
self.vit = 1
self.ene = 1
self.exp = 1
self.exptolvl = self.lvl * 2.5
self.maxhp = 100 + (self.vit * 2)
self.maxmp = 100 + (self.ene * 2)
self.hp = self.maxhp
self.mp = self.maxmp
self.gold = 50
self.primary = [items.Wood_Sword]
self.secondary = [items.Wood_Shield]
self.armor = [items.Wood_Armor]
self.attack = self.str + self.primary[0].attack + self.agy
self.defense = self.agy + (self.armor[0].attack/2) + (self.secondary[0].attack/2) + (self.vit / 1.5)
self.magicattack = ((self.ene * 1.5) + self.primary[0].attack + self.agy)/2
self.inventory = []
def update(self):
self.attack = self.str + self.primary[0].attack + self.agy
self.defense = self.agy + (self.armor[0].attack/2) + (self.secondary[0].attack/2) + (self.vit / 1.5)
self.magicattack = ((self.ene * 1.5) + self.primary[0].attack + self.agy) / 2
def main():
clear()
print("New Game")
print("Load Game")
print("Options")
print("Exit")
option = input("What do you want to do: ").lower()
if option == "new game":
start()
elif option == "load game":
loadgame()
else:
main()
def load(save):
global playerig
playerig = save
input(f"Welcome back {playerig.name}, we missed you")
game()
def start():
print("Hello welcome to mu")
name = input("What is your name ? \n")
global playerig
playerig = Player(name)
game()
def game():
os.system('cls')
print(f"Explore Level {round(playerig.lvl, 2)} Health {round(playerig.hp, 2)}/{round(playerig.maxhp, 2)} Mana {round(playerig.mp, 2)}/{round(playerig.maxmp, 2)}")
print("Inventory")
print("Character Primary Weapon Armor Shield")
print(f"Harald {playerig.primary[0].name} {playerig.armor[0].name} {playerig.secondary[0].name}")
print("Skills")
print(f"Credits Experience Attack Magic Attack Defense")
print(f"Save {playerig.exp}/{playerig.exptolvl} {round(playerig.attack, 2)} {round(playerig.magicattack, 2)} {round(playerig.defense, 2)}")
print("Exit")
option = input("\nWhat do you want to do ?\n").lower()
if option == "credits":
input("Just you")
game()
elif option == "skills":
skillupgrade()
elif option == "harald":
harald()
elif option == "inventory":
inventory()
elif option == "explore":
explore(mappa)
elif option == "character":
character()
elif option == "exit":
input("Cyaaa\n")
os.system("exit")
elif option == "save":
savegame()
else:
game()
def explore(map):
clear()
print(f"You are in {map.curzone}")
print("\nWrite travel north or travel south to explore new zones else write back to go back.")
option = input("\nWhat do you want to do?\n").lower()
if option == "travel north" or option == "travel south":
clear()
if map.loot == True:
luck = random.randint(1, 30)
if luck == 17:
print(f"There is something on the ground")
print(f"...")
print(f"You found {items.Great_Sword.name}")
giveitem(items.Great_Sword)
input("Press enter to continue")
if option == "travel north":
if map.walking < 40:
playerig.hp += (playerig.maxhp * 0.10)
if playerig.hp > playerig.maxhp:
playerig.hp = playerig.maxhp
playerig.hp += (playerig.maxhp * 0.10)
if playerig.mp > playerig.maxmp:
playerig.mp = playerig.maxmp
map.walking += 1
if map.walking == 5:
map.count = 1
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 10:
map.count = 2
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 20:
map.count = 3
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 40:
map.count = 4
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
print("You advance\n")
print("Nothing to see around")
elif map.walking >= 4:
input("You can't go more north than this\n")
elif option == "travel south":
if map.walking > 0:
playerig.hp += (playerig.maxhp * 0.10)
if playerig.hp > playerig.maxhp:
playerig.hp = playerig.maxhp
playerig.hp += (playerig.maxhp * 0.10)
if playerig.mp > playerig.maxmp:
playerig.mp = playerig.maxmp
map.walking -= 1
if map.walking == 0:
map.count = 0
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 5:
map.count -= 1
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 10:
map.count -= 2
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 20:
map.count -= 3
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
print("You advance\n")
print("Nothing to see around")
elif map.walking <= 0:
input("You can't go more south than this\n")
if map.fight == True:
monsterlist = [items.Spider, items.Huge_Spider]
monsterlist1 = [items.Baby_Dragon, items.Goblin]
monsterlist2 = [items.Stone_Goblin, items.Cyclop]
monsterlist3 = [items.Great_Dragon, items.Cyclop]
monsterlist4 = [items.Great_Dragon, items.Great_Dragon, items.Great_Dragon, items.Golden_Dragon]
luck = random.randint(1, 2)
if luck == 2:
if map.curzone == map.zone[0]:
luck1 = random.choice(monsterlist)
print(luck1.name)
fight(luck1)
elif map.curzone == map.zone[1]:
luck1 = random.choice(monsterlist1)
fight(luck1)
elif map.curzone == map.zone[2]:
luck1 = random.choice(monsterlist2)
fight(luck1)
elif map.curzone == map.zone[3]:
luck1 = random.choice(monsterlist3)
fight(luck1)
elif map.curzone == map.zone[4]:
luck1 = random.choice(monsterlist4)
fight(luck1)
else:
print("\nNo monsters around")
input("\nPress enter to continue")
explore(map)
elif option == "back":
game()
else:
input("\nPlease input a valid command")
explore(map)
def fight(monster):
clear()
print(f"You are fighting {monster.name}")
print(f"{playerig.name}'s Health {playerig.hp} {monster.name}'s Health {monster.hp}")
print(f"{playerig.name}'s Health {playerig.mp}")
print("\nAttack")
print("Skills")
print("Run")
if playerig.hp <= 0:
dead()
elif monster.hp <= 0:
reward(monster)
else:
option = input("\nWhat do you want to do?\n").lower()
if option == "attack":
monster.hp -= playerig.attack
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {playerig.attack} damage and took {damagetook} damage")
fight(monster)
elif option == "skills":
skills()
option1 = input('\nWhat skill do you want to use?\n').lower()
if option1 == "twisting" or option1 == "ice storm":
monster.hp -= useskill(option1)
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {useskill(option1)} damage and take {damagetook} damage")
fight(monster)
elif option1 == "regenerate":
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You took {damagetook} damage and healed for {useskill(option1)} hp")
fight(monster)
else:
input("Enter a valid skill name\n")
fight(monster)
elif option == "run":
probability = random.randint(1, 2)
if probability == 1:
print("You ran away")
input("Press enter to continue")
explore(mappa)
else:
print("You couldn't run away")
playerig.mp -= 5
print("Your mana decrease by 5")
monster.hp -= playerig.attack
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {damagetook} damage and took {monster.attack} damage")
fight(monster)
else:
input("Enter a valid command\n")
fight(monster)
def shop():
print(f"Available items: {items.Great_Sword.name} and {items.Exe_Sword.name}")
print("Buy")
print("Back")
option = input("What do you do: ").lower()
if option == "back":
game()
elif option == "buy":
option1 = input("What do you want to buy ?\n").lower()
if option1 == "great sword":
print("You bought the item")
playerig.inventory.append(items.Great_Sword)
game()
elif option1 == "exe sword":
print("You bought the item")
playerig.inventory.append(items.Exe_Sword)
game()
else:
print("Invalid input")
game()
def inventory():
clear()
print("Inside the Inventory you have: ")
c = 1
for i in playerig.inventory:
print(f"{c}.{i.name}")
c += 1
print(f"\nGold: {playerig.gold}")
c = 1
option = input("\nWrite back to go back else write wear to equip an item\n").lower()
if option == "back":
game()
elif option == "wear":
wearitem()
else:
inventory()
def wearitem():
try:
item = int(input("Write the number of the item you want to wear\n"))
item -= 1
if item in range(len(playerig.inventory)):
if playerig.inventory[item].type == "Weapon":
playerig.inventory.append(playerig.primary[0])
playerig.primary.pop(0)
print(f"You wore the item {playerig.inventory[item].name}")
playerig.primary.append(playerig.inventory[item])
playerig.inventory.pop(item)
playerig.update()
input("Press enter to continue")
game()
elif playerig.inventory[item].type == "Shield":
playerig.inventory.append(playerig.secondary[0])
playerig.secondary.pop(0)
print(f"You wore the item {playerig.inventory[item].name}")
playerig.secondary.append(playerig.inventory[item])
playerig.inventory.pop(item)
playerig.update()
input("Press enter to continue")
game()
elif playerig.inventory[item].type == "Armor":
playerig.inventory.append(playerig.armor[0])
playerig.armor.pop(0)
print(f"You wore the item {playerig.inventory[item].name}")
playerig.armor.append(playerig.inventory[item])
playerig.inventory.pop(item)
playerig.update()
input("Press enter to continue")
inventory()
except:
input("Please chose a number from the inventory.")
inventory()
def giveitem(item):
playerig.inventory.append(item)
def character():
clear()
print(f"Available points {playerig.points}\n")
print(f"Strength {playerig.str}")
print(f"Agility {playerig.agy}")
print(f"Vitality {playerig.vit}")
print(f"Energy {playerig.ene}")
print("\nTo add points write: Attribute press enter then chose the amount of points you want to add")
print("Example:")
print("Strength")
print("3")
print("----------------------------------------------------------------------------------------")
print("To reset points write 'reset'")
option = input("\nWhat do you want to do? Write back to go back.\n").lower()
if option == "back":
game()
elif option == "strength" or option == "agility" or option == "vitality" or option == "energy":
try:
option1 = int(input("How many points you want to add ?"))
if option1 <= playerig.points:
playerig.points -= option1
adder(option, option1)
else:
input("Not enough available points")
character()
except:
input("Invalid amount of points")
character()
elif option == "reset":
resetPoints()
else:
input("Invalid choice")
character()
def skills():
print(f"--Twisting-- Damage: {items.Twisting.damage}, Mana cost: {items.Twisting.manacost}, Description: {items.Twisting.description}, Level: {items.Twisting.lvl}")
print(f"--Ice Storm-- Damage: {items.Ice_Storm.damage}, Mana cost: {items.Ice_Storm.manacost}, Description: {items.Ice_Storm.description}, Level: {items.Ice_Storm.lvl}")
print(f"--Regenerate-- Damage: {items.Regenerate.damage}, Mana cost: {items.Regenerate.manacost}, Description: {items.Regenerate.description}, Level: {items.Regenerate.lvl}")
def skillupgrade():
clear()
skills()
try:
print(f"\nAvailable attribute points: {playerig.attributepoints}")
option = input("\nWhat skill do you wanna upgrade? Or write back to go back\n").lower()
if option == "twisting" and playerig.attributepoints > 0:
items.Twisting.lvl += 1
playerig.attributepoints -= 1
items.Twisting.damage += 3
items.Twisting.manacost += 3
input(f"--Twisting-- Damage: {items.Twisting.damage}, Mana cost: {items.Twisting.manacost}, Description: {items.Twisting.description}, Level: {items.Twisting.lvl}")
clear()
skills()
elif option == "ice storm" and playerig.attributepoints > 0:
items.Ice_Storm.lvl += 1
playerig.attributepoints -= 1
items.Ice_Storm.damage += 4
items.Ice_Storm.manacost += 8
input(f"--Ice Storm-- Damage: {items.Ice_Storm.damage}, Mana cost: {items.Ice_Storm.manacost}, Description: {items.Ice_Storm.description}, Level: {items.Ice_Storm.lvl}")
clear()
skills()
elif option == "Regenerate" and playerig.attributepoints > 0:
items.Regenerate.lvl += 1
playerig.attributepoints -= 1
items.Regenerate.damage += 10
items.Regenerate.manacost += 10
input(f"--Regenerate-- Damage: {items.Regenerate.damage}, Mana cost: {items.Regenerate.manacost}, Description: {items.Regenerate.description}, Level: {items.Regenerate.lvl}")
clear()
skills()
elif option == "back":
game()
else:
input("Invalid command\n")
skillupgrade()
except:
input("No skill with this name")
skillupgrade()
def useskill(option):
if option == "twisting":
playerig.mp -= items.Twisting.manacost
return items.Twisting.damage
elif option == "ice storm":
playerig.mp -= items.Ice_Storm.manacost
return items.Ice_Storm.damage
elif option == "regenerate":
curhp = playerig.maxhp - playerig.hp
playerig.mp -= items.Regenerate.manacost
playerig.hp += items.Regenerate.damage
if playerig.hp >= playerig.maxhp:
playerig.hp = playerig.maxhp
return curhp
else:
return items.Regenerate.damage
else:
input("Chose a valid skill")
def adder(option, option1):
if option == "strength":
playerig.str += option1
input(f"You added {option1} points to {option}")
elif option == "agility":
playerig.agy += option1
input(f"You added {option1} points to {option}")
elif option == "stamina":
playerig.vit += option1
input(f"You added {option1} points to {option}")
elif option == "energy":
playerig.ene += option1
input(f"You added {option1} points to {option}")
playerig.update()
character()
def reward(monster):
print(f"\n{monster.name} died , you earn {monster.givegold} gold")
playerig.gold += monster.givegold
playerig.exp += monster.giveexp
monster.hp = monster.maxhp
if playerig.exp >= playerig.exptolvl:
playerig.lvl += 1
playerig.points += 5
playerig.exptolvl = playerig.lvl * 2.5
print(f"\nYou leveled up, you are level: {playerig.lvl}")
print(f"You gained 5 points")
print(f"You gained 2 attribute points\n")
if monster.lvl == 1 or monster.lvl == 2:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 3 or monster.lvl == 4:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox2)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 5 or monster.lvl == 6:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox3)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 6:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox4)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 7:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox5)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
else:
print(f"{monster.name} didn't dropped anything")
input("\nPress enter to continue")
explore(mappa)
def harald():
clear()
print("Inside the Inventory you have: ")
c = 1
for i in playerig.inventory:
print(f"{c}.{i.name}")
c += 1
print(f"\nGold: {playerig.gold}")
c = 1
option = input("\nWrite back to go back else write sell to sell a item or recharge to heal/mana\n").lower()
if option == "back":
game()
elif option == "sell":
sellItem()
elif option == "recharge":
recharge()
else:
harald()
def recharge():
clear()
option = input("What do you want to recharge ? Health or Mana? back to go back\n").lower()
if option == "health":
if playerig.gold > 10:
playerig.gold -= 10
playerig.hp += playerig.maxhp
if playerig.hp > playerig.maxhp:
playerig.hp = playerig.maxhp
input("Health refiled")
game()
else:
input("Insufficient gold")
game()
elif option == "mana":
if playerig.gold > 10:
playerig.gold -= 10
playerig.mp += playerig.maxmp
if playerig.mp > playerig.maxmp:
playerig.mp = playerig.maxmp
input("Mana refiled")
game()
else:
input("Insufficient gold")
game()
elif option == "back":
game()
else:
input("Invalid command")
game()
def sellItem():
try:
item = int(input("Write the number of the item you want to sell\n"))
item -= 1
if item in range(len(playerig.inventory)):
playerig.gold += playerig.inventory[item].price
print(f"You sold the item {playerig.inventory[item].name}")
playerig.inventory.pop(item)
input("Press enter to continue")
harald()
except:
input("Please chose a number from the inventory.")
inventory()
def dead():
playerig.hp = playerig.maxhp
playerig.mp = playerig.maxmp
print("You died")
print("...")
input("Press enter enter to continue")
game()
def resetPoints():
option = input("Are you sure you want to reset all your points ? Yes or No?\n").lower()
if option == "yes":
if playerig.gold >= 100:
playerig.gold -= 100
playerig.points += (playerig.str + playerig.agy + playerig.vit + playerig.ene)-4
playerig.str -= (playerig.str - 1)
playerig.agy -= (playerig.agy - 1)
playerig.vit -= (playerig.vit - 1)
playerig.ene -= (playerig.ene - 1)
input("You reset your points")
clear()
character()
else:
input("Insufficient gold, you need 100 gold")
game()
elif option == "no":
input("You didn't reset your points")
game()
else:
input("Please enter a valid command")
resetPoints()
def savegame():
with open("savegame.b", "wb") as save:
pickle.dump(playerig, save)
input(f"You saved your current status")
game()
def loadgame():
try:
with open("savegame.b", "rb") as save:
playerig = pickle.load(save)
load(playerig)
except:
input("There is no saved game in the directory")
main()
def clear():
os.system('cls')
main()import random
empty = [["Empty", 0, 0]]
primarys = [["Wood Sword", 2, 3, "Weapon"], ["Great Sword", 12, 9, "Weapon"], ["Exe Sword", 22, 14, "Weapon"], ["Dragon Sword", 45, 23, "Weapon"], ["Dragon Knight Sword", 50, 30, "Weapon"]]
secondarys = [["Wood Shield", 2, 3, "Shield"], ["Great Shield", 13, 11, "Shield"], ["Exe Shield", 23, 15, "Shield"], ["Dragon Shield", 50, 21, "Shield"], ["Dragon Knight Shield", 53, 28, "Shield"]]
armors = [["Wood Armor", 2, 3, "Armor"], ["Great Armor", 9, 6, "Armor"], ["Exe Armor", 21, 10, "Armor"], ["Dragon Armor", 48, 14, "Armor"], ["Dragon Knight Armor", 54, 22, "Armor"]]
skills = [["Twisting", 25, 10, "Turn around in a circular motion and deal damage all around you", "Attack", 1], ["Regenerate", 25, 10, "You regenerate some health", "Regen", 1], ["Ice Storm", 25, 10, "You start a small Ice Storm", "Attack", 1]]
monsters = [["Spider", 1, 30, 8, 13, 15], ["Huge Spider", 2, 45, 10, 15, 20], ["Baby Dragon", 2, 50, 12, 15, 20], ["Goblin", 3, 45, 15, 19, 25], ["Stone Goblin", 4, 55, 20, 26, 27], ["Cyclop", 5, 70, 30, 36, 33], ["Great Dragon", 6, 100, 40, 43, 40], ["Golden Dragon", 7, 200, 50, 100, 65]]
class Items:
def __init__(self, name, price, attack, type):
self.name = name
self.price = price
self.attack = attack
self.type = type
class Skill:
def __init__(self, name, damage, manacost, description, type, lvl):
self.name = name
self.damage = damage
self.manacost = manacost
self.description = description
self.type = type
self.lvl = lvl
class Monster:
def __init__(self, name, lvl, maxhp, minattack, maxattack, defense):
self.name = name
self.lvl = lvl
self.maxhp = maxhp
self.hp = self.maxhp
self.minattack = minattack
self.maxattack = maxattack
self.defense = defense
self.givegold = random.randint(1, 4) * self.lvl
self.giveexp = lvl * 1.5
Wood_Sword = Items(primarys[0][0], primarys[0][1], primarys[0][2], primarys[0][3])
Great_Sword = Items(primarys[1][0], primarys[1][1], primarys[1][2], primarys[1][3])
Exe_Sword = Items(primarys[2][0], primarys[2][1], primarys[2][2], primarys[2][3])
Dragon_Sword = Items(primarys[3][0], primarys[3][1], primarys[3][2], primarys[3][3])
Dragon_Knight_Sword = Items(primarys[4][0], primarys[4][1], primarys[4][2], primarys[4][3])
Wood_Shield = Items(secondarys[0][0], secondarys[0][1], secondarys[0][2], secondarys[0][3])
Great_Shield = Items(secondarys[1][0], secondarys[1][1], secondarys[1][2], secondarys[1][3])
Exe_Shield = Items(secondarys[2][0], secondarys[2][1], secondarys[2][2], secondarys[2][3])
Dragon_Shield = Items(secondarys[3][0], secondarys[3][1], secondarys[3][2], secondarys[3][3])
Dragon_Knight_Shield = Items(secondarys[4][0], secondarys[4][1], secondarys[4][2], secondarys[4][3])
Wood_Armor = Items(armors[0][0], armors[0][1], armors[0][2], armors[0][3])
Great_Armor = Items(armors[1][0], armors[1][1], armors[1][2], armors[1][3])
Exe_Armor = Items(armors[2][0], armors[2][1], armors[2][2], armors[2][3])
Dragon_Armor = Items(armors[3][0], armors[3][1], armors[3][2], armors[3][3])
Dragon_Knight_Armor = Items(armors[4][0], armors[4][1], armors[4][2], armors[4][3])
rewardbox = [Wood_Sword, Great_Sword, Wood_Shield, Great_Shield, Wood_Armor, Great_Armor]
rewardbox2 = [Great_Sword, Exe_Sword, Great_Shield, Exe_Shield, Great_Armor, Exe_Armor]
rewardbox3 = [Exe_Sword, Dragon_Sword,Exe_Shield, Dragon_Shield,Exe_Armor, Dragon_Armor]
rewardbox4 = [Dragon_Sword, Dragon_Knight_Sword, Dragon_Shield, Dragon_Knight_Shield, Dragon_Armor, Dragon_Knight_Armor]
rewardbox5 = [Dragon_Knight_Sword, Dragon_Knight_Shield, Dragon_Knight_Armor]
Twisting = Skill(skills[0][0], skills[0][1], skills[0][2], skills[0][3], skills[0][4], skills[0][5])
Regenerate = Skill(skills[1][0], skills[1][1], skills[1][2], skills[1][3], skills[1][4], skills[0][5])
Ice_Storm = Skill(skills[2][0], skills[2][1], skills[2][2], skills[2][3], skills[2][4], skills[0][5])
Spider = Monster(monsters[0][0],monsters[0][1],monsters[0][2],monsters[0][3],monsters[0][4],monsters[0][5])
Huge_Spider = Monster(monsters[1][0],monsters[1][1],monsters[1][2],monsters[1][3],monsters[1][4],monsters[1][5])
Baby_Dragon = Monster(monsters[2][0],monsters[2][1],monsters[2][2],monsters[2][3],monsters[2][4],monsters[2][5])
Goblin = Monster(monsters[3][0],monsters[3][1],monsters[3][2],monsters[3][3],monsters[3][4],monsters[3][5])
Stone_Goblin = Monster(monsters[4][0],monsters[4][1],monsters[4][2],monsters[4][3],monsters[4][4],monsters[0][5])
Cyclop = Monster(monsters[5][0],monsters[5][1],monsters[5][2],monsters[5][3],monsters[5][4],monsters[5][5])
Great_Dragon = Monster(monsters[6][0],monsters[6][1],monsters[6][2],monsters[6][3],monsters[6][4],monsters[6][5])
Golden_Dragon = Monster(monsters[7][0],monsters[7][1],monsters[7][2],monsters[7][3],monsters[7][4],monsters[7][5])maps = [["Lorencia", "Lorencia is 1 of the oldest map of the ancient", True, True, [["Lorencia's safe zone"], ["Lorencia Woods"], ["Lorencia Sanctuary"], ["Lorencia Dungeon"], ["Lorencia Boss"]]]]
class Map:
def __init__(self, name, desc, loot, fight, zone):
self.name = name
self.desc = desc
self.loot = loot
self.fight = fight
self.zone = zone
self.curzone = self.zone[0]
self.count = 0
self.walking = 0
mappa = Map(maps[0][0], maps[0][1], maps[0][2], maps[0][3], maps[0][4])发布于 2021-10-05 16:00:25
我假设这是你的第一个这么大的项目,如果是这样的话,那是一个伟大的工作。你这么做真的很酷。
这是代码中最糟糕的问题。你看,调用函数不是免费的,它在调用堆栈中使用空间。这个空间是在函数返回或程序退出时释放的;但是,由于您从来没有从诸如game()、harald()、The升级()等函数返回,所以它将消耗越来越多的空间。手动使程序耗尽堆栈空间是非常困难的,但是在编程中这被认为是一个非常糟糕的模式。尝试使用循环重新思考程序。
中的重复
请考虑以下代码:
if option1 == "twisting" or option1 == "ice storm":
monster.hp -= useskill(option1)
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {useskill(option1)} damage and take {damagetook} damage")
fight(monster)
elif option1 == "regenerate":
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You took {damagetook} damage and healed for {useskill(option1)} hp")
fight(monster)
else:
input("Enter a valid skill name\n")
fight(monster)在任何情况下,执行的最后一行将是fight(monster)。所以你可以把它搬出去,否则:
if option1 == "twisting" or option1 == "ice storm":
monster.hp -= useskill(option1)
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {useskill(option1)} damage and take {damagetook} damage")
elif option1 == "regenerate":
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You took {damagetook} damage and healed for {useskill(option1)} hp")
else:
input("Enter a valid skill name\n")
fight(monster)还有几个地方可以使用这种技术。
线条
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook在代码中重复多次。您可以将它们移动到Monster方法中,并编写如下内容
damagetook = monster.attack(playerig)使用
class Monster:
...
def attack(self, player):
damage = random.randint(self.minattack, self.maxattack)
player.hp -= damage
return damage这将使代码更加紧凑和可读性更强。
全局变量被认为是不好的。您只有一个这样的变量- playerig;但是仍然可以在一个类中收集使用它的所有函数(比如场景或游戏),使playerig成为该类的成员,并且在main()函数中只创建一个场景对象。
Wood_Sword = Items(primarys[0][0], primarys[0][1], primarys[0][2], primarys[0][3])可以缩短为
Wood_Sword = Items(*primarys[0])*意味着将列表解压缩为参数。还可以重写__init__方法以接受列表。
通常,从代码中分离数据是个好主意。你可以保持所有的数据(怪物,项目,地图)在配置文件,而不需要编辑代码,每次你想改变平衡在游戏。我不确定你现在是否需要这个,可能会用它作为下一个版本的想法。
也许你可以在这里用一下。看看文档。
我想这对初学者来说已经足够了。继续你的好工作!
更新
您已经计算了数据成员(attack、defense),这些成员在update方法中更改。这很糟糕,因为您可以忘记调用update。更好的方法是删除数据成员并使用方法获取这些值:
def get_attack(self):
return self.str + self.primary[0].attack + self.agy这样,你永远不会忘记更新它们。另外,通过方法访问所有数据也是一个好习惯(像get_attack这样的getter用于获取数据,set_attack这样的setter来设置数据),因此您可以随时更改公式,比如用项来更改统计数据。
发布于 2021-10-06 19:49:29
这是很多代码。很好,你已经分享了这一切,但我可能不得不停止提供一个完整的重构。
self.vit = 1
self.maxhp = 100 + (self.vit * 2)你会想要像
self.vit = 1
# ...
@property
def max_hp(self) -> int:
return 100 + 2*self.vit与上述内容相关的是,根本没有update;只有返回那些动态计算的派生值的@property函数。
def __init__(self, name: str) -> None。primary是一个列表?玩家一次能持有任意数量的武器吗?如果不是,那么这应该只是对某一项的单个引用。self.agy + (self.armor[0].attack/2)不需要父文件。magicattack应该是由PEP8指定的magic_attack,与其他变量和函数名类似。clear实现。只要您选择,将此程序移植到其他操作系统是相当容易的。 if option == "credits":
input("Just you")
game()
elif option == "skills":
skillupgrade()
elif option == "harald":
harald()
elif option == "inventory":
inventory()
elif option == "explore":
explore(mappa)
elif option == "character":
character()
elif option == "exit":
input("Cyaaa\n")
os.system("exit")
elif option == "save":
savegame()
else:
game()在函数引用字典中。
if map.loot == True,只有if map.lootmonster.lvl == 3 or monster.lvl == 4可以缩写为
monster.lvl in {3, 4}或者更好,因为这个比较应该支持连续的值,
3 <= monster.lvl <= 4harald是一个人,那么它应该是Harold;或者您的意思是herald。playerig.str -= (playerig.str - 1)你是什么意思?这将始终将强度设置为1,更有可能是指
playerig.str = playerig.str - 1这相当于
playerig.str -= 1game绝对不应该从savegame调用。if __name__ == '__main__':之前,你需要一个main()。mappa = Map(
name='Lorencia',
desc='Lorencia is 1 of the oldest map of the ancient',
loot=True,
fight=True,
zones=[
"Lorencia's safe zone",
"Lorencia Woods",
"Lorencia Sanctuary",
"Lorencia Dungeon",
"Lorencia Boss"
],
)注意,zones应该是一个字符串列表,而不是一个字符串列表。
https://codereview.stackexchange.com/questions/268687
复制相似问题