This function checks if two objects truly collide. This is useful when you have two objects whose rects collide even when they are not actually touching each other, and you want to know when the actual objects collide. This code will check 1000 collisions between 2 rects that are 25 * 10 in size in about 0.015 to 0.07 seconds. PyGame's rect.colliderect will do the same collisions in 0.001 seconds.
All objects must have a 'rect' attribute and a 'hitmask' attribute. The 'blank' attribute is voluntary, as 0 will most likely be its value, and using the pixel as a boolean statement would then work to the same effect. The hitmask can be any type of surfarray, but you will most likely use array_alpha(image) or array_colorkey(image).
The following is a revision of Joshua Gram's version, by Alfonso Crawford.
def PixelPerfectCollision(obj1, obj2):
"""
If the function finds a collision, it will return True;
if not, it will return False. If one of the objects is
not the intended type, the function instead returns None.
"""
try:
#create attributes
rect1, mask1, blank1 = obj1.rect, obj1.hitmask, obj1.blank
rect2, mask2, blank2 = obj2.rect, obj2.hitmask, obj2.blank
#initial examination
if rect1.colliderect(rect2) is False:
return False
except AttributeError:
return None
#get the overlapping area
clip = rect1.clip(rect2)
#find where clip's top-left point is in both rectangles
x1 = clip.left - rect1.left
y1 = clip.top - rect1.top
x2 = clip.left - rect2.left
y2 = clip.top - rect2.top
#cycle through clip's area of the hitmasks
for x in range(clip.width):
for y in range(clip.height):
#returns True if neither pixel is blank
if mask1[x1+x][y1+y] is not blank1 and \
mask2[x2+x][y2+y] is not blank2:
return True
#if there was neither collision nor error
return False
Note: You can see an example using an algorithm almost identical to Joshua's
at John Eriksson's project, PixelPerfect.
Here is a cleaned up and bug-fixed version of the original by RB[0],
that now uses the for loop(as suggested here by Joshua Grams),
instead of while loops, which are slower.
There are also a few helper functions that are used to create hitmasks without using pygames surfarray module,
as it is currently broken(at least for me),
these dont even require Numeric.
This pixelperfect implementation is anywhere from 1.2 to 2.5 times faster than the one shown above.
def check_collision(obj1,obj2):
"""checks if two objects have collided, using hitmasks"""
try:rect1, rect2, hm1, hm2 = obj1.rect, obj2.rect, obj1.hitmask, obj2.hitmask
except AttributeError:return False
rect=rect1.clip(rect2)
if rect.width==0 or rect.height==0:
return False
x1,y1,x2,y2 = rect.x-rect1.x,rect.y-rect1.y,rect.x-rect2.x,rect.y-rect2.y
for x in xrange(rect.width):
for y in xrange(rect.height):
if hm1[x1+x][y1+y] and hm2[x2+x][y2+y]:return True
else:continue
return False
def get_colorkey_hitmask(image, rect, key=None):
"""returns a hitmask using an image's colorkey.
image->pygame Surface,
rect->pygame Rect that fits image,
key->an over-ride color, if not None will be used instead of the image's colorkey"""
if key==None:colorkey=image.get_colorkey()
else:colorkey=key
mask=[]
for x in range(rect.width):
mask.append([])
for y in range(rect.height):
mask[x].append(not image.get_at((x,y)) == colorkey)
return mask
def get_alpha_hitmask(image, rect, alpha=0):
"""returns a hitmask using an image's alpha.
image->pygame Surface,
rect->pygame Rect that fits image,
alpha->the alpha amount that is invisible in collisions"""
mask=[]
for x in range(rect.width):
mask.append([])
for y in range(rect.height):
mask[x].append(not image.get_at((x,y))[3]==alpha)
return mask
def get_colorkey_and_alpha_hitmask(image, rect, key=None, alpha=0):
"""returns a hitmask using an image's colorkey and alpha."""
mask=[]
for x in range(rect.width):
mask.append([])
for y in range(rect.height):
mask[x].append(not (image.get_at((x,y))[3]==alpha or\
image.get_at((x,y))==colorkey))
return mask
def get_full_hitmask(image, rect):
"""returns a completely full hitmask that fits the image,
without referencing the images colorkey or alpha."""
mask=[]
for x in range(rect.width):
mask.append([])
for y in range(rect.height):
mask[x].append(True)
return mask
For an example of use:
import pygame, pixelperfect, time
from pygame.locals import *
from pixelperfect import *
def load_image(name, colorkey=None, alpha=False):
"""loads an image into memory"""
try:
image = pygame.image.load(name)
except pygame.error, message:
print 'Cannot load image:', name
raise SystemExit, message
if alpha:image = image.convert_alpha()
else:image=image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
class my_object(object):
def __init__(self, image,colorkey=None,alpha=None):
self.image, self.rect=load_image(image,colorkey=colorkey, alpha=alpha)
if colorkey and alpha:
self.hitmask=get_colorkey_and_alpha_hitmask(self.image, self.rect,
colorkey, alpha)
elif colorkey:
self.hitmask=get_colorkey_hitmask(self.image, self.rect,
colorkey)
elif alpha:
self.hitmask=get_alpha_hitmask(self.image, self.rect,
alpha)
else:
self.hitmask=get_full_hitmask(self.image, self.rect)
pygame.init()
screen = pygame.display.set_mode([200,200])
screen.fill([255,255,255])
a=my_object('carrots.png',-1,None)
a.rect.center=(25,25)
b=my_object('carrots.png',None,True)
b.rect.center=(50,50)
screen.blit(a.image, a.rect)
screen.blit(b.image, b.rect)
pygame.display.flip()
def main():
av=0
for i in xrange(999):
st_time=time.clock()
check_collision(a, b)
av+=time.clock()-st_time
print "time:", av, check_collision(a, b)
main()
If you have any suggestions, please email me at "roebros (at) gmail.com"
JAPANESE PATTERN-DESIGNER. JAPANESE PATTERN-DESIGNER. All that warm afternoon we paid the tiresome penalty of having pushed our animals too smartly at the outset. We grew sedate; sedate were the brows of the few strangers we met. We talked in pairs. When I spoke with Miss Harper the four listened. She asked about the evils of camp life; for she was one of that fine sort to whom righteousness seems every man's and woman's daily business, one of the most practical items in the world's affairs. And I said camp life was fearfully corrupting; that the merest boys cursed and swore and stole, or else were scorned as weaklings. Then I grew meekly silent and we talked in pairs again, and because I yearned to talk most with Camille I talked most with Estelle. Three times when I turned abruptly from her to Camille and called, "Hark!" the fagged-out horses halted, and as we struck our listening pose the bugle's faint sigh ever farther in our rear was but feebly proportioned to the amount of our gazing into each other's eyes. "I'm glad you didn't," Bruce smiled. "What a sensation those good people will have presently! And most of them have been on intimate terms with our Countess. My darling, I shall never be easy in my mind till you are out of that house." Those manifestations of sympathy which are often so much more precious than material assistance were also repugnant to Stoic principles. On this subject, Epict¨ºtus expresses himself with singular harshness. ¡®Do not,¡¯ he says, ¡®let yourself be put out by the sufferings of your friends. If they are unhappy, it is their own fault. God made them for happiness, not for misery. They are grieved at parting from you, are they? Why, then, did they set their affections on things outside themselves? If they suffer for their folly it serves them right.¡¯93 You are awfully good, Daddy, to bother yourself with me, when you're ¡°Some strong, pungent liquid had been poured on the green necklace,¡± the letter from the millionaire stated. ¡°No alarm was given. My wife did not want to broadcast either the fact that she had the real gems or the trouble in the hotel. But people had heard the ¡®fire!¡¯ cry and doubtless some suspected the possible truth, knowing why she was getting ready. ¡°But the switches that control the motor for the drum are right out on the wall in plain sight,¡± he told himself, moving over toward them, since the rolling door was left wide open when the amphibian was taken out. ¡°Yes, here they all are¡ªthis one up for lifting the door, and down to drop it. And that switch was in the neutral¡ª¡®off¡¯¡ªposition when we were first here¡ªand it¡¯s in neutral now.¡± The strong sense, lively fancy, and smart style of his satires, distinguished also Pope's prose, as in his "Treatise of the Bathos; or, the Art of Sinking in Poetry;" his "Memoirs of P. P., Clerk of this Parish"¡ªin ridicule of Burnet's "Own Times"¡ªhis Letters, etc. In some of the last he describes the country and country seats, and the life there of his friends; which shows that, in an age more percipient of the charm of such things, he would have probably approached nearer to the heart of Nature, and given us something more genial and delightful than anything that he has left us. The taste for Italian music was now every day increasing; singers of that nation appeared with great applause at most concerts. In 1703 Italian music was introduced into the theatres as intermezzi, or interludes, consisting of singing and dancing; then whole operas appeared, the music Italian, the words English; and, in 1707, Urbani, a male soprano, and two Italian women, sang their parts all in Italian, the other performers using English. Finally, in 1710, a complete Italian opera was performed at the Queen's Theatre, Haymarket, and from that time the Italian opera was regularly established in London. This led to the arrival of the greatest composer whom the world had yet seen. George Frederick Handel was born at Halle, in Germany, in 1685. He had displayed wonderful genius for music as a mere child, and having, at the age of seven years, astonished the Duke of Saxe Weissenfels¡ªat whose court his brother-in-law was a valet¡ªwho found him playing the organ in the chapel, he was, by the Duke's recommendation, regularly educated for the profession of music. At the age of ten, Handel composed the church service for voices and instruments; and after acquiring a great reputation in Hamburg¡ªwhere, in 1705, he brought out his "Almira"¡ªhe proceeded to Florence, where he produced the opera of "Rodrigo," and thence to Venice, Rome, and Naples. After remaining in Italy four years, he was induced to come to England in 1710, at the pressing entreaties of many of the English nobility, to superintend the opera. But, though he was enthusiastically received, the party spirit which raged at that period soon made it impossible to conduct the opera with any degree of self-respect and independence. He therefore abandoned the attempt, having sunk nearly all his fortune in it, and commenced the composition of his noble oratorios. Racine's "Esther," abridged and altered by Humphreys, was set by him, in 1720, for the chapel of the Duke of Chandos at Cannons. It was, however, only by slow degrees that the wonderful genius of Handel was appreciated, yet it won its way against all prejudices and difficulties. In 1731 his "Esther" was performed by the children of the chapel-royal at the house of Bernard Gates, their master, and the following year, at the king's command, at the royal theatre in the Haymarket. It was fortunate for Handel that the monarch was German too, or he might have quitted the country in disgust before his fame had triumphed over faction and ignorance. So far did these operate, that in 1742, when he produced his glorious "Messiah," it was so coldly received that it was treated as a failure. Handel, in deep discouragement, however, gave it another trial in Dublin, where the warm imaginations of the Irish caught all its sublimity, and gave it an enthusiastic reception. On its next presentation in London his audience reversed the former judgment, and the delighted composer then presented the manuscript to the Foundling Hospital, where it was performed annually for the benefit of that excellent institution, and added to its funds ten thousand three hundred pounds. It became the custom, from 1737, to perform oratorios[156] on the Wednesdays and Fridays in Lent. Handel, whose genius has never been surpassed for vigour, spirit, invention, and sublimity, became blind in his latter years. He continued to perform in public, and to compose, till within a week of his death, which took place on April 13, 1759. The Deacon took his position behind a big black walnut, while he reconnoitered the situation, and got his bearings on the clump of willows. He felt surer than ever of his man, for he actually saw a puff of smoke come from it, and saw that right behind the puff stood a willow that had grown to the proportions of a small tree, and had its bark rubbed off by the chafing of driftwood against it. "Certainly. I see it very plainly," said the Surgeon, after looking them over. "Very absurd to start such a report, but we are quite nervous on the subject of smallpox getting down to the army. "Yes, just one." Reuben pulled up his chair to the table. His father sat at one end, and at the other sat Mrs. Backfield; Harry was opposite Reuben. Reuben counted them¡ªten. Then he pushed them aside, and began rummaging in the cart among cabbages and bags of apples. In a second or two he had dragged out five more rabbits. Robert stood with hanging head, flushed cheeks, and quivering hands, till his father fulfilled his expectations by knocking him down. HoMEBT ÏÂÔØ ÀïÃÀÓÈÀûæ« ENTER NUMBET 0016www.exc-led.com.cn