Python pygame 模块,init() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygame.init()

项目:SmartCar    作者:amarlearning    | 项目源码 | 文件源码
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()
项目:pytari2600    作者:ajgrah2000    | 项目源码 | 文件源码
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)
项目:Maps    作者:DarkPurple141    | 项目源码 | 文件源码
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()
项目:joysix    作者:niberger    | 项目源码 | 文件源码
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()
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
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
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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()
项目:Material-Design-Avatar    作者:today4king    | 项目源码 | 文件源码
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
项目:PyCut    作者:FOSSRIT    | 项目源码 | 文件源码
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
项目:cs6244_motionplanning    作者:chenmin1107    | 项目源码 | 文件源码
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"
项目:cs6244_motionplanning    作者:chenmin1107    | 项目源码 | 文件源码
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"
项目:pi-thrum    作者:arosspope    | 项目源码 | 文件源码
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)
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def initPygame(w, h, caption=_DEFAULT_CAPTION, center_mouse=False, icon=None, centered=False):
    """
    Inicia Pygame

    :param w: Ancho de la ventana (px)
    :param h: Alto de la ventana (px)
    :param caption: Título de la ventana
    :param center_mouse: Indica si el mouse está centrado
    :param icon: Indica el ícono de la ventana
    :param centered: Indica si la ventana está centrada
    :return: None
    """
    pygame.init()
    if centered:
        os.environ['SDL_VIDEO_CENTERED'] = '1'
    pygame.display.set_mode((w, h), OPENGLBLIT | DOUBLEBUF)
    pygame.display.set_caption(caption)
    if center_mouse:
        pygame.mouse.set_pos(w / 2, h / 2)
    if icon is not None:
        pygame.display.set_icon(icon)


# noinspection PyBroadException,PyUnresolvedReferences
项目:Galaxian-Against-COMP140    作者:tomjlw    | 项目源码 | 文件源码
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("COMP140??--???????")
    play_button = Button(ai_settings, screen, "Play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    while True:
        gf.check_events(ai_settings, screen, stats, sb,  play_button, ship, aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb,  ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens, bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
项目:AR-BXT-AR4Python    作者:GeekLiB    | 项目源码 | 文件源码
def __init__(self, captionStr, markImageName, sceneImageName, OBJFileName, isMatches=False):
        markImage = cv2.imread(markImageName)
        sceneImage = cv2.imread(sceneImageName)
        height, width = sceneImage.shape[:2]

        # Init pygame.
        pygame.init()
        pygame.display.set_mode((width,height), OPENGL | DOUBLEBUF)
        pygame.display.set_caption(captionStr)

        draw_background(sceneImageName)

        glP, glM = getGLPM(markImage, sceneImage, isMatches)
        set_projection_from_camera(glP)
        if isMatches:
            set_modelview_from_camera(glM, 0.5)
        else:
            set_modelview_from_camera(glM)

        load_and_draw_model(OBJFileName)
项目:PyDesktopPlatform    作者:Nathoune    | 项目源码 | 文件源码
def __init__(self, size=(1024, 600)):

        pygame.init()

        self.screen = pygame.display.set_mode(size)

        self.background = pygame.image.load(
            DATA_FOLDER / "background.jpg").convert()

        self.player = Character("pikachu",
                                image=DATA_FOLDER / "pikachu.png",
                                x=(1024 - 100) / 2,
                                y=(600 - 100) / 2)
        self.blocks = []

        # create 3 balls 1...3

        for i in range(1, 2):
            block = Block(DATA_FOLDER / "folder-icon.jpg", x=300, y=300)
#             player.update()  # set random position on start
            self.blocks.append(block)

    #------------
项目:photobooth    作者:LoiX07    | 项目源码 | 文件源码
def __init__(self, name, size, fullscreen=True):
        # Call init routines
        pygame.init()

        # Window name
        pygame.display.set_caption(name)

        # Hide mouse cursor
        pygame.mouse.set_visible(False)

        # Store screen and size
        self.size = size
        if fullscreen:
            self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode(size)
            # windowed mode is for debug so we also show the cursor
            pygame.mouse.set_visible(True)

        # Clear screen
        self.clear()
        self.apply()
项目:TetrisAI    作者:bbergrobots    | 项目源码 | 文件源码
def __init__( self, grid, time, score, ai, grapher ):

        try:
            os.environ['SDL_VIDEO_WINDOW_POS'] = '10,50'
        except:
            pass
        self.grid = grid
        self.time = time
        self.score = score
        self.ai = ai
        self.grapher = grapher
        self.abort = False
        self.update = True
        self.infoMode = 0
        self.genomeScreen = [ 0, -1 ]
        self.aiState = False
        #gui.init( )
        self.screen = gui.display.set_mode( ( 820,720 ) )
        self.fontBold = gui.font.Font( 'font/texgyrecursor-bold.otf', 60 )
        self.fontRegular = gui.font.Font( 'font/texgyrecursor-regular.otf', 30 )
        self.fontSmall = gui.font.Font( 'font/texgyrecursor-regular.otf', 15 )
        self.updateStatic( True )
项目:pi-photo-booth    作者:gamblecd    | 项目源码 | 文件源码
def init(self):
        self.__initScreen()
        load_event = threading.Event()
        messageThread = self.__loadMessage(load_event)
        try:
            self.acting = False
            self._button = Button()
            self.__initActions()
            self.__initPreviewer()
            self.__initCamera()
            self.compliments = Compliments()
            time.sleep(.1)
            self.init_complete = True
        except Exception as e:
            load_event.set()
            messageThread.join()
            print(e)
            self.outputScreen.drawText("Load Failure: {}".format(e.message), erase=True)
            self.init_complete = False
        load_event.set()
        messageThread.join()
项目:Lab-Assistant    作者:SPARC-Auburn    | 项目源码 | 文件源码
def playsound(audio_file):
        """
        Plays mp3 use process best for each operating system
        :param audio_file: String of location of mp3 file to be played
        """
        if platform == "linux" or platform == "linux2":
            pygame.mixer.pre_init(22050, -16, 1, 2048)
            pygame.init()
            pygame.mixer.init()
            pygame.mixer.music.load(audio_file)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)
        else:
            sound = pyglet.media.load(audio_file, streaming=False)
            sound.play()
            time.sleep(sound.duration)
项目:freddie    作者:kunkkakada    | 项目源码 | 文件源码
def main():
    global DISPLAYSURF, font, menufont


    pygame.init()
    font = pygame.font.Font('etc/INVASION2000.ttf', 25)
    menufont = pygame.font.Font('etc/INVASION2000.ttf', 15)
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    pygame.display.set_caption('Ski Jump Henri 1.0')

    while True: # main game loop
        #header = 

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            #elif event.type == KEYDOWN and event.key == pygame.K_DOWN:



        for h in hills:
            player_jump(h)
项目:Traptris    作者:JesperDramsch    | 项目源码 | 文件源码
def __init__(self):
        pygame.init()
        pygame.key.set_repeat(250,25)
        self.width = cell_size*(2*cols+2)
        self.height = cell_size*rows
        self.rlim = cell_size*cols

        self.default_font =  pygame.font.Font(
            pygame.font.get_default_font(), 12)

        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.event.set_blocked(pygame.MOUSEMOTION) # We do not need
                                                     # mouse movement
                                                     # events, so we
                                                     # block them.
        self.next_stone = tetris_shapes[rand(len(tetris_shapes))]

        self.init_game()
        pygame.mixer.init()
        pygame.mixer.music.load(file)
        pygame.mixer.music.play(loops=-1)
项目:FaceSwap    作者:MarekKowalski    | 项目源码 | 文件源码
def __init__(self, targetImg, textureImg, textureCoords, mesh):
        self.h = targetImg.shape[0]
        self.w = targetImg.shape[1]

        pygame.init()
        pygame.display.set_mode((self.w, self.h), DOUBLEBUF|OPENGL)
        setOrtho(self.w, self.h)

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_TEXTURE_2D) 

        self.textureCoords = textureCoords
        self.textureCoords[0, :] /= textureImg.shape[1] 
        self.textureCoords[1, :] /= textureImg.shape[0]

        self.faceTexture = addTexture(textureImg)
        self.renderTexture = addTexture(targetImg)

        self.mesh = mesh
