我无法更改变量的值

时间:2014-08-14 20:57:54

标签: python project

我正在制作一个关于制作的游戏,我无法改变变量的值,我不知道为什么。这是我的一些代码:

#Setting Up
#-------------------------------------------------------------------------------
sapling = 3
log = 0
twig = 0
stick = 0
boulder = 5
pickaxe = 1
axe = 1
coal = 0
torch = 0
#-------------------------------------------------------------------------------
#Inventory
#-------------------------------------------------------------------------------
inventory = {
    "sapling" : sapling,
    "log" : log,
    "twig" : twig,
    "stick" : stick,
    "boulder" : boulder,
    "pickaxe" : pickaxe,
    "axe" : axe,
    "coal" : coal,
    "torch" : torch,
    }
#-------------------------------------------------------------------------------
#InGameItems
#-------------------------------------------------------------------------------
game = {
    "Items =",
    "sapling",
    "log",
    "twig",
    "stick",
    "boulder",
    "pickaxe",
    "axe",
    "coal",
    "torch",
    }
#-------------------------------------------------------------------------------
#Help
#-------------------------------------------------------------------------------
h = {
    "(i)" : "To access inventory",
    "(?)" : "For help",
    "(g)" : "To check out all in game items",
    "plant (item)" : "To plant item",
    "craft (item)" : "To craft an item",
    }
#--------------------------------------------------------------------------------
#Begin Code
#-------------------------------------------------------------------------------
print("To ask for help type (?)")
while 1:
    player = input(":")
    if player == "?":
        print(h)
    if player == "i":
        print(inventory)
    if player == "g":
        print(game)
    if player == "plant sapling" and sapling != 0 and axe != 0:
        print("Planting")
        print("You planted a sapling!")
        print("Your sapling turned into a tree!")
        print("Cutting tree")
        print("2 logs gained!")
        log += 2
        sapling -= 1

所以这就是我的问题,我正在增加日志的价值,但是当我玩游戏日志时不会增加。我似乎无法找出如何增加日志的价值。

2 个答案:

答案 0 :(得分:1)

当你这样做时:

inventory = {
    ...
    "log" : log
    ...
}

您在log内复制了0inventory)的引用,但当您执行log += 2时,您并未真正更改该值log的{​​{1}},您正在创建一个log + 2的临时变量并将其链接到名称loglog内的inventory仍引用旧的log,即0

因此,您应该log += 2而不是inventory["log"] += 2

答案 1 :(得分:-1)

您违反了这样一个事实,即您的词典是按而不是按引用构建的。具体来说,字典条目

"log": log

意味着“密钥”log“的值将是当时log变量中发生的任何事情。”这意味着“将log的当前值和 copy 作为具有键”log“的字典条目的值。现在有两个单独的值,而不是一个值字典对于键“log”有自己的值,它是一个恰好是0的整数,而log是一个包含整数0的完全独立的变量。改变一个不会影响另一个。而不是log += 2,你需要把:

inventory["log"] += 2