This is a simple quad-tree class intended for static geometry such as the game world. It can be used to limit drawing, by returning the set of objects that intersect the screen (as in the example), and it can be used to speed up collision detection by returning the set of objects that intersect with the player's bounding box.
class QuadTree(object):
"""An implementation of a quad-tree.
This QuadTree started life as a version of [1] but found a life of its own
when I realised it wasn't doing what I needed. It is intended for static
geometry, ie, items such as the landscape that don't move.
This implementation inserts items at the current level if they overlap all
4 sub-quadrants, otherwise it inserts them recursively into the one or two
sub-quadrants that they overlap.
Items being stored in the tree must possess the following attributes:
left - the x coordinate of the left edge of the item's bounding box.
top - the y coordinate of the top edge of the item's bounding box.
right - the x coordinate of the right edge of the item's bounding box.
bottom - the y coordinate of the bottom edge of the item's bounding box.
where left < right and top < bottom
...and they must be hashable.
Acknowledgements:
[1] http://mu.arete.cc/pcr/syntax/quadtree/1/quadtree.py
"""
def __init__(self, items, depth=8, bounding_rect=None):
"""Creates a quad-tree.
@param items:
A sequence of items to store in the quad-tree. Note that these
items must possess left, top, right and bottom attributes.
@param depth:
The maximum recursion depth.
@param bounding_rect:
The bounding rectangle of all of the items in the quad-tree. For
internal use only.
"""
# The sub-quadrants are empty to start with.
self.nw = self.ne = self.se = self.sw = None
# If we've reached the maximum depth then insert all items into this
# quadrant.
depth -= 1
if depth == 0:
self.items = items
return
# Find this quadrant's centre.
if bounding_rect:
l, t, r, b = bounding_rect
else:
# If there isn't a bounding rect, then calculate it from the items.
l = min(item.left for item in items)
t = min(item.top for item in items)
r = max(item.right for item in items)
b = max(item.bottom for item in items)
cx = self.cx = (l + r) * 0.5
cy = self.cy = (t + b) * 0.5
self.items = []
nw_items = []
ne_items = []
se_items = []
sw_items = []
for item in items:
# Which of the sub-quadrants does the item overlap?
in_nw = item.left <= cx and item.top <= cy
in_sw = item.left <= cx and item.bottom >= cy
in_ne = item.right >= cx and item.top <= cy
in_se = item.right >= cx and item.bottom >= cy
# If it overlaps all 4 quadrants then insert it at the current
# depth, otherwise append it to a list to be inserted under every
# quadrant that it overlaps.
if in_nw and in_ne and in_se and in_sw:
self.items.append(item)
else:
if in_nw: nw_items.append(item)
if in_ne: ne_items.append(item)
if in_se: se_items.append(item)
if in_sw: sw_items.append(item)
# Create the sub-quadrants, recursively.
if nw_items:
self.nw = QuadTree(nw_items, depth, (l, t, cx, cy))
if ne_items:
self.ne = QuadTree(ne_items, depth, (cx, t, r, cy))
if se_items:
self.se = QuadTree(se_items, depth, (cx, cy, r, b))
if sw_items:
self.sw = QuadTree(sw_items, depth, (l, cy, cx, b))
def hit(self, rect):
"""Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes.
"""
def overlaps(item):
return rect.right >= item.left and rect.left <= item.right and \
rect.bottom >= item.top and rect.top <= item.bottom
# Find the hits at the current level.
hits = set(item for item in self.items if overlaps(item))
# Recursively check the lower quadrants.
if self.nw and rect.left <= self.cx and rect.top <= self.cy:
hits |= self.nw.hit(rect)
if self.sw and rect.left <= self.cx and rect.bottom >= self.cy:
hits |= self.sw.hit(rect)
if self.ne and rect.right >= self.cx and rect.top <= self.cy:
hits |= self.ne.hit(rect)
if self.se and rect.right >= self.cx and rect.bottom >= self.cy:
hits |= self.se.hit(rect)
return hits
if __name__ == '__main__':
import pygame
import random
# The class that we're storing in the quad-tree. It possesses the necessary
# attributes of left, top, right and bottom, and it is hashable.
class Item(object):
def __init__(self, left, top, right, bottom, colour=(255, 255, 255)):
self.left = left
self.top = top
self.right = right
self.bottom = bottom
self.colour = colour
def draw(self):
x = self.left
y = self.top
w = self.right - x
h = self.bottom - y
pygame.draw.rect(screen, self.colour, pygame.Rect(x, y, w, h), 2)
# Create 10,000 random items, some of which should overlap with the screen.
colours = [
(0, 0, 255),
(0, 255, 0),
(0, 255, 255),
(255, 0, 0),
(255, 0, 255),
(255, 255, 0),
(255, 255, 255)
]
items = []
for i in range(10000):
x = random.uniform(-5000, 5000)
y = random.uniform(-5000, 5000)
w = 5 + random.expovariate(1.0/50)
h = 5 + random.expovariate(1.0/50)
colour = random.choice(colours)
items.append(Item(x, y, x+w, y+h, colour))
# Put them into a quad-tree.
tree = QuadTree(items)
WIDTH = 640
HEIGHT = 480
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
quit = False
while not quit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit = True
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
quit = True
# Use the quad-tree to restrict which items we're going to draw.
area = pygame.Rect(0, 0, WIDTH, HEIGHT)
visible_items = tree.hit(area)
# Draw the visible items only.
screen.fill((0, 0, 0))
for item in visible_items:
item.draw()
pygame.display.flip()
pygame.quit()
print "Total items:", len(items)
print "Visible items:", len(visible_items)
Hi, I found this very useful (thank you), but ended up modifying it to assume that everything you pass to it is a pygame.Rect or is an object with a .rect attribute. This turned out to be the case for everything I wanted to use it for and is faster and more convenient in that case.
Most of the speedup comes from using rect.collidelistall() to do the dirty work in hit(). I also experimented with using rect.collidedictall() but the dict.update() to merge them turned out to be slower.
from pygame import Rect
class QuadTree(object):
"""An implementation of a quad-tree.
This QuadTree started life as a version of [1] but found a life of its own
when I realised it wasn't doing what I needed. It is intended for static
geometry, ie, items such as the landscape that don't move.
This implementation inserts items at the current level if they overlap all
4 sub-quadrants, otherwise it inserts them recursively into the one or two
sub-quadrants that they overlap.
Items being stored in the tree must be a pygame.Rect or have have a
.rect (pygame.Rect) attribute that is a pygame.Rect
...and they must be hashable.
Acknowledgements:
[1] http://mu.arete.cc/pcr/syntax/quadtree/1/quadtree.py
"""
def __init__(self, items, depth=8, bounding_rect=None):
"""Creates a quad-tree.
@param items:
A sequence of items to store in the quad-tree. Note that these
items must be a pygame.Rect or have a .rect attribute.
@param depth:
The maximum recursion depth.
@param bounding_rect:
The bounding rectangle of all of the items in the quad-tree. For
internal use only.
"""
# The sub-quadrants are empty to start with.
self.nw = self.ne = self.se = self.sw = None
# If we've reached the maximum depth then insert all items into this
# quadrant.
depth -= 1
if depth == 0 or not items:
self.items = items
return
# Find this quadrant's centre.
if bounding_rect:
bounding_rect = Rect( bounding_rect )
else:
# If there isn't a bounding rect, then calculate it from the items.
bounding_rect = Rect( items[0] )
for item in items[1:]:
bounding_rect.union_ip( item )
cx = self.cx = bounding_rect.centerx
cy = self.cy = bounding_rect.centery
self.items = []
nw_items = []
ne_items = []
se_items = []
sw_items = []
for item in items:
# Which of the sub-quadrants does the item overlap?
in_nw = item.rect.left <= cx and item.rect.top <= cy
in_sw = item.rect.left <= cx and item.rect.bottom >= cy
in_ne = item.rect.right >= cx and item.rect.top <= cy
in_se = item.rect.right >= cx and item.rect.bottom >= cy
# If it overlaps all 4 quadrants then insert it at the current
# depth, otherwise append it to a list to be inserted under every
# quadrant that it overlaps.
if in_nw and in_ne and in_se and in_sw:
self.items.append(item)
else:
if in_nw: nw_items.append(item)
if in_ne: ne_items.append(item)
if in_se: se_items.append(item)
if in_sw: sw_items.append(item)
# Create the sub-quadrants, recursively.
if nw_items:
self.nw = QuadTree(nw_items, depth, (bounding_rect.left, bounding_rect.top, cx, cy))
if ne_items:
self.ne = QuadTree(ne_items, depth, (cx, bounding_rect.top, bounding_rect.right, cy))
if se_items:
self.se = QuadTree(se_items, depth, (cx, cy, bounding_rect.right, bounding_rect.bottom))
if sw_items:
self.sw = QuadTree(sw_items, depth, (bounding_rect.left, cy, cx, bounding_rect.bottom))
def hit(self, rect):
"""Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes.
"""
# Find the hits at the current level.
hits = set( [ self.items[n] for n in rect.collidelistall( self.items ) ] )
# Recursively check the lower quadrants.
if self.nw and rect.left <= self.cx and rect.top <= self.cy:
hits |= self.nw.hit(rect)
if self.sw and rect.left <= self.cx and rect.bottom >= self.cy:
hits |= self.sw.hit(rect)
if self.ne and rect.right >= self.cx and rect.top <= self.cy:
hits |= self.ne.hit(rect)
if self.se and rect.right >= self.cx and rect.bottom >= self.cy:
hits |= self.se.hit(rect)
return hits
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.fushipifa.net.cn