项目:rpi_lcars    作者:tobykurien    | 项目源码 | 文件源码
def __init__(self, screen, resolution=(800,480), 
                 ui_placement_mode=False, fps=60, dev_mode=False,
                 audio=(22050, -8, 1, 1024)):
        # init system
        pygame.mixer.init(audio[0], audio[1], audio[2], audio[3])
        pygame.font.init()
        pygame.init()

        self.screenSurface = pygame.display.set_mode(resolution) #, pygame.FULLSCREEN)
        self.fpsClock = pygame.time.Clock()
        self.fps = fps
        pygame.display.set_caption("LCARS")
        if not dev_mode: pygame.mouse.set_visible(False)

        # set up screen elements
        self.all_sprites = pygame.sprite.LayeredDirty()
        self.all_sprites.UI_PLACEMENT_MODE = ui_placement_mode

        self.screen = screen
        self.screen.setup(self.all_sprites)
        self.running = True
项目:openag_brain    作者:OpenAgInitiative    | 项目源码 | 文件源码
def __init__(self):
        self.air_temp = None
        self.humidity = None
        self.co2 = None
        self.o2 = None
        self.water_temp = None
        self.ph = None
        self.ec = None
        self.desired_temp = 25
        self.desired_hum = 50
        self.cmd_temp = 0
        self.cmd_hum = 0
        self.white = [255,255,255]
        self.black = [0,0,0]
        self.event_queue = None

        rospy.loginfo("Initializing touchscreen")
        pygame.init()
        # pygame.mouse.set_visible(False)
        self.screen = pygame.display.set_mode((WIDTH,HEIGHT),pygame.NOFRAME)
