How to scale multiple images with a for loop? - python

I'm trying to use a for-loop to iterate through a list of self classes. I want to give each one the same scale.
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Migue/m_normal.png")
self.quieto = pygame.image.load("Migue/m_normal.png")
self.andando = pygame.image.load("Migue/m_andando_normal.png")
self.image = pygame.transform.scale(self.image, sizenorm)
states = [self.quieto, self.andando]
for i in states:
i = pygame.transform.scale(i, sizenorm)
This wont work, but I can achieve the result using this:
self.quieto = pygame.transform.scale(self.quieto, sizenorm)
self.andando = pygame.transform.scale(self.andando, sizenorm)
The problem is that I have to make a lot of more states, and using that for loop would be shorter. However, it doesn't work like the lower example does. I don't know what's wrong with the loop.

You can create a list of the scaled objects and assign the elements of the list to the original attributes:
states = [self.quieto, self.andando]
states = [pygame.transform.scale(i, sizenorm) for i in states]
(self.quieto, self.andando) = states
This can even be written in a single line
(self.quieto, self.andando) = [pygame.transform.scale(i, sizenorm) for i in [self.quieto, self.andando]]
Alternatively, you can simply put the images in a list:
filenames = ["Migue/m_normal.png", "Migue/m_andando_normal.png"]
self.states = [pygame.transform.scale(pygame.image.load(n), sizenorm) for n in filenames]

Related

How to read element in list item in Python?

I have the following output from a function and I need to read shape, labels, and domain from this stream.
[Annotation(shape=Rectangle(x=0.0, y=0.0, width=1.0, height=1.0), labels=[ScoredLabel(62282a1dc79ed6743e731b36, name=GOOD, probability=0.5143796801567078, domain=CLASSIFICATION, color=Color(red=233, green=97, blue=21, alpha=255), hotkey=ctrl+3)], id=622cc4d962f051a8f41ddf35)]
I need them as follows
shp = Annotation.shape
lbl = Annotation.labels
dmn = domain
It seems simple but I could not figure it out yet.
Given output as a list of Annotation objects:
output = [Annotation(...)]
you ought to be able to simply do:
shp = output[0].shape
lbl = output[0].labels
dmn = labels[0].domain

Pulling PowerPoint Text Attributes Through Python

I am trying to pull in the attributes associated with my text in PowerPoint and am getting weird outputs... The output from shape.fill is not as expected. I am also curious to find the other attributes like shape.font and the position of the shape - is this possible?
Issue:
f = shape.fill
Output: <pptx.dml.fill.FillFormat object at 0x00000215C4D6DD90>
Code:
mylist = []
mylist2 = []
mylist3 = []
mylist4 = []
mylist5 = []
mylist6 = []
mylist7 = []
for eachfile in glob.glob(direct):
s = 1
file = os.path.basename(eachfile)
try:
prs = Presentation(eachfile)
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
x = nltk.word_tokenize(shape.text)
t = shape.text
f = shape.fill
print(f)
mylist4.append(file)
mylist5.append(t)
mylist7.append(f)
mylist6.append('Slide: ' + str(s))
# x = shape.text.split() #looks for words with punctuation included
for word in x:
word = word.lower()
if word in terms:
mylist.append("Slide " + str(s))
mylist2.append(file)
mylist3.append(word)
s = s + 1
except:
pass
#mylist = list(dict.fromkeys(mylist))
d = {'FileName':mylist2,'Slide':mylist, 'Match':mylist3}
d2 = {'FileName':mylist4, 'Slide':mylist6, 'Text':mylist5, 'Color':mylist7}
search = phrases + terms
d3 = {'Text':search}
df = pd.DataFrame(d)
df = df.drop_duplicates()
<pptx.dml.fill.FillFormat object at 0x00000215C4D6DD90> is a python object. You need to look up the documentation for these type of objects and use its attribute functions in order to get information out of it.
The only documentation I could find for this type of object is this one, although that is not a "normal" one, but just the source code. Functions You can use are written inside of the FillFormat class, starting with back_color(self, ...)
The API documentation describes what you should expect on any given attribute. For example, here: https://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects
you can find out how to interrogate the FillFormat object that Shape.fill returns.
In many cases, things are substantially more complex than the common cases and the API will reflect that. For example, fills come in several varieties: an RGB color (most common), a pattern (repeated bitmap mask), an image (either tiled or fit in a variety of ways), and a "null" fill. Accommodating all these options requires you to learn more about PowerPoint than you probably originally wanted to know :)
The overall API documentation is here: https://python-pptx.readthedocs.io/en/latest/#api-documentation

How can I speed up the following code in Python?

I was trying to think of a faster way to implement this code. Tried vectorizing the init of the glider object, but could not figure out how to pass in the multiple values or perform an action such as the move() function on each of the objects.
def myFunc(fairy_dust):
for particle in fairy_dust:
temp = glider(particle[0], particle[1], particle[2], particle[3])
temp = temp.move()
particle[0] = temp.x
particle[1] = temp.y
particle[2] = temp.heading

Creating an array of objects in Python for pygame

I create the objects
class Disk:
def __init__(self,number,colour,position,size):
self.size = size
self.colour = colour
self.number = number
self.position = position
def Render(self,screen):
pygame.draw.rect(screen,self.colour,(self.position,self.size))
I am trying to create an array of this object using user input (for right now I am just making my own number)
Colours are a seperate array that I've created (it works)
def drawDisk(screen,colours):
num = 5
for i in range (num):
disk[i] = Disk(i,colours[i*num],(0+(i*15),500-(i*50)),(400 -(i*30),50))
disk[i].Render(screen)
My program works except for when I try creating an array of disks and using those disks instead of hard coding each individual disk.
You haven't defined disk. You are trying to simultaneously create the list and the items in it and iterate over it, but haven't actually told Python what disk is supposed to be. Try:
def drawDisk(screen, colours):
disk = [Disk(i, colours[i], (0+(i*15), 500-(i*50)), (400 -(i*30), 50))
for i in range(len(colours))] # create and fill disk
# list comprehension, equivalent to:
# disk = []
# for i in range(len(colours)):
# disk.append(Disk(i, colours[i], ...))
for d in disk:
d.Render(screen) # use items in disk
return disk # for use elsewhere

Python for x in list basic question

I am trying to create a function which will load a whole lot of images and map them to appropriate names in PyGame. I'm not all that great with python and this really has me stuck. My current code is this:
tile1 = pygame.image.load("/one.bmp")
tile2 = pygame.image.load("/two.bmp")
tile3 = pygame.image.load("/three.bmp")
and it keeps going on for about 20 tiles. The thing is I just found out that I need a lot more and was wondering how I could do this using a for x in y loop. My basic idea was:
tile = ['/one.bmp', '/two.bmp', '/three.bmp']
tilelist = [1,2,3]
for tile in tile:
tilelist[x] = pygame.image.load(tile)
or something like that but I'm not quite there. I was also wondering if it could be done using dictionaries.
Any help would be appreciated, thanks :)
List comprehensions to the rescue.
tiles = ['/one.bmp', '/two.bmp', '/three.bmp']
tilelist = [pygame.img.load(tile) for tile in tiles]
As #isakkarlsson commented,
...or easier(?) tilelist = map(pygame.img.load, tiles)
To load the data
tile = ['/one.bmp', '/two.bmp', '/three.bmp']
imageMap = {}
for t in tile:
imageMap[t] = pygame.img.load(t)
Then you have all the data in a dictionary and can loop through the file names using imageMap.keys() or the index directly into the dictionary to get a particular image.

Categories