附加函数变量

时间:2013-11-25 18:35:05

标签: function variables

我正在创建一个RPG游戏,我在其中使用健康和药水的功能。在每次遇到敌人后,玩家都会失去随机的健康状况。如果英雄剩下药水,他们就会获得给定的健康。我正试图保存下次遭遇时的健康和药水量,健康和药水从上次遇到时是相同的。如何为下一轮追加或保存变量???这是我对该功能的代码。

    import random
    health = 20
    potion = 5
    playerdamage = random.randint(0, 7)
    print("\nDuring the fight you took", playerdamage, "damage!")
    health -= playerdamage
    if potion > 0:
        print("You have a health potion to use!")
        health += 5
        potion -= 1
        print("You gained 5 health back and are now at",health,"health!")
        print("you have", potion, "health potion(s) left!")
    else:
        print("You have no health potions left!")
        print("You have", health, "health left\n")

    return health

这是完整代码

def main():
    choice = None
    while choice != "0":
        print("\nThe time has come to choose your path!")
        print(
"""
0 - quit
1 - Start adventure!
"""
          )
        choice = input("Choice: ")
        if choice == "0":
            print("Good-bye")

        elif choice == "1":
            print("\n\nLets see what kind of hero you would like to be!")
            character_select()
        else:
            print("That is not an option")
    return

def character_select():
     choiceB = None
     while choiceB != "0":
         print("\nWho will you be?")
         print(
            """
0 - return
1 - Warrior
2 - Mage
""")
         choiceB = input("Choice: ")
         if choiceB == "0":
             print("Returning to main menu")

         elif choiceB == "1":
             print("\nYou have chosen the path of the mighty Warrior!")
             input("\nPress enter to start the adventure")
             adventure_start()

         elif choiceB == "2":
             print("\nYou will follow the path of the all powerful Mage!")
             input("\nPress enter to start the adventure")
             adventure_start()

         else:
             print("\nI'm sorry thats not an option")

def adventure_start():
    print("\n\nYou have been asked to venture into a rundown castle \nthat has been recently taken over by a band of highwaymen.")
    print("It has taken several hours to get to the castle.")
    print("As you aproach the castle you see several Highwayman standing outside")
    input("\nPress enter to start your attack!")
    encounter()
    playerhealth()
    input("\nPress enter to continue into the castle")
    print("\nAs you enter the courtyard you see there are 3 enterences!")
    choiceC = None
    while choiceC!= "0":
        print("You see three choices in your path!")
        print("As you look around you can head through the \n1:Tower,\n2:the stairs off the the left or \n3:continue through the Main Castle Door.")
        choiceC = input("Choice: \n\n")
        if choiceC == "1":
            tower()
        elif choiceC == "2":
            stairs()
        elif choiceC == "3":
            main_castledoor()
        else:
            print("That is not one of the options Hero. Please try one of the three paths before its too late!")
    return

def playerhealth():
    import random
    health = 20
    potion = 5
    playerdamage = random.randint(0, 7)
    print("\nDuring the fight you took", playerdamage, "damage!")
    health -= playerdamage
    if potion > 0:
        print("You have a health potion to use!")
        health += 5
        potion -= 1
        print("You gained 5 health back and are now at", health,"health!")
        print("you have", potion, "health potion(s) left!")
    else:
        print("You have no health potions left!")
        print("You have", health, "health left\n")
    return 


def encounter():
    import random
    highwayman = random.randint(2,4)
    print("\n\nthere are",highwayman ,"Highwayman")
    print("You attack the closest Highwayman\n")
    while highwayman > 0:
        highwaymanhealth = 5
        while highwaymanhealth >= 1:
            damage = random.randint(5,10)
            highwaymanhealth -= damage
            print("You hit the Highwayman and did", damage, "damage to them!")
            highwayman -= 1
            print("there are", highwayman, "left.")
    print("The Highwayman have been defeated!")
    return


def stairs():
    print("Something about the stairs\n draws you attention and you start heading toward them.")
    print("As you reach the top of the stairs you enter an empty hallway.")
    print("You hear voices coming from a behind a door at the end of the hall.")
    print("Slowly creeping towards the door you verify that the voices are coming from within.")
    print("Gently openning the door you find yourself at the top of a stair case within the Great Hall!")
    greathall()
    return 

def tower():
    print("You hear a noice coming from the tower and run to the door!")
    print("As you run into the tower you come face to face with another group of Highwayman!")
    encounter()
    playerhealth()
    greathall()
    return

def main_castledoor():
    print("As you enter the main enterence you come across another group of Highwayman!")
    encounter()
    playerhealth()
    print("")
    greathall()
    return

def greathall():
    input("\nPress enter to continue.\n\n")
    print("Upon entering the Great Hall you realize that you have just come face to face with the main force of the Highwayman and their leader!")
    print("")
    encounter()
    final_step()
    return

def final_step():
    print("You are victorious in defeating the Highwayman! As you look around you see a chest full of Gold and a strange orb.")
    print("While you collect the gold you are careful not to touch the orb and walk away. However, as you are about to leave you can't get it off your mind...")
    print("\n\n Slowly walking back to the chest you stare at the orb. Entranced by the swirling smoke within you find yourself reaching towards it.")
    print("As you are about to grab the orb you stop. Something doesn't feel right, but you grab the orb anyways.")
    print("Instantly you realize it was a mistake. Your body feels as if it was just jerked backwards and everything goes black.")
    print("\n\n\nThanks for playing!")
    print("You have reached the end")
    main()
    return




main()

1 个答案:

答案 0 :(得分:0)

这里要考虑两个方面:如何组织代码以及如何组织数据。要反复“遇到敌人”,请使用子程序(即def语句)。要存储数据,您有两种选择:创建播放器类型或将数据存储在全局变量中。如果你可以保证游戏只涉及一个玩家,那么使用全局变量更容易,但是可扩展性更低 走全球路线:

import random
health = 20
potion = 5

def encounterEnemy():
    playerdamage = random.randint(0, 7)
    print("\nDuring the fight you took", playerdamage, "damage!")
    health -= playerdamage
    if potion > 0:
        print("You have a health potion to use!")
        health += 5
        potion -= 1
        print("You gained 5 health back and are now at",health,"health!")
        print("you have", potion, "health potion(s) left!")
    else:
        print("You have no health potions left!")
        print("You have", health, "health left\n")
    return health

然后,每次拨打encounterEnemy时,玩家的生命总数和药水都会相应调整。

创建新数据类型:

import random
class Player:
    def __init__(health, potion):
        self.health = health
        self.potion = potion
    def encounterEnemy():
        playerdamage = random.randint(0, 7)
        print("\nDuring the fight you took", playerdamage, "damage!")
        self.health -= playerdamage
        if self.potion > 0:
            print("You have a health potion to use!")
            self.health += 5
            self.potion -= 1
            print("You gained 5 health back and are now at", self.health, "health!")
            print("you have", self.potion, "health potion(s) left!")
        else:
            print("You have no health potions left!")
            print("You have", self.health, "health left\n")
        return self.health

currPlayer = Player(20, 5)
currPlayer.encounterEnemy()

创建新数据类型也很有用,因为它允许您将与问题相关的所有数据“捆绑”在一起。