项目:pygame-flipclock    作者:prehensile    | 项目源码 | 文件源码
def init_pygame( self, native_width=480, native_height=272 ):

        self.background_colour = ( 255,255,255 )

        pygame.init()

        display_info = pygame.display.Info()
        w = display_info.current_w
        h = display_info.current_h
        self.window_size=(w,h)

        if (w <= native_width) or (h <= native_height):
            self.window = pygame.display.set_mode( self.window_size, pygame.FULLSCREEN )  
        else:
            self.window = pygame.display.set_mode( (native_width, native_height) )

        self.surface = pygame.display.get_surface()

        pygame.mouse.set_visible( False )

        self.clock = pygame.time.Clock()
项目:pytari2600    作者:ajgrah2000    | 项目源码 | 文件源码
def __init__(self, *args):
        # 'default_color' is used by stella init, need to set before super
        self.default_color = 0
        self._colors = PygameColors()
        super(PygameStella, self).__init__(*args)

        # Test if 'PixelArray' is part of pygame
        # pygame_cffi, may not have PixelArray

        if has_numpy:
            # Use a faster blit with a numpy array, if available.      
            self.driver_draw_display = self._draw_using_numpy_array
        elif hasattr(pygame, 'PixelArray'):
            self.driver_draw_display = self._draw_using_pixel_array
        else:
            self.driver_draw_display = self._draw_using_set_at
项目:pytari2600    作者:ajgrah2000    | 项目源码 | 文件源码
def driver_open_display(self):
      pygame.init()

      if has_numpy:
        # Replayce the 'display_lines' with a numpy array.
        #self._display_lines = numpy.zeros((self.END_DRAW_Y - self.START_DRAW_Y + 1, self.FRAME_WIDTH), dtype=numpy.int)
        self._display_lines = numpy.array(self._display_lines)

      self._screen = pygame.display.set_mode((
                            stella.Stella.FRAME_WIDTH  * stella.Stella.PIXEL_WIDTH, 
                            stella.Stella.FRAME_HEIGHT * stella.Stella.PIXEL_HEIGHT))
      pygame.display.set_caption('Pytari')
      pygame.mouse.set_visible(0)

      self._background = pygame.Surface((stella.Stella.FRAME_WIDTH, stella.Stella.FRAME_HEIGHT+stella.Stella.HORIZONTAL_BLANK))
      self._background = self._background.convert()
项目:CodeRepository    作者:sahirvsahirv    | 项目源码 | 文件源码
def init():
    """
    Initialize the black screen with tile, font and screen size
    """
    global SCREEN
    #initialize pygame - call the constructor
    pygame.init()


    os.environ["SDL_VIDEO_CENTERED"] = "1"

    #set the font
    font = pygame.font.Font('freesansbold.ttf', 20)
    #caption
    pygame.display.set_caption("Memory game")


    #screen object to display
    #resolution = (0,0) tuple - immutable data structure
    SCREEN = pygame.display.set_mode((TILEWIDTH*BOARDWIDTH, TILEHEIGHT*BOARDHEIGHT))
###################################INIT#################################



###################################DRAWBOARD#################################
项目:CodeRepository    作者:sahirvsahirv    | 项目源码 | 文件源码
def init():
    """
    Initialize the black screen with tile, font and screen size
    """
    global SCREEN
    #initialize pygame - call the constructor
    pygame.init()


    os.environ["SDL_VIDEO_CENTERED"] = "1"

    #set the font
    font = pygame.font.Font('freesansbold.ttf', 20)
    #caption
    pygame.display.set_caption("Memory game")


    #screen object to display
    #resolution = (0,0) tuple - immutable data structure
    SCREEN = pygame.display.set_mode((TILEWIDTH*BOARDWIDTH, TILEHEIGHT*BOARDHEIGHT))
###################################INIT#################################



###################################DRAWBOARD#################################
项目:slugscan    作者:SLUGSoc    | 项目源码 | 文件源码
def __init__(self):
        #pygame.init()
        self.screen = pygame.display.set_mode((S_WIDTH, S_HEIGHT))
        pygame.display.set_caption("SLUGScan")
        pygame.font.init()

        self.bg    = pygame.image.load(os.path.join("gui", "bg.jpg")).convert()
        self.title = pygame.image.load(os.path.join("gui", "slugs_logo.png")).convert_alpha()

        self.fontEvent = pygame.font.SysFont("DejaVu Sans", 48)
        self.fontEvent.set_bold(True)
        self.fontOut   = pygame.font.SysFont("DejaVu Sans", 20)

        self.eventName = ""
        self.outputBuf = ""

        self.textEvent = self.fontEvent.render(self.eventName, 1, (61,61,61))
        self.textOut   = self.fontOut.render(self.outputBuf, 1, (61,61,61))

        pygame.display.toggle_fullscreen()

        self.update()
项目:SelfDrivingRCCar    作者:sidroopdaska    | 项目源码 | 文件源码
def __init__(self):
        # Find the Arduino
        try:
            self.ser = find_arduino(serial_number=arduino_serial_number)
        except IOError as e:
            print(e)
            sys.exit()

        self.ser.flush()

        # Setup and begin pygame
        pygame.init()

        pygame.display.set_mode((400, 300))
        self.send_inst = True
        self.steer()