def Kaboom(score):
init()
gameDisplay.blit(GameOver,(382,175))
pygame.draw.rect(gameDisplay, white, (200, 400, 550, 50))
text = smallfont.render("Press [RETURN] to continue and [Q] to quit", True, darkBlue)
gameDisplay.blit(text, [370,400])
text = smallfont.render("Score : " + str(score), True, red)
gameDisplay.blit(text, [450,420])
pygame.display.update()
gameExit = True
while gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
gameExit = False
gameloop()
if event.key == pygame.K_q:
pygame.quit()
python类init()的实例源码
def display_test():
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption('Pygame')
pygame.mouse.set_visible(0)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250,250,250))
pxarray = pygame.PixelArray(background)
pxarray[:] = (i%250,i%25,i%150)
del pxarray
screen.blit(background, (0,0))
pygame.display.flip()
time.sleep(3)
def pygame_demo_image():
# this function is for demoing a default output
size,polygons,poly_sites,rivers,cities,roads,regions = setup()
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode(size,pygame.RESIZABLE)
pygame.display.set_caption('Map')
city_font = pygame.font.SysFont('arial', 20)
region_font = pygame.font.SysFont('arial', 30)
simple_render(polygons,poly_sites,rivers,cities,roads,regions,city_font,region_font,flag=True)
pygame.image.save(screen,'test.png')
pygame.quit()
def __init__(self, win_width = 640, win_height = 480):
pygame.init()
self.screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("JoySix Cube Demo")
self.clock = pygame.time.Clock()
self.vertices = [
[-1,1,-1],
[1,1,-1],
[1,-1,-1],
[-1,-1,-1],
[-1,1,1],
[1,1,1],
[1,-1,1],
[-1,-1,1]
]
# Define the vertices that compose each of the 6 faces. These numbers are
# indices to the vertices list defined above.
self.faces = [(0,1,2,3),(1,5,6,2),(5,4,7,6),(4,0,3,7),(0,4,5,1),(3,2,6,7)]
# Define colors for each face
self.colors = [(255,0,255),(255,0,0),(0,255,0),(0,0,255),(0,255,255),(255,255,0)]
self.angle = 0
self.joystick = joystick.Joystick()
def _vis_init(screen, mdp, draw_state, cur_state, agent=None, value=False):
# Pygame setup.
pygame.init()
screen.fill((255, 255, 255))
pygame.display.update()
done = False
# Draw name of MDP:
_draw_title_text(mdp, screen)
if agent is not None:
_draw_agent_text(agent, screen)
if not value:
# If we're not visualizing the value.
_draw_state_text(cur_state, screen)
agent_shape = draw_state(screen, mdp, cur_state, draw_statics=True)
return agent_shape
def main():
pygame.init()
screen = pygame.display.set_mode((500,500))
screen.fill((255, 0, 0))
s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32)
pygame.draw.line(s, (0,0,0), (250, 250), (250+200,250))
width = 1
for a_radius in range(width):
radius = 200
pygame.gfxdraw.aacircle(s, 250, 250, radius-a_radius, (0, 0, 0))
screen.blit(s, (0, 0))
pygame.display.flip()
try:
while 1:
event = pygame.event.wait()
if event.type == pygame.QUIT:
break
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.unicode == 'q':
break
pygame.display.flip()
finally:
pygame.quit()
def main():
pygame.init()
pygame.mixer.quit() # remove ALSA underflow messages for Debian squeeze
size = 600, 400
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = pygame.display.set_mode(size, NOFRAME, 0)
pygame.event.set_blocked(MOUSEMOTION) #keep our queue cleaner
pygame.time.set_timer(USEREVENT, 500)
while 1:
event = pygame.event.wait()
if event.type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
break
elif event.type == USEREVENT:
DisplayGradient(screen)
def load_sound(file):
if not pygame.mixer: return dummysound()
file = os.path.join(main_dir, 'data', file)
try:
sound = pygame.mixer.Sound(file)
return sound
except pygame.error:
print ('Warning, unable to load, %s' % file)
return dummysound()
# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
def main():
pygame.init()
pygame.font.init()
font = pygame.font.Font(None, 24)
bg = pygame.display.set_mode((800, 600), 0, 24)
bg.fill((255,255,255))
bg.blit(font.render("Click to advance", 1, (0, 0, 0)), (0, 0))
pygame.display.update()
for cursor in [no, arrow]:
TestCursor(cursor)
going = True
while going:
pygame.event.pump()
for e in pygame.event.get():
if e.type == pygame.MOUSEBUTTONDOWN:
going = False
pygame.quit()
def test_init__keyword_args(self):
# Fails on a Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
#### configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
configs = [{'frequency' : 22050, 'size' : -16, 'channels' : 2}]
for kw_conf in configs:
mixer.init(**kw_conf)
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def todo_test_pre_init__keyword_args(self):
# Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
for kw_conf in configs:
mixer.pre_init(**kw_conf)
mixer.init()
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def test_array_interface(self):
mixer.init(22050, -16, 1)
try:
snd = mixer.Sound(as_bytes('\x00\x7f') * 20)
d = snd.__array_interface__
self.assertTrue(isinstance(d, dict))
if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
typestr = '<i2'
else:
typestr = '>i2'
self.assertEqual(d['typestr'], typestr)
self.assertEqual(d['shape'], (20,))
self.assertEqual(d['strides'], (2,))
self.assertEqual(d['data'], (snd._samples_address, False))
finally:
mixer.quit()
def todo_test_pre_init(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.pre_init:
# pygame.mixer.pre_init(frequency=0, size=0, channels=0,
# buffersize=0): return None
#
# preset the mixer init arguments
#
# Any nonzero arguments change the default values used when the real
# pygame.mixer.init() is called. The best way to set custom mixer
# playback values is to call pygame.mixer.pre_init() before calling
# the top level pygame.init().
#
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.init:
# CD.init(): return None
# initialize a cdrom drive for use
#
# Initialize the cdrom drive for use. The drive must be initialized
# for most CD methods to work. Even if the rest of pygame has been
# initialized.
#
# There may be a brief pause while the drive is initialized. Avoid
# CD.init() if the program should not stop for a second or two.
#
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.play:
# CD.init(): return None
# initialize a cdrom drive for use
#
# Playback audio from an audio cdrom in the drive. Besides the track
# number argument, you can also pass a starting and ending time for
# playback. The start and end time are in seconds, and can limit the
# section of an audio track played.
#
# If you pass a start time but no end, the audio will play to the end
# of the track. If you pass a start time and 'None' for the end time,
# the audio will play to the end of the entire disc.
#
# See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def maskFromSurface(surface, threshold = 127):
mask = pygame.Mask(surface.get_size())
key = surface.get_colorkey()
if key:
for y in range(surface.get_height()):
for x in range(surface.get_width()):
if surface.get_at((x+0.1,y+0.1)) != key:
mask.set_at((x,y),1)
else:
for y in range(surface.get_height()):
for x in range (surface.get_width()):
if surface.get_at((x,y))[3] > threshold:
mask.set_at((x,y),1)
return mask
#pygame.init()
#pygame.display.set_mode((10,10))
def test_resolution(self):
was_init = ft.was_init()
if not was_init:
ft.init()
try:
ft.set_default_resolution()
resolution = ft.get_default_resolution()
self.assertEqual(resolution, 72)
new_resolution = resolution + 10
ft.set_default_resolution(new_resolution)
self.assertEqual(ft.get_default_resolution(), new_resolution)
ft.init(resolution=resolution+20)
self.assertEqual(ft.get_default_resolution(), new_resolution)
finally:
ft.set_default_resolution()
if was_init:
ft.quit()
def not_init_assertions(self):
self.assert_(not pygame.display.get_init(),
"display shouldn't be initialized" )
if 'pygame.mixer' in sys.modules:
self.assert_(not pygame.mixer.get_init(),
"mixer shouldn't be initialized" )
if 'pygame.font' in sys.modules:
self.assert_(not pygame.font.get_init(),
"init shouldn't be initialized" )
## !!! TODO : Remove when scrap works for OS X
import platform
if platform.system().startswith('Darwin'):
return
try:
self.assertRaises(pygame.error, pygame.scrap.get)
except NotImplementedError:
# Scrap is optional.
pass
# pygame.cdrom
# pygame.joystick
def test_quit__and_init(self):
# __doc__ (as of 2008-06-25) for pygame.base.quit:
# pygame.quit(): return None
# uninitialize all pygame modules
# Make sure everything is not init
self.not_init_assertions()
# Initiate it
pygame.init()
# Check
self.init_assertions()
# Quit
pygame.quit()
# All modules have quit
self.not_init_assertions()
def test_get_palette(self):
pygame.init()
try:
palette = [Color(i, i, i) for i in range(256)]
pygame.display.set_mode((100, 50))
surf = pygame.Surface((2, 2), 0, 8)
surf.set_palette(palette)
palette2 = surf.get_palette()
r,g,b = palette2[0]
self.failUnlessEqual(len(palette2), len(palette))
for c2, c in zip(palette2, palette):
self.failUnlessEqual(c2, c)
for c in palette2:
self.failUnless(isinstance(c, pygame.Color))
finally:
pygame.quit()
def test_set_palette_at(self):
pygame.init()
try:
pygame.display.set_mode((100, 50))
surf = pygame.Surface((2, 2), 0, 8)
original = surf.get_palette_at(10)
replacement = Color(1, 1, 1, 255)
if replacement == original:
replacement = Color(2, 2, 2, 255)
surf.set_palette_at(10, replacement)
self.failUnlessEqual(surf.get_palette_at(10), replacement)
next = tuple(original)
surf.set_palette_at(10, next)
self.failUnlessEqual(surf.get_palette_at(10), next)
next = tuple(original)[0:3]
surf.set_palette_at(10, next)
self.failUnlessEqual(surf.get_palette_at(10), next)
self.failUnlessRaises(IndexError,
surf.set_palette_at,
256, replacement)
self.failUnlessRaises(IndexError,
surf.set_palette_at,
-1, replacement)
finally:
pygame.quit()
def test_convert(self):
"""Ensure method convert() preserves the surface's class
When Surface is subclassed, the inherited convert() method will return
instances of the subclass. Non Surface fields are omitted, however.
This includes instance attributes.
"""
pygame.display.init()
try:
ms1 = self.MySurface((32, 32), 0, 24)
ms2 = ms1.convert(24)
self.assertTrue(ms2 is not ms1)
self.assertTrue(isinstance(ms2, self.MySurface))
self.assertTrue(ms1.an_attribute)
self.assertRaises(AttributeError, getattr, ms2, "an_attribute")
finally:
pygame.display.quit()
def test_convert_alpha(self):
"""Ensure method convert_alpha() preserves the surface's class
When Surface is subclassed, the inherited convert_alpha() method will
return instances of the subclass. Non Surface fields are omitted,
however. This includes instance attributes.
"""
pygame.display.init()
try:
pygame.display.set_mode((40, 40))
s = pygame.Surface((32, 32), pygame.SRCALPHA, 16)
ms1 = self.MySurface((32, 32), pygame.SRCALPHA, 32)
ms2 = ms1.convert_alpha(s)
self.assertTrue(ms2 is not ms1)
self.assertTrue(isinstance(ms2, self.MySurface))
self.assertTrue(ms1.an_attribute)
self.assertRaises(AttributeError, getattr, ms2, "an_attribute")
finally:
pygame.display.quit()
def main():
print 'Welcome to Alphabet to Morse Code Translator v.01\n'
msg = raw_input('Enter Message: ')
verify(msg)
print
pygame.init()
for char in msg:
if char == ' ':
print ' '*7,
time.sleep(SEVEN_UNITS)
else:
print CODE[char.upper()],
pygame.mixer.music.load(PATH + char.upper() + '_morse_code.ogg')
pygame.mixer.music.play()
time.sleep(THREE_UNITS)
def playmusic2(soundfile):
"""Stream music with mixer.music module using the event module to wait
until the playback has finished.
This method doesn't use a busy/poll loop, but has the disadvantage that
you neet to initialize the video module to use the event module.
Also, interrupting the playback with Ctrl-C does not work :-(
Change the call to 'playmusic' in the 'main' function to 'playmusic2'
to use this method.
"""
pygame.init()
pygame.mixer.music.load(soundfile)
pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
pygame.event.set_allowed(pygame.constants.USEREVENT)
pygame.mixer.music.play()
pygame.event.wait()
def avatar_gen_img(self):
font_size = int(self.size / 10 * 8)
pic_size = self.size
an, is_letter = self.avatar_name()
font = self.zh_font_file_name
if is_letter:
font = self.en_font_file_name
font_size = int(self.size / 10 * 11)
font_file = os.path.abspath(os.path.join(self.font_dir, font))
pygame.init()
f = pygame.font.Font(font_file, font_size)
is_light=self.is_light_color(self.avatar_background_color())
rtext = f.render(an.upper(), True, (0,0,0) if is_light else (255, 255, 255))
# pygame.image.save(rtext, '%s.png' % an)
mode = 'RGBA'
astr = pygame.image.tostring(rtext, 'RGBA')
circle = Image.new("RGBA", (self.size, self.size))
word = Image.frombytes(mode, f.size(an), astr)
word_x = int((pic_size - word.size[0]) / 2)
word_y = int(word_x * 0.9)
if is_letter:
word_y = int((pic_size - word.size[1]) / 2)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, self.size , self.size ),
fill=self.avatar_background_color(), outline=self.avatar_background_color())
draw.point((100, 100), 'red')
r, g, b, a = word.split()
circle.paste(word, (word_x, word_y), a)
sharpness = ImageEnhance.Sharpness(circle)
# circle = sharpness.enhance(7.0)
# im.show()
# circle.show()
# print(circle)
return circle
def _run_pygame_cb(self, main_fn):
assert pygame.display.get_surface() is None, "PygameCanvas.run_pygame can only be called once."
# Preinitialize Pygame with the X window ID.
assert pygame.display.get_init() == False, "Pygame must not be initialized before calling PygameCanvas.run_pygame."
os.environ['SDL_WINDOWID'] = str(self._socket.get_id())
pygame.init()
# Restore the default cursor.
self._socket.props.window.set_cursor(None)
# Initialize the Pygame window.
r = self.get_allocation()
pygame.display.set_mode((r.width, r.height), pygame.RESIZABLE)
# Hook certain Pygame functions with GTK equivalents.
self.translator.hook_pygame()
# Run the Pygame main loop.
main_fn()
return False
def init(self):
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((250, 250))
rospy.init_node('highway_teleop')
self.rate = rospy.Rate(rospy.get_param('~hz', 10))
self.acc = rospy.get_param('~acc', 5)
self.yaw = rospy.get_param('~yaw', 0)
self.robot_pub = rospy.Publisher('robot_0/cmd_vel', Twist, queue_size=1)
print "Usage: \n \
up arrow: accelerate \n \
down arrow: decelerate \n \
left arrow: turn left \n \
right arrow: turn right"
def init(self):
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((250, 250))
rospy.init_node('teleop')
self.rate = rospy.Rate(rospy.get_param('~hz', 20))
self.acc = rospy.get_param('~acc', 1)
self.yaw = rospy.get_param('~yaw', 0.25)
self.robot_pub = rospy.Publisher('control_command', controlCommand, queue_size=1)
self.path_record_pub = rospy.Publisher('record_state', \
RecordState, queue_size=1)
self.highway_game_start_pub = rospy.Publisher('highway_game_start', RecordState, queue_size=1)
print "Usage: \n \
up arrow: accelerate \n \
down arrow: decelerate \n \
left arrow: turn left \n \
right arrow: turn right"
def __soundInit(self):
"""
Initialises the pygame module and loads the sound samples
"""
# Initialise pygame module
pygame.mixer.pre_init(44100, -16, 12, 512) # TODO: Tweak values?
pygame.init()
# Load sounds from samples folder
self.__samples.append(pygame.mixer.Sound('samples/Blop-01.wav'))
self.__samples.append(pygame.mixer.Sound('samples/Glitch-02.wav'))
self.__samples.append(pygame.mixer.Sound('samples/Vocal-03.wav'))
self.__samples.append(pygame.mixer.Sound('samples/Noise-04.wav'))
self.__samples.append(pygame.mixer.Sound('samples/SFX-05.wav'))
self.__samples.append(pygame.mixer.Sound('samples/Strike-06.wav'))
for sample in self.__samples:
sample.set_volume(.95)