Files
Project1/start.py
T

74 lines
2.2 KiB
Python

import os
import pygame
from src.config.game_config import GameConfig
from src.config.scenes import scene_dict
class Game:
def __init__(self):
# 初始化
pygame.init()
# 显示输入法候选框
os.environ["SDL_IME_SHOW_UI"] = "1"
# 如果设置中屏幕为0,0则获取屏幕大小
display_info = pygame.display.Info()
if not GameConfig.window_x:
GameConfig.window_x = display_info.current_w
if not GameConfig.window_y:
GameConfig.window_y = display_info.current_h
# 设置窗口大小
size = (GameConfig.window_x, GameConfig.window_y)
self.screen = pygame.display.set_mode(size, pygame.NOFRAME)
# 避免每次启动需要切换输入法
pygame.key.stop_text_input()
# 设置计时器
self.clock = pygame.time.Clock()
# 场景字典
self.game_scenes = scene_dict
# 当前场景
self.scene = self.game_scenes["MainMenuScene"](self.screen)
# 运行循环
self.running = True
self.run()
def run(self):
while self.running:
# 更新每帧时间
dt = self.clock.tick()
# 事件处理
for event in pygame.event.get(): # 这里已经获取了事件,事件队列被清空,在场景的update中再次获取将没有事件
if event.type == pygame.QUIT:
self.running = False
self.scene.handle_event(event) # 当前场景接收事件
# 检查是否切换场景
if self.scene.next_scene is not None:
if self.scene.next_scene in self.game_scenes.keys():
scene_class = self.game_scenes[self.scene.next_scene]
self.scene = scene_class(self.screen)
# 清屏
self.screen.fill(GameConfig.bg_color)
# 场景每帧更新逻辑运行
self.scene.update(dt)
# 当场景的下一场景为exit时退出游戏
if self.scene.next_scene == "exit":
self.running = False
# 更新显示
pygame.display.update()
if __name__ == "__main__":
Game()