Reputation: 55
Long story in short, I am getting back into coding after a while away, and thought I'd do something relatively (for me) straightforward, which is converting a C program into Python. I'm familiar with basic C, and am familiar with basic programming concepts, so to me what I'm asking shouldn't be that difficult.
I'm rewriting the classic Star Trek
text game from C
into Python
. One function sets up the game universe:
After a lot of teeth-gnashing, I have come to the conclusion I am using lists incorrectly. My code for one function is:
def setupGalaxy(difficulty):
for x in range(0,8):
for y in range(0,8):
sectors[x][y] = 0
quadrants[x][y].baseHere = 0
quadrants[x][y].klingonCount = 0
quadrants[x][y].starCount = 0
klingonsHere = 0
numBases = 0
for x in range(0,8):
for y in range(0,8):
J = random.randint(1,99)
baseHere = 0
if (J < 5):
numBases += 1
baseHere = 1
temp = getKlingons(difficulty)
klingonsHere += temp
quadrants[x][y].klingonCount = temp
quadrants[x][y].baseHere = baseHere
quadrants[x][y].starCount = random.randint(1,4)
print quadrants[x][y].klingonCount,quadrants[x][y].baseHere,quadrants[x][y].starCount," ",
print
numKlingons = klingonsHere
for x in range(0,8):
for y in range(0,8):
print quadrants[x][y].klingonCount,quadrants[x][y].baseHere,quadrants[x][y].starCount," ",
return
What the function should do is: Initiate the contents of 2-dimensional list quadrants to 0 (probably not necessary, but gives me some peace of mind), then generate a random number of Klingons, starbases and stars and place them within the lists.
My problem is this: I included some print statements to let me see the output of the assignments, and he first print statement spits out exactly what I wanted to see, and random collection of stars, Klingons, etc.
The second print statement prints out the same number 64 times. In between the first and the second time, I can't see what has changed.
I assume I'm doing something wrong with lists. Can anyone help?
Joseph.
Upvotes: 3
Views: 73
Reputation: 55
It seems I need to go back and do some more homework before starting out coding again. There are a few pits and traps with Python that I've not encountered before, and as such I'd better get some proper advice, rather than trying to attach it piecemeal. Many thanks for everybodys help.
Upvotes: 0
Reputation: 2052
In Python, If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
x = 4;
def f():
x = 6
print(x)
f()
print(x)
Outputs:
6
4
Insert an explicit global declaration at the start of function
x = 4;
def f():
global x
x = 6
print(x)
f()
print(x)
Outputs:
6
6
Read This for details.
Upvotes: 1