Here's some functions that I wrote to help with collision detection in a retro arcade remake of Asteroids using Python and Pygame. Some simple assertion tests are included at the bottom.
Features:
The entry point for an intersect test is the getIntersectPoint function.
# geometry.py
#
# Geometry functions to find intersecting lines.
# Thes calc's use this formula for a straight line:-
# y = mx + b where m is the gradient and b is the y value when x=0
#
# See here for background http://www.mathopenref.com/coordintersection.html
#
# Throughout the code the variable p is a point tuple representing (x,y)
#
# Copyright (C) 2008 Nick Redshaw
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from __future__ import division
from pygame import Rect
# Calc the gradient 'm' of a line between p1 and p2
def calculateGradient(p1, p2):
# Ensure that the line is not vertical
if (p1[0] != p2[0]):
m = (p1[1] - p2[1]) / (p1[0] - p2[0])
return m
else:
return None
# Calc the point 'b' where line crosses the Y axis
def calculateYAxisIntersect(p, m):
return p[1] - (m * p[0])
# Calc the point where two infinitely long lines (p1 to p2 and p3 to p4) intersect.
# Handle parallel lines and vertical lines (the later has infinate 'm').
# Returns a point tuple of points like this ((x,y),...) or None
# In non parallel cases the tuple will contain just one point.
# For parallel lines that lay on top of one another the tuple will contain
# all four points of the two lines
def getIntersectPoint(p1, p2, p3, p4):
m1 = calculateGradient(p1, p2)
m2 = calculateGradient(p3, p4)
# See if the the lines are parallel
if (m1 != m2):
# Not parallel
# See if either line is vertical
if (m1 is not None and m2 is not None):
# Neither line vertical
b1 = calculateYAxisIntersect(p1, m1)
b2 = calculateYAxisIntersect(p3, m2)
x = (b2 - b1) / (m1 - m2)
y = (m1 * x) + b1
else:
# Line 1 is vertical so use line 2's values
if (m1 is None):
b2 = calculateYAxisIntersect(p3, m2)
x = p1[0]
y = (m2 * x) + b2
# Line 2 is vertical so use line 1's values
elif (m2 is None):
b1 = calculateYAxisIntersect(p1, m1)
x = p3[0]
y = (m1 * x) + b1
else:
assert false
return ((x,y),)
else:
# Parallel lines with same 'b' value must be the same line so they intersect
# everywhere in this case we return the start and end points of both lines
# the calculateIntersectPoint method will sort out which of these points
# lays on both line segments
b1, b2 = None, None # vertical lines have no b value
if m1 is not None:
b1 = calculateYAxisIntersect(p1, m1)
if m2 is not None:
b2 = calculateYAxisIntersect(p3, m2)
# If these parallel lines lay on one another
if b1 == b2:
return p1,p2,p3,p4
else:
return None
# For line segments (ie not infinitely long lines) the intersect point
# may not lay on both lines.
#
# If the point where two lines intersect is inside both line's bounding
# rectangles then the lines intersect. Returns intersect point if the line
# intesect o None if not
def calculateIntersectPoint(p1, p2, p3, p4):
p = getIntersectPoint(p1, p2, p3, p4)
if p is not None:
width = p2[0] - p1[0]
height = p2[1] - p1[1]
r1 = Rect(p1, (width , height))
r1.normalize()
width = p4[0] - p3[0]
height = p4[1] - p3[1]
r2 = Rect(p3, (width, height))
r2.normalize()
# Ensure both rects have a width and height of at least 'tolerance' else the
# collidepoint check of the Rect class will fail as it doesn't include the bottom
# and right hand side 'pixels' of the rectangle
tolerance = 1
if r1.width < tolerance:
r1.width = tolerance
if r1.height < tolerance:
r1.height = tolerance
if r2.width < tolerance:
r2.width = tolerance
if r2.height < tolerance:
r2.height = tolerance
for point in p:
try:
res1 = r1.collidepoint(point)
res2 = r2.collidepoint(point)
if res1 and res2:
point = [int(pp) for pp in point]
return point
except:
# sometimes the value in a point are too large for PyGame's Rect class
str = "point was invalid ", point
print str
# This is the case where the infinately long lines crossed but
# the line segments didn't
return None
else:
return None
# Test script below...
if __name__ == "__main__":
# line 1 and 2 cross, 1 and 3 don't but would if extended, 2 and 3 are parallel
# line 5 is horizontal, line 4 is vertical
p1 = (1,5)
p2 = (4,7)
p3 = (4,5)
p4 = (3,7)
p5 = (4,1)
p6 = (3,3)
p7 = (3,1)
p8 = (3,10)
p9 = (0,6)
p10 = (5,6)
p11 = (472.0, 116.0)
p12 = (542.0, 116.0)
assert None != calculateIntersectPoint(p1, p2, p3, p4), "line 1 line 2 should intersect"
assert None != calculateIntersectPoint(p3, p4, p1, p2), "line 2 line 1 should intersect"
assert None == calculateIntersectPoint(p1, p2, p5, p6), "line 1 line 3 shouldn't intersect"
assert None == calculateIntersectPoint(p3, p4, p5, p6), "line 2 line 3 shouldn't intersect"
assert None != calculateIntersectPoint(p1, p2, p7, p8), "line 1 line 4 should intersect"
assert None != calculateIntersectPoint(p7, p8, p1, p2), "line 4 line 1 should intersect"
assert None != calculateIntersectPoint(p1, p2, p9, p10), "line 1 line 5 should intersect"
assert None != calculateIntersectPoint(p9, p10, p1, p2), "line 5 line 1 should intersect"
assert None != calculateIntersectPoint(p7, p8, p9, p10), "line 4 line 5 should intersect"
assert None != calculateIntersectPoint(p9, p10, p7, p8), "line 5 line 4 should intersect"
print "\nSUCCESS! All asserts passed for doLinesIntersect"
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.kbchain.com.cn