如何从Python2.7中的函数返回变量值?

2024-06-09 00:47:23 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
import time

#universal variables
attack = 1
defend = 2
heal = 3
v = False

player_health = 0
player_damage = 0
player_heal = 0
player_block = 0

ai_health = 0
ai_damage = 0
ai_heal = 0
ai_block = 0

#player classes in the form of dictionaries
sniper = {}
sniper["health"] = 50
sniper["damage"] = random.randint(20,40)
sniper["heal"] = random.randint(2,10)
sniper["block"] = 5

tank = {}
tank["health"] = 200
tank["damage"] = random.randint(2,8)
tank["heal"] = random.randint(5,20)
tank["block"] = 20

def start():
    print "lets play"
    while clas():
        pass
    while game():
        pass
    win()

#get the class of the player
def clas():
    while True:
        Class = raw_input("choose a class:\nsniper = 1\ntank =2\n") #change as stats are added
        try:
            Class = int(Class)
            if Class in (1,2): #change as stats are added
                    Class1 = random.randint(1,2)

    #get the class' stats for the player
                    if Class == 1:
                        player_health = sniper["health"]
                        player_damage = sniper["damage"]
                        player_heal = sniper["heal"]
                        player_block = sniper["block"]

                    if Class == 2:
                        player_health = tank["health"]
                        player_damage = tank["damage"]
                        player_heal = tank["heal"]
                        player_block = tank["block"]

                    #get the class' stats for the ai
                    if Class1 == 1:
                        ai_health = sniper["health"]
                        ai_damage = sniper["damage"]
                        ai_heal = sniper["heal"]
                        ai_block = sniper["block"]

                    if Class1 == 2:
                        ai_health = tank["health"]
                        ai_damage = tank["damage"]
                        ai_heal = tank["heal"]
                        ai_block = tank["block"]
                    break
        except ValueError:
            pass
        print "Oops! I didn't understand that. Please enter a valid number"

在上面的代码中,有一个名为clas()的函数。在这个函数中,有8个关于玩家和ai属性的变量。我希望这些变量复制到第10-18行的变量中,但我不知道如何复制。在


Tags: theifstatsrandomblockaiclassplayer
1条回答
网友
1楼 · 发布于 2024-06-09 00:47:23

通常,要复制任何变量的值,请使用copy.deepcopy函数:

from copy import deepcopy

z = 1
x = {'a': {'z': 12}}

def copy_args(z, x):
    copy_z = deepcopy(z)
    copy_x = deepcopy(x)
    return copy_z, copy_x

copy_z, copy_x = copy_args(z, x)
print(copy_z, copy_x)

有关python-course deepcopy articlepython copy module documentation的详细信息

祝你好运

相关问题 更多 >