I am making a puzzle game with Python, it's supposed to be a 3x3 slide puzzle. I've made a class that stores name/id and x,y coordinates.
In the function up() I want to move the asterisk (*) up one row and in theory it should work but apparently not. I have a function that finds the class instance associated with two coordinates (find()) and it returns an instance of the class called symbol.
Layout of the slide puzzle:
1 2 3
4 5 6
7 8 *
When I try to assign the new values to the class instance above me (represented by the 6) nothing gets assigned. I would like to use the global keyword but that seems like such a hassle because then I would have to check every coordinate and then say what variable to change.
This is a puzzle game so it's really important that the player can move around without issues. I haven't tried anything else since I don't know how to proceed from this point.
class symbol:
def __init__(self, x, y, val):
self.x = x
self.y = y
self.val = val
s1 = symbol(1, 1, "1")
s2 = symbol(2, 1, "2")
s3 = symbol(3, 1, "3")
s4 = symbol(1, 2, "4")
s5 = symbol(2, 2, "5")
s6 = symbol(3, 2, "6")
s7 = symbol(1, 3, "7")
s8 = symbol(2, 3, "8")
s9 = symbol(3, 3, "*")
def getPos():
xPos = 0
yPos = 0
for element in symbols:
if element.val == "*":
xPos = element.x
yPos = element.y
else:
pass
return xPos, yPos
def find(x, y):
xPos = 0
yPos = 0
found = symbol(100, 100, "FIND")
for element in symbols:
if element.x == x and element.y == y:
found.x = x
found.y = y
found.val = element.val
else:
pass
return found
def up():
x, y = getPos()
if y > 1:
newBlock = find(x, y-1)
myBlock = find(x, y)
myBlock.val = newBlock.val
newBlock.val = "*"
clear()
draw()
print(f"myBlock: {myBlock.val} ({myBlock.x}, {myBlock.y}), newBlock: {newBlock.val} ({newBlock.x}, {newBlock.y})")
else:
pass
#cannot go higher
The problem is that your find function is making a new symbol and returning that. When up() modifies the result of find(), it's just changing some copy that lives outside of (what I assume is) your list of symbols.
One solution would be to just return the element from the list in find. i.e.
for element in symbols:
if element.x == x and element.y == y:
return element
return None
Related
Hello i am trying to learn some basics by making some mistakes.
I am making a basic python based snake game, using as little of non built in modules as i can.
at the moment the main one is tkinter.
Some of my logic is changing a member of a list, when i do not expect it do so and i can't see why.
The change is happening at line 60 (21) where index 1 is changed to equal index 0
when only index 0 should change only when "middle" occurs on line 71 (31)
the error is within this function
self.player[1] changes when i did not expect
def move(self):
print("old snake pos {}".format(self.player))
for i in range(len(self.player)-1, -1, -1):
# runs through loop backwards as the positions of the next piece needs to be known
print(i)
if i == len(self.player)-1:
print("last piece")
if self.eat():
print("eat = True")
self.player.append(self.player[-1])
print("{} changed from {} to {}".format(i, self.player[i], self.player[i-1]))
self.player[i] = self.player[i-1]
else:
if i == 0:
print("Head")
print(self.vel)
print(self.player[0])
print(self.player[1])
self.player[0][0] = self.player[0][0] + self.vel[0]
print("why has it changed????????")
print(self.player[0])
print(self.player[1])
self.player[0][1] = self.player[0][1] + self.vel[1]
print(self.player[1])
print(self.player)
continue
print("middle piece")
print("{} changed from {} to {}".format(i, self.player[i], self.player[i - 1]))
self.player[i] = self.player[i - 1]
print(self.player[i])
print(self.player[i])
print(self.player)
print("new snake pos {}".format(self.player))
i have tried different checks, but it doesnt seem to be doing any line that i dont expect at the right time.
and the full code is this:
# programme for learning more about creating graphical displays in Python
# will start with some investigation and use of tkinter resource
# then move to creating a snake style game
import tkinter as tk
import random as r
import time
class SnakeApp(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.setup()
self.gameloop()
def mat2str(self, matrix):
string = ""
for y in matrix:
for x in y:
string += x
string += "\n"
return string
# random an int co-ordinate
def newpos(self):
return [r.randint(0, self.wx), r.randint(0, self.wy)]
# check if the fruit has been eaten
def eat(self):
if any([s == self.fruit for s in self.player]):
print("fruit col detected {}".format(self.fruit))
# new position
self.fruit = self.newpos()
# increase the game speed by 2.5%
self.dt = self.dt * 0.975
# need to add a segment to the player
return True
# move the game 1 turn and compute all the logic before the next frame is drawn
def move(self):
print("old snake pos {}".format(self.player))
for i in range(len(self.player)-1, -1, -1):
# runs through loop backwards as the positions of the next piece needs to be known
print(i)
if i == len(self.player)-1:
print("last piece")
if self.eat():
print("eat = True")
self.player.append(self.player[-1])
print("{} changed from {} to {}".format(i, self.player[i], self.player[i-1]))
self.player[i] = self.player[i-1]
else:
if i == 0:
print("Head")
print(self.vel)
print(self.player[0])
print(self.player[1])
self.player[0][0] = self.player[0][0] + self.vel[0]
print("why has it changed????????")
print(self.player[0])
print(self.player[1])
self.player[0][1] = self.player[0][1] + self.vel[1]
print(self.player[1])
print(self.player)
continue
print("middle piece")
print("{} changed from {} to {}".format(i, self.player[i], self.player[i - 1]))
self.player[i] = self.player[i - 1]
print(self.player[i])
print(self.player[i])
print(self.player)
print("new snake pos {}".format(self.player))
def up(self, event):
print("up")
if self.vel != [0, 1]:
self.vel = [0, -1]
def down(self, event):
print("down")
if self.vel != [0, -1]:
self.vel = [0, 1]
def left(self, event):
print("left")
if self.vel != [1, 0]:
self.vel = [-1, 0]
def right(self, event):
print("right")
if self.vel != [-1, 0]:
self.vel = [1, 0]
def drawempty(self, wx, wy):
frame = []
for y in range(wy):
xlayer = []
for x in range(wx):
xlayer.append("-")
frame.append(xlayer)
return frame
def redraw(self, player, object):
# self.drawempty(self.wx, self.wy)
# replaced redraw each frame with a static empty frame build
print(self.gameframe)
self.gameframe = self.drawempty(self.wx, self.wy)
print(self.gameframe)
# set the string in the co-ord of the object to A
# check for collision needs to occur before this - all game logic before
# set the string in the co-ords of all players to *
print(object)
self.gameframe[object[1]][object[0]] = "A"
for b in player:
self.gameframe[b[1]][b[0]] = "*"
def setup(self):
# set game size
self.wx = 20
self.wy = 20
self.master.geometry("300x300")
self.vel = [-1, 0]
self.dt = 1
# create text matrices of spaces of size wx * wy
#self.gameframe = tk.Variable()
self.gameframe = []
#self.emptyframe = tk.Variable()
self.emptyframe = self.drawempty(self.wx, self.wy)
self.gameframe = self.emptyframe
# create a player and fruit object in the space
self.player = [[round(self.wx / 2), round(self.wy / 2)],[round(self.wx / 2) + 1, round(self.wy / 2)],[round(self.wx / 2) + 2, round(self.wy / 2)]]
self.fruit = self.newpos()
self.redraw(self.player, self.fruit)
self.game = tk.Text(self, height=self.wy, width=self.wx)
self.game.pack()
self.game.insert(tk.END, self.mat2str(self.gameframe))
self.master.bind("<Up>", self.up)
self.master.bind("<Down>", self.down)
self.master.bind("<Left>", self.left)
self.master.bind("<Right>", self.right)
def gameloop(self):
while True:
self.redraw(self.player, self.fruit)
self.game.delete('1.0', tk.END)
self.game.insert(tk.END, self.mat2str(self.gameframe))
self.move()
self.master.update()
time.sleep(self.dt)
Snake = tk.Tk()
app = SnakeApp(master=Snake)
The problem can be found at your move function as this point (Line 122)
self.player[i] = self.player[i - 1] # i == 1, self.player[1] = self.player[0]
At the point when i is 1 this code block is reached and it sets self.player[1] to self.player[0]
The problem is that self.player[0] after that is equal by reference to self.player[1], which means that when one changes, the other does as well (which you said was your problem).
What you need to do to prevent that from happening is to create a copy of self.player[i-1] and set that equal to self.player[i]. This can be achieved through multiple ways.
In your case because you have a list of lists the following should be fine
self.player[i] = [item for item in self.player[i-1]] # Create a new list
if you want use a built-in functions for this you can use deepcopy
from copy import deepcopy
# ...
self.player[i] = deepcopy(self.player[i-1])
Note that this behavior can also be found on lines 25,43, 104 and 122. So you'll have to change all of them to create a copy as shown above.
The code that should be modified is:
self.player[i] = self.player[i - 1]
When you change element 1 to be element 0, you are not making a copy but making them pointing to the same element, which is 0. So when you change element 0, element 1 change as well.
Example why this leads to what you see in code:
player = [[1,2], [3,4]]
i = 1
player[i] = player[i - 1]
player[0][0] = 100
print(player)
[[100, 2], [100, 2]]
One quick solution to create a copy:
self.player[i] = [x for x in self.player[i - 1]]
I am making game sort of like Minecraft using python. I have a world that the user can walk around and look around in but I don't know how to make it so they can break and place blocks.
I need to know how to calculate the block that they are looking at from a 3d array of the blocks in the world (blocks, format:[[[a,b,c],[d,e,f],[g,h,i]],[[j,k,l],[m,n,o],[p,q,r]],[[s,t,u],[v,w,x],[y,z,0]]]), their position (x,y,z) and head rotation (xrot,yrot).
I also only need it in a certain distance away from where they are, maybe 5 blocks. I tried to find a function for a line and kind of follow it but that didn't work out and I looked around on the internet and I couldn't find what I needed.
I need to be able to figure out which block they would break or where a new block would go based of the side they are looking at.
I need to find which face of which cube I am looking at. This is the code I made but some of the math must be off because it isn't working.
def get_looking_at(xrot, yrot, xpos, ypos, zpos, blocks, reach):
xrot, yrot = math.radians(xrot), math.radians(yrot)
xform = sin(xrot)*cos(yrot)+xpos
yform = sin(yrot)+ypos
zform = -(cos(xrot)*cos(yrot))+zpos
xforward = xform-xpos >= 0
yforward = yform-ypos >= 0
zforward = zform-zpos >= 0
if xforward:
xset = [floor(x+xpos+.5)+.5 for x in range(reach)]
else:
xset = [floor((-x)+xpos+.5)-.5 for x in range(reach)]
if yforward:
yset = [ceil(y+ypos) for y in range(reach)]
else:
yset = [floor((-y)+ypos) for y in range(reach)]
if zforward:
zset = [floor(z+zpos+.5)+.5 for z in range(reach)]
else:
zset = [floor((-x)+xpos+.5)-.5 for x in range(reach)]
xint = []
yint = []
zint = []
for x in xset:
y = ((yform-ypos)*x)/(xform-xpos)
z = ((zform-zpos)*x)/(xform-xpos)
xint.append((x, y+ypos, z+zpos))
for y in yset:
x = ((xform-xpos)*y)/(yform-ypos)
z = ((zform-zpos)*y)/(yform-ypos)
yint.append((x+xpos, y, z+zpos))
for z in zset:
x = ((xform-xpos)*z)/(zform-zpos)
y = ((yform-ypos)*z)/(zform-zpos)
zint.append((x+xpos,y+ypos,z))
intercepts = dict()
for pos in xint:
intercepts[(pos[0]-xpos)**2+(pos[1]-ypos)**2+(pos[2]-zpos)**2] = (pos[0], pos[1], pos[2], "x")
for pos in yint:
intercepts[(pos[0]-xpos)**2+(pos[1]-ypos)**2+(pos[2]-zpos)**2] = (pos[0], pos[1], pos[2], "y")
for pos in zint:
intercepts[(pos[0]-xpos)**2+(pos[1]-ypos)**2+(pos[2]-zpos)**2] = (pos[0], pos[1], pos[2], "z")
indices = [x for x in intercepts]
indices.sort()
for index in indices:
connection = intercepts[index]
if xforward:
x = floor(connection[0]+.5)
xdir = "e"
else:
x = ceil(connection[0]-.5)
xdir = "w"
if yforward:
y = floor(connection[1])
ydir = "d"
else:
y = floor(connection[1])+1
ydir = "u"
if zforward:
z = ceil(connection[2]-.5)
zdir = "n"
else:
z = floor(connection[2]+.5)
zdir = "s"
print(x,y,z)
try:
if blocks.get_data(x, y, z) != None:
if math.sqrt(index) <= reach:
if connection[3] == "x":
return x, y, z, xdir
if connection[3] == "y":
return x, y, z, ydir
if connection[3] == "z":
return x, y, z, zdir
else:
return
else:
continue
except IndexError:
continue
return
You could make a sphere of contact around the player and use a radius "protruding" from the player's face.
Radius r would be the maximum distance the user could look at a block and still be able to affect it.
Using triangles you could detect if the end of the radius is inside a block or not, etc.
Im trying to make a stepping function in python for rhino,
The function is supposed to make a step in a random direction, without going backwards.
How do i prevent a step back?
import rhinoscriptsyntax as rs
import random as r
r.seed(seed)
class Walker:
def __init__(self):
self.x = 0
self.y = 0
def point(self):
shape = rs.AddPoint(self.x, self.y, 0)
return shape
def step(self):
choice = r.randint(0,3)
choice = r.randint(1,3)
if (choice == 0):
self.x = self.x + r.choice(uList)
elif (choice == 1):
self.x = self.x - r.choice(uList)
elif (choice == 2):
self.y = self.y + r.choice(uList)
else:
self.y = self.y - r.choice(uList)
uList = [8,11,14]
w = Walker()
pList = []
for t in range(time):
w.step()
pList.append(w.point())
for t-1 in range(time):
a = pList
This line:
choice = r.randint(0,3)
chooses one of 4 directions randomly. But if you don't want to go backwards, then you only want forward, left and right. So change the parameters to randint() so that it only chooses from 3 possible numbers, avoiding the one that corresponds to the direction you are calling backwards, whichever that is.
So i'm making a genetic algorithm in python. The goal is for the "organism" to get to the top of the screen (x,20). I have a loop that creates the population which is a list of objects of type "Organism". Here is the code for the Organism class:
class Organism(object):
def __init__(self, genes,ID):
self.genes = genes
self.position = [0,0]
self.thisTime=str()
self.geneTranslation = []
self.ID=ID
def move(self,d):
if d == "f" or d == "forward":
self.position[1] += 1
elif d == "b" or d == "back":
self.position[1] -= 1
elif d == "r" or d == "right":
self.position[0] += 1
elif d == "l" or d == "left":
self.position[0] -= 1
print(self.position)
def isInContactWith(self,point):
point = list(point)
if self.position == point:
return True
else:
return False
def run(self):
for i in range(0,4):
if i == 0:
self.geneTranslation.extend(["f"] * self.genes[0])
elif i == 1:
self.geneTranslation.extend(["b"] * self.genes[1])
elif i == 2:
self.geneTranslation.extend(["r"] * self.genes[2])
elif i == 3:
self.geneTranslation.extend(["l"] * self.genes[3])
r.shuffle(self.geneTranslation)
for x in range(1,20):
self.thisTime = r.choice(self.geneTranslation)
self.move(self.thisTime)
As you can see, the genes specify the chance of a particular move. The problem is in the for loop that creates the population and runs it(ive added prints for debugging):
population = []
yValues={}
running = True
BestOrganism=Organism([25,25,25,25],0)
SecondOrganism=Organism([25,25,25,25],1)
for count in range(5):
for x in range(10):
a = lambda: r.randint(0, 3)
c = lambda: r.randint(-1, 1)
b = BestOrganism.genes
anOrganism = Organism(b,x)
anOrganism.genes[a()]+=c()
population.append(anOrganism)
for j in range(len(population)):
print("Organism " + str(population[j].ID) + str(population[j].genes))
population[j].run()
yValues[population[j].ID]=population[j].position[1]
if population[j].position[1]>=20:
print(population[j].genes)
running = False
break
BestOrganism=max(yValues)
for k in range(len(population)):
if population[k].ID==BestOrganism:
BestOrganism=population[k]
print(yValues[max(yValues)])
print(str(population)+"\n"+str(yValues)+"\n"+str(BestOrganism.genes))
population=[]
yValues={}
No errors pop up but, whenever I try to "mutate" a particular part of the organism's genes with anOrganism.genes[a()]=c(), it ends up mutating every organism in the list, even the ones not yet created, so that all of their genes are the exact same at the end (as seen in the final product). Why is python doing this?
It's because of this line: anOrganism = Organism(b,popPos).
So on the first iteration of the loop, you create an Organism and set the self.genes to b. Then you modify the .genes of that organism you just created.
When you iterate through the loop again, you are creating a new organism but with the same exact list, so it has the changes from the previous one.
Basically, there is only one b, and you are setting the .genes attribute of every organism to point to that single list. So any and everytime you change it, it changes for all of the organisms.
What you need to do is be sending in a copy of b to the constructor of Organism.
And then change the line anOrganism = Organism(b,popPos) to be
anOrganism = Organism(list(b), popPos)
The key is these lines:
b = BestOrganism.genes
anOrganism = Organism(b,popPos)
The list of genes will be shared by every organism created by that line. That is, anOrganism.genes is exactly the same object as BestOrganism.genes. So a change to BestOrganism.genes is seen in anOrganism.genes.
Python has an easy way to make a copy of a list, using "slicing". Change the line to this:
anOrganism = Organism(b[:],popPos)
Now anOrganism has its own genes, starting off identical to but still distinct from BestOrganism's genes.
Postscript:
Here is a simplified form, using literal ints instead of the random functions:
>>> class Organism(object):
... def __init__(self, genes, ID):
... self.genes = genes
... self.ID = ID
...
>>> zero = Organism([25,25,25,25],0)
>>> one = Organism(zero.genes, 1)
>>> two = Organism(zero.genes[:], 2)
>>> one.genes[2] += 5
>>> two.genes[3] += 7
>>> zero.genes
[25, 25, 30, 25]
>>> one.genes
[25, 25, 30, 25]
>>> two.genes
[25, 25, 25, 32]
>>>
So I am programming a checkers game, and the problem I am having is with creating several pieces in a loop. I have the class creation part of the code, which I won't post here, and the rest, which I'm posting, but I don't know how to change the variable the loop is about to use. If you can lend me a hand and clear this out, I would be thankful.
Sorry for posting my code as image, I'm new to this website ( and programming) and couldn't format so that the website would accept my post. I really hope it's ok for you guys to help me!
Thanks for the help!
Further clarification: I need to use a different "piece" creation everytime the loop runs. That means the first loop has to create piece1, then piece2, then piece3... and so forward
EDIT: Posting whole code. I know format is wrong, can't help it. So, hope somebody can fix it.
class Piece:
def __init__(self, kind, yposition, xposition):
self.color = kind
self.ypos = xposition
self.xpos = yposition
def getColor(self):
return self.getColor
def adjustY(self, change):
self.ypos = self.ypos + change
def adjustX(self, change):
self.xpos = self.xpos + change
def getY(self):
return self.ypos
def getX(self):
return self.xpos
def mover(self, direction):
self.direc = direction
if self.direc == "right" and self.color == "white":
for n in alist:
if n.getY == (self.getY - 1) and n.getX == (self.getX + 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(-1)
self.adjustX(+1)
elif self.direc == "left" and self.color == "white":
for n in alist:
if n.getY == (self.getY - 1) and n.getX == (self.getX - 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(-1)
self.adjustX(-1)
elif self.direc == "right" and self.color == "black":
for n in alist:
if n.getY == (self.getY + 1) and n.getX == (self.getX + 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(+1)
self.adjustX(+1)
else:
for n in alist:
if n.getY == (self.getY + 1) and n.getX == (self.getX - 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(+1)
self.adjustX(-1)
piece1 = 0
piece2 = 0
piece3 = 0
piece4 = 0
piece5 = 0
piece6 = 0
piece7 = 0
piece8 = 0
piece9 = 0
piece10 = 0
piece11 = 0
piece12 = 0
alistb1 = [piece1,piece2,piece3,piece4,piece5,piece6,piece7,piece8,piece9,piece10,piece11,piece12]
k = 2
for i in range(0,11):
if i >= 0 and i <5:
j = 8
m = 0
elif i >= 5 and i < 9:
j = 7
m = 1
else:
j = 6
m = 0
alistb1[i] = Piece("white",j,(m + 1 + i * k))
print(alistb1[i].getY())
# print(piece7.getY()) test reasons
PS: def mover is not ready yet.
You do not need to assign a variable for each piece. You are already using a list for your pieces. Instead of writing piece1, you can just write pieces[0]. (You do need to note that lists start with index 0.)
range has an exclusive right bound. This means that it is not included, your range ends with one less than that value. You want to use range(0,12).
In python, you can add to lists dynamically. You do not need to allocate enough spaces to fit your pieces. You can use the .append() method of lists.
One way to write your code now is this:
pieces = []
for i in range(0, 12): # 0-11
if i < 5:
pieces.append(Piece("white", 8, 1 + i*2))
elif i < 9:
pieces.append(Piece("white", 7, 2 + i*2))
else:
pieces.append(Piece("white", 6, 1 + i*2))
I took the liberty of simplifying your conditional statements (i will always be >= 0 and if i < 5 is false, then the inverse, i >= 5, is true, so you don't need to restate it in your elif) and getting rid of j, k, and m which are unnecessary variables and can be replaced with literals to save memory.
One more thing: your implementation of getColor will return the function object itself. I think you wanted to do:
def getColor():
return self.color
Use a dictionary and a for loop:
pieces = {}
# I'm assuming you want 12 pieces since your list has 12 pieces
for i in range(1,13): # range starts at m so, range(m,n) iterates from m up to n-1
# I would suggest using more descriptive variable names if you can, row or column for example
if i >= 0 and i <5:
j = 8
m = 0
elif i >= 5 and i < 9:
j = 7
m = 1
else:
j = 6
m = 0
pieces['piece{}'.format(i)] = Piece("white",j,(m + 1 + i * k))
This should do what you want unless I am misunderstanding you. Also this isn't C++ you don't need those get methods you can simply Piece.color to get the color attribute of a piece.
Use the dictionary to access the pieces, pieces['piece1'].whatever(). However for brevity's sake you don't need to pieces['piece{}.format(i)] you can just pieces[i] and the piece would be accessed pieces[1].whatever().
More info on dictionaries http://docs.python.org/3.3/tutorial/datastructures.html#dictionaries
What I have and it works with no errors:
class Piece:
def __init__(self, kind, yposition, xposition):
self.color = kind
self.ypos = xposition
self.xpos = yposition
def getColor(self):
return self.getColor
def adjustY(self, change):
self.ypos = self.ypos + change
def adjustX(self, change):
self.xpos = self.xpos + change
def getY(self):
return self.ypos
def getX(self):
return self.xpos
def mover(self, direction):
self.direc = direction
if self.direc == "right" and self.color == "white":
for n in alist:
if n.getY == (self.getY - 1) and n.getX == (self.getX + 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(-1)
self.adjustX(+1)
elif self.direc == "left" and self.color == "white":
for n in alist:
if n.getY == (self.getY - 1) and n.getX == (self.getX - 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(-1)
self.adjustX(-1)
elif self.direc == "right" and self.color == "black":
for n in alist:
if n.getY == (self.getY + 1) and n.getX == (self.getX + 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(+1)
self.adjustX(+1)
else:
for n in alist:
if n.getY == (self.getY + 1) and n.getX == (self.getX - 1):
pass
# NOT YET IMPLEMENTED
else:
self.adjustY(+1)
self.adjustX(-1)
k=2
pieces = {}
# I'm assuming you want 12 pieces since your list has 12 pieces
for i in range(1,13): # range starts at m so, range(m,n) iterates from m up to n-1
# I would suggest using more descriptive variable names if you can, row or column for example
if i >= 0 and i <5:
j = 8
m = 0
elif i >= 5 and i < 9:
j = 7
m = 1
else:
j = 6
m = 0
pieces['piece{}'.format(i)] = Piece("white",j,(m + 1 + i * k))
Output:
>>> pieces['piece1'].color
'white'
>>> pieces['piece3'].color
'white'
>>> pieces['piece3'].xpos
8
>>> for key in pieces:
print(key, pieces[key])
piece8 <__main__.Piece object at 0x000000000329A4E0>
piece9 <__main__.Piece object at 0x000000000329A550>
piece6 <__main__.Piece object at 0x000000000329A400>
piece7 <__main__.Piece object at 0x000000000329A470>
piece4 <__main__.Piece object at 0x000000000329A320>
piece5 <__main__.Piece object at 0x000000000329A390>
piece2 <__main__.Piece object at 0x0000000003287DA0>
piece3 <__main__.Piece object at 0x000000000329A2B0>
piece1 <__main__.Piece object at 0x00000000031D9CF8>
piece10 <__main__.Piece object at 0x000000000329A5C0>
piece11 <__main__.Piece object at 0x000000000329A630>
piece12 <__main__.Piece object at 0x000000000329A6A0>
>>> pieces['piece3'].mover('right')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
pieces['piece3'].mover('right')
File "C:/Users/Hannah/Documents/thing.py", line 25, in mover
for n in alist:
NameError: global name 'alist' is not defined
>>> pieces['piece3'].xpos
8
>>> pieces['piece3'].adjustX(1)
>>> pieces['piece3'].xpos
9
Keep in mind dictionaries are unordered so the order they print in is arbitrary.
The traceback on mover is expected since I don't have alist in my version of the code. You will need to modify mover() to work with the dictionary. Some helpful ways to work with dicts:
>>> for n in pieces.values(): # iterates over the values in a dict
n.color
'white'
'white'
'white'
'white'
'white'
'white'
'white'
'white'
'white'
'white'
'white'
'white'
>>> for n in pieces.keys(): # iterates over the keys
print(n)
piece8
piece9
piece6
piece7
piece4
piece5
piece2
piece3
piece1
piece10
piece11
piece12