在pygame中有一种方法可以在程序最小化时暂停程序吗?

时间:2014-07-26 02:01:52

标签: python-3.x pygame

前几天我正在玩Terraria,在新的更新中,当游戏最小化时,它们会暂停游戏。显然它是用python编写的另一个程序,但我想知道是否有可能复制这些效果。

2 个答案:

答案 0 :(得分:1)

您可以使用pygame.display.get_active()检查窗口是否已最小化。

在示例中,您可以按SPACE以最小化窗口。

import pygame
import pygame.locals

pygame.init()

screen = pygame.display.set_mode((800,600))

count = 0

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            elif event.key == pygame.K_SPACE:
                pygame.display.iconify()

    if pygame.display.get_active():
        print count
        count +=1
    else:
        print "minimized"

pygame.quit()    

或者您可以使用pygame.ACTIVEEVENT获取有关更多事件的信息 - 例如最小化,鼠标移出窗口等等。

import pygame
import pygame.locals

pygame.init()

screen = pygame.display.set_mode((800,600))

count = 0

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            elif event.key == pygame.K_SPACE:
                pygame.display.iconify()
        elif event.type == pygame.ACTIVEEVENT:
            print 'state:', event.state, '| gain:', event.gain, 
            if event.state == 1:
                if event.gain == 0:
                    print "| mouse out",
                elif event.gain == 1:
                    print "| mouse in",
            elif event.state == 2:
                if event.gain == 0:
                    print "| titlebar pressed",
                elif event.gain == 1:
                    print "| titlebar unpressed",
            elif event.state == 6:
                if event.gain == 0:
                    print "| window minimized",
            elif event.state == 4:
                if event.gain == 1:
                    print "| window normal",
            print

pygame.quit()

只有在执行pygame.event.get()时,这两种方法才能正常工作。

答案 1 :(得分:0)

您可以使用pygame.APPACTIVE事件。来自pygame.display.iconify的文档:

Then the display mode is set, several events are placed on the pygame event queue. pygame.QUIT is sent when the user has requested the program to shutdown. The window will receive pygame.ACTIVEEVENT events as the display gains and loses input focus [This is when the window is minimized]. If the display is set with the pygame.RESIZABLE flag, pygame.VIDEORESIZE events will be sent when the user adjusts the window dimensions. Hardware displays that draw direct to the screen will get pygame.VIDEOEXPOSE events when portions of the window must be redrawn.

看看furas的第二个例子'回答下面的问题,但是不要使用第一个例子中的轮询方法来做这样的事情,你不想花时间每一帧试图检查窗口是否已被最小化。