【发布时间】:2021-09-03 15:00:03
【问题描述】:
我使用 python pygame 和 android 子集创建了一个基于图块的简单游戏。 当我在我的安卓设备上退出应用程序并重新打开它时,我看到一个黑屏,如果我从“选项卡”关闭程序,那么游戏将再次运行,有人知道是什么问题吗?是不是一定要在程序中添加一些代码?
from pygame.locals import *
from settings import *
from sprites import *
import pygame
import time
import sys
import os
try:
import pygame_sdl2
pygame_sdl2.import_as_pygame()
except ImportError:
pass
pygame.init()
pygame.display.set_caption(TITLE)
class Game:
def __init__(self):
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.up_button = pygame.Rect(1000, 400, 100, 100)
self.down_button = pygame.Rect(1000, 600, 100, 100)
self.right_button = pygame.Rect(1100, 500, 100, 100)
self.left_button = pygame.Rect(900, 500, 100, 100)
self.all_sprites = pygame.sprite.Group()
self.walls = pygame.sprite.Group()
self.player = Player(self, 2, 2)
for x in range(5, 10):
Wall(self, x, 3)
for x in range(5, 10):
Wall(self, x, 7)
for y in range(3, 8):
Wall(self, 10, y)
self.buttons = pygame.sprite.Group()
self.game_over = False
def update(self):
self.all_sprites.update()
def draw(self):
self.screen.fill(BLACK)
self.draw_grid()
self.all_sprites.draw(self.screen)
pygame.draw.rect(self.screen, GREEN, self.up_button)
pygame.draw.rect(self.screen, RED, self.down_button)
pygame.draw.rect(self.screen, BLUE, self.right_button)
pygame.draw.rect(self.screen, YELLOW, self.left_button)
pygame.display.update()
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
if self.up_button.collidepoint(mouse_pos):
self.player.move(dy = -1)
elif self.down_button.collidepoint(mouse_pos):
self.player.move(dy = 1)
elif self.right_button.collidepoint(mouse_pos):
self.player.move(dx = 1)
elif self.left_button.collidepoint(mouse_pos):
self.player.move(dx = -1)
def run(self):
self.title_menu()
while not self.game_over:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
def draw_grid(self):
for x in range(0, WIDTH, TILESIZE):
pygame.draw.line(self.screen, LIGHTGRAY, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, TILESIZE):
pygame.draw.line(self.screen, LIGHTGRAY, (0, y), (WIDTH, y))
def title_menu(self):
pass
if __name__ == '__main__':
game = Game()
game.run()
【问题讨论】:
-
您是按
ESCAPE退出应用程序还是用主页按钮关闭它?由于 Android 如何使应用程序休眠并假定您的应用程序能够解冻,因此这一点非常重要。 -
我只是按主页按钮,如果我尝试按返回按钮它什么也做不了
-
您的代码明确表示在引发事件
pygame.QUIT时触发pygame.quit(),它仅在K_ESCAPE(键盘键Escape)被按下时引发。 主页按钮不是转义键。当您“再次”打开应用程序时,主页按钮将使应用程序休眠,而实际上它只是恢复了。这是为了在重新打开应用程序时节省处理能力和启动时间。这是人们想要的被关闭和打开超级快的错觉,而不是真正关闭它们;) -
此外,这段代码与 Android 无关,我错了吗?你如何在 Android 上运行它?猕猴桃?如果是这样,您可能应该在此处添加一些代码,以了解如何检测不同的 Android 特定操作系统调用和事件,因为我假设您在某种形式的 Python 模拟器中运行,因为 Android 并没有真正原生地执行 Python。
标签: android python pygame pysdl2