views:

42

answers:

2

I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for the "hero" to fight. The issue I am running into is that python is copying from list to list by reference, not value (I think), because of the code shown below...

import random

#ene = [HP,MAXHP,loDMG,hiDMG]   
enemies = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]]
genENE = []  

#skews # of ene's to be gen, favoring 1,2, and 3 
eneAppears = 3

for i in range(0,eneAppears):
    num = random.randint(5,5)
    if num <= 5:
        genENE.insert(i,enemies[0])
    elif num >= 6 and num <=8:
        genENE.insert(i,enemies[1])
    else:
        genENE.insert(i,enemies[2])

#genENE = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]]          
for i in range(0,eneAppears):
    if eneAppears == 1:
        print "A " + genENE[0][4] + " appears!"
    else:
        while i < eneAppears:
            print "A " + genENE[i][4] + " appears!"
            i = eneAppears

genENE[1][0] = genENE[1][0] - 1
print genENE

Basically I have a "master" list of enemies that I use to copy whatever one I want over into an index of another list during my first "for" loop. Normally the randomly generated numbers are 1 through 10, but the problem I'm having is more easily shown by forcing the same enemy to be inserted into my "copy" list several times. Basically when I try to subtract a value of an enemy with the same name in my "copy" list, they all subtract that value (see last two lines of code). I've done a lot of searching and cannot find a way to copy just a single index from one list to another. Any suggestions? Thanks!

+1  A: 

Change

genENE.insert(i,enemies[0])

to

genENE.insert(i,enemies[0][:])

This will force the list to be copied rather than referenced. Also, I would use append rather than insert in this instance.

Justin Peel
Fantastic! Amazing how I was just 3 characters away from success...I also implemented append as you've suggested, I'm assuming because it's a little faster, cleaner, and less error prone? Thanks a million!
thebill
list(enemies[0]) does the same thing as enemies[0][:], and is a little more explicit, but the choice is a matter of taste.
Russell Borogove
@Ruseel Borogove, you're quite right. My conscience had been telling me that I should have mentioned that.
Justin Peel
I like list(enemies[0]) too and less typing, can't beat that. Funny how syntaxy this is, two different syntaxes that perform the same exact thing, interesting.
thebill
A: 

they all subtract that value What do you mean do they all? If you mean both lists, you're problem is because you're only referencing the list NOT creating a second one.

John