This module requires Pygame 1.8 and either Numeric or NumPy.
# shadows.py module
"""Tools for adding a shadow effect to pygame images
Exports make_shadow, make_shadow_opaque, place_shadow, add_shadow.
pygame.display.set_mode() must be called before this module's functions
can be used.
"""
import pygame
_arraytype = pygame.surfarray.get_arraytype()
if _arraytype == 'numeric':
from Numeric import UInt8 as uint8, minimum, array, Float32 as float32, Int32 as int32
elif _arraytype == 'numpy':
from numpy import uint8, minimum, array, float32, int32
else:
raise TypeError("Unrecognized surfarray array type %s" % _arraytype)
def make_shadow(image, ambience=None):
"""Return a shadow representation of image for a given ambient lighting
image - foreground image.
ambience (optional) - 0.0 to 1.0: Ambient light ratio. 0.0 gives a
totally black shadow while 1.0 gives no shadow.
Defaults to 0.0 .
"""
if ambience is None:
ambience = 0.0
elif not (0.0 <= ambience <= 1.0):
raise ValueError("ambience must be between 0.0 and 1.0 inclusive")
if image.get_masks()[3] != 0:
image_alpha = pygame.surfarray.pixels_alpha(image)
if ambience > 0.0:
shadow_alpha = (image_alpha *
(1.0 - ambience)).astype(uint8)
else:
shadow_alpha = image_alpha
elif image.get_colorkey() is not None:
image_alpha = pygame.surfarray.array_colorkey(image)
image.unlock(); image.unlock() # pygame 1.7 bug (fixed in 1.8).
surface_alpha = image.get_alpha()
if surface_alpha is not None:
# Do what array_colorkey should have done: use surface alpha!
minimum(image_alpha, surface_alpha, image_alpha)
if ambience > 0.0:
shadow_alpha = (image_alpha *
(1.0 - ambience)).astype(uint8)
else:
shadow_alpha = image_alpha
else:
image_alpha = image.get_alpha()
if image_alpha is None:
image_alpha = 255
shadow_alpha = int(image_alpha * (1.0 - ambience))
shadow = image.convert_alpha()
shading = pygame.Surface(shadow.get_size(), pygame.SRCALPHA, 32)
pygame.surfarray.pixels_alpha(shading)[...] = image_alpha
shadow.blit(shading, (0, 0))
pygame.surfarray.pixels_alpha(shadow)[...] = shadow_alpha
return shadow
def make_shadow_opaque(size, ambience=None, pixel_size=None):
"""Return a retangular shadow for the given ambient lighting
size - (width, height): shadow dimensions.
ambience (optional) - 0.0 to 1.0: Ambient light ratio. 0.0 gives a
totally black shadow while 1.0 gives no shadow.
Defaults to 0.0 .
pixel_size (optional) - bits per pixel - defaults to screen value.
This version is provided for performance.
"""
if ambience is None:
ambience = 0.0
if pixel_size is None:
rest = ()
else:
rest = (pixel_size,)
shadow = pygame.Surface(size, 0, rest)
shadow.set_alpha(255 * (1.0 - ambience))
return shadow
def place_shadow(image, shadow, shadow_offset):
"""Return a surface that combines the image and shadow
image - foreground image.
shadow - image shadow.
shadow_offset - (dx, dy) amount, in pixel, to shift
shadow center relative to image center.
"""
image_rect = image.get_rect()
shadow_rect = shadow.get_rect()
shadow_rect.center = image_rect.center
shadow_rect.move_ip(shadow_offset)
rect = image_rect.union(shadow_rect)
result = pygame.Surface(rect.size, pygame.SRCALPHA, 32)
result.blit(shadow, (shadow_rect.left - rect.left,
shadow_rect.top - rect.top))
result.blit(image, (image_rect.left - rect.left,
image_rect.top - rect.top))
return result
def add_shadow(image, shadow_offset, shadow_scale=None, ambience=None):
"""Return a copy of image with a shadow added
image - a surface with or without alpha or colorkey.
shadow_offset - (dx, dy) amount, in pixel, to shift
shadow center relative to image center.
shadow_scale (optional) - amount by which to scale the shadow.
defaults to 1.0 (no scaling).
ambience (optional) - 0.0 to 1.0: Ambient light ratio. 0.0 gives a
totally black shadow while 1.0 gives no shadow.
Defaults to 0.0 .
"""
if (image.get_flags() & pygame.SRCALPHA or
image.get_colorkey() is not None):
shadow = make_shadow(image, ambience)
if shadow_scale is not None:
size = (array(shadow.get_size(), float32) * shadow_scale).astype(int32)
shadow = pygame.transform.smoothscale(shadow, size)
else:
size = (array(image.get_size(), float32) * shadow_scale).astype(int32)
if shadow_scale is None:
shadow_scale = 1.0
shadow = make_shadow_opaque(size, ambience, image.get_bitsize())
return place_shadow(image, shadow, shadow_offset)
__all__ = ['make_shadow', 'make_shadow_opaque', 'place_shadow', 'add_shadow']
Manipulating a surface's alpha values is one use for Pygame's surfarray module and an array package like Numeric or NumPy. The alpha values of a surface can be isolated as a two dimensional array of bytes.
image_alpha = pygame.surfarray.pixels_alpha(image)
Array operations can be performed on the alpha bytes.
shadow_alpha = (image_alpha *
(1.0 - ambience)).astype(uint8)
This multiplies all alpha bytes in the array by a floating point value.
The intermediate floating point array is then cast into the final array of single byte integers.
Finally, a surface's alpha values can be replaced with new values using an assignment to an array slice.
pygame.surfarray.pixels_alpha(shadow)[...] = shadow_alpha
Below is a demonstration program that adds shadows to text.
import pygame, sys
try:
pygame.surfarray.use_arraytype(sys.argv[1])
except IndexError:
pass
except ValueError:
print ("Unknown array type %s. Valid types are %s." %
(sys.argv[1], ", ".join(pygame.surfarray.get_arraytypes())))
sys.exit()
from pygame.locals import *
from shadows import *
def main():
screen_size = (400, 200)
pygame.init()
screen = pygame.display.set_mode(screen_size)
screen.fill((255, 255, 200, 255))
rect = screen.get_rect()
for i in range(3):
rect.inflate_ip(-60, -60)
pygame.draw.rect(screen, Color('gray'), rect, 1)
pygame.display.flip()
font = pygame.font.SysFont([], 24)
ambience = 0.4
textA = font.render("Per-pixel alpha, ambience %.1f" % ambience,
True,
Color('blue'))
labelA = add_shadow(textA, (20, 10), shadow_scale=0.8, ambience=ambience)
ambience = 0.2
alpha = 180
textB = font.render("Surface alpha %i, ambience %.1f" % (alpha, ambience),
True,
Color('red'), Color('white'))
textB.set_alpha(alpha)
labelB = add_shadow(textB, (20, 10), shadow_scale=0.8, ambience=ambience)
ambience = 0.2
textC = font.render("No alpha, ambience %.1f" % ambience,
True,
Color('white'), Color('black'))
labelC = add_shadow(textC, (20, 10), shadow_scale=0.8, ambience=ambience)
ambience = 0.8
textD = font.render("Colorkey, ambience %.1f" % ambience,
True,
Color('white'), Color('black'))
textD.set_colorkey(Color('white'))
labelD = add_shadow(textD, (20, 10), shadow_scale=0.8, ambience=ambience)
screen.blit(labelA, (50, 20))
screen.blit(labelB, (50, 67))
screen.blit(labelC, (50, 114))
screen.blit(labelD, (50, 160))
pygame.event.set_blocked(MOUSEMOTION)
repeat = 1
while repeat:
for e in pygame.event.get():
if e.type in [pygame.QUIT, pygame.MOUSEBUTTONDOWN]:
repeat = 0
break
elif e.type == pygame.KEYDOWN:
key = e.key
if key == K_q or key == K_ESCAPE:
repeat = 0
break
pygame.display.flip()
if __name__ == '__main__':
main()
This is the sampling of shadow effects it displays.
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 0016jduigr.com.cn