def __init__(self): self.gameover = False self.screen = pygame.display.set_mode(constants.SIZE) self.phase = 0 self.phases = [MainMenu, Play, GameOver] self.inter = Interactor() self.cur_phase = MainMenu(self.inter.get_top_5())
class SeriousGame(DirectObject): def __init__(self): DirectObject.__init__(self) self.__fsm = SeriousFSM() self.accept("serious_menu",self.__menu_window) self.accept("serious_new_game",self.__new_game_window) self.accept("serious_load_game",self.__load_game_window) self.accept("serious_description",self.__description) self.__fsm.request('Menu') def __menu_window(self): if type(self.__menu_window)==MainMenu: self.__menu_window.start() self.__fsm.set_menu_window(self.__menu_window) self.__menu_window.run() else: self.__menu_window = MainMenu() self.__menu_window.start() self.__fsm.set_menu_window(self.__menu_window) self.__menu_window.run() def __new_game_window(self): print '控制器选择了新建游戏窗口' def __load_game_window(self): print '控制器选择载入游戏窗口' def __description(self): print '进入描述界面'
class App(): def __init__(self, width, height): self.width = width self.height = height self.configure_window() self.show_main_menu() self.window.mainloop() def configure_window(self): self.window = tk.Tk() self.window.title("Minesweeper") self.window.geometry(f"{self.width}x{self.height}") self.window.minsize(300, 300) def show_main_menu(self): self.main_menu = MainMenu(self.window) self.main_menu.start_btn.config(command=self.show_play_options) self.main_menu.pack(fill=tk.BOTH, expand=True) def show_play_options(self): self.main_menu.pack_forget() self.play_options = PlayOptions(self.window) self.play_options.pack(fill=tk.BOTH, expand=True) # Used to set size of game to the same size as window self.play_options.width = self.width self.play_options.height = self.height
class App: def __init__(self): menu_options = menu_options_dict() self.menu = MainMenu(menu_options["main"][0], menu_options["main"][2:]) def run(self): self.menu.prompt()
def initMainMenu(self, customMainMenu=None): '''Call this to initialize and show main menu''' if not self.mainMenu: if not customMainMenu: self.mainMenu = MainMenu() else: self.mainMenu = customMainMenu self.mainMenu.open()
def __init__(self): self.display = pg.display.set_mode([640, 480]) self.next_screen = None self.running = True # menu = menu.Menu() self.screen = MainMenu() # screen = Lore() self.screen.bake() self.clock = pg.time.Clock()
def test_menu_block_init_test(self): """ """ m = MainMenu.NEW_QUERY() self.assertTrue(m.matches('menu-new-query')) m = MainMenu.VIEW() self.assertTrue(m.matches('menu-view')) m = MainMenu.SAVE() self.assertTrue(m.matches('menu-save')) m = MainMenu.CORPORA() self.assertTrue(m.matches('menu-corpora')) m = MainMenu.CONCORDANCE() self.assertTrue(m.matches('menu-concordance')) m = MainMenu.FILTER() self.assertTrue(m.matches('menu-filter')) m = MainMenu.FREQUENCY() self.assertTrue(m.matches('menu-frequency')) m = MainMenu.COLLOCATIONS() self.assertTrue(m.matches('menu-collocations')) m = MainMenu.HELP() self.assertTrue(m.matches('menu-help'))
class Game(arcade.Window): def __init__(self): super().__init__(WINDOW_WIDTH, WINDOW_LENGTH, "Aythar") self.main_menu_view = None self.aythar_view = None def setup(self): # When game starts, setup and display main menu self.main_menu_view = MainMenu() self.main_menu_view.setup() self.show_view(self.main_menu_view)
def __init__(self): ShowBase.__init__(self) MainMenu.__init__(self) GameApp.__init__(self) BattleApp.__init__(self) self.stack = [MainMenu()] self.gameTask = taskMgr.add(self.programLoop, 'programLoop') self.last = self.current() self.hasDrawnMainMenu = False self.disableMouse()
def main(): menu = MainMenu() while True: menu.show() preset_chosen = menu.preset_chosen if menu.exit: break board = Board(width=30, height=30, preset=presets_dict[preset_chosen]) controller = Controller(board, cell_size=20) controller.run()
def initialize(standard_screen): globals.STDSCR = standard_screen globals.MAIN = MainMenu() globals.INTERFACES.append(globals.MAIN) globals.MAP = GameMap() globals.INTERFACES.append(globals.MAP) globals.INVENTORY = Inventory() globals.INTERFACES.append(globals.INVENTORY) globals.PAUSE = PauseMenu() globals.INTERFACES.append(globals.PAUSE) globals.STORY = StoryScreen() globals.INTERFACES.append(globals.STORY) globals.CONTROLS_MAP = Controls(Controls.Type.game_map) globals.INTERFACES.append(globals.CONTROLS_MAP) globals.CONTROLS_INVENTORY = Controls(Controls.Type.inventory) globals.INTERFACES.append(globals.CONTROLS_INVENTORY) globals.CREDITS = Credits() globals.INTERFACES.append(globals.CREDITS) globals.NEW_GAME = NewGameDialog() globals.INTERFACES.append(globals.NEW_GAME) globals.QUIT_GAME = EndGameDialog() globals.INTERFACES.append(globals.QUIT_GAME) globals.SAVE_GAME = SaveGameDialog() globals.INTERFACES.append(globals.SAVE_GAME) globals.MONSTER = MonsterDialog() globals.INTERFACES.append(globals.MONSTER) globals.ITEM = ItemDialog() globals.INTERFACES.append(globals.ITEM) globals.GAME_OVER = GameOverDialog() globals.INTERFACES.append(globals.GAME_OVER) globals.LADDER = LadderDialog() globals.INTERFACES.append(globals.LADDER)
def update(self, method): if method == "calculate": self.alpha = float(self.alpha_entry.get()) self.l = float(self.l_entry.get()) self.u = float(self.u_entry.get()) result = erlang_c_time(self.l, self.u, self.alpha) self.num_servers = result['c'] self.ew = result['ew'] self.en = result['en'] self.ens = result['ens'] self.num_servers_result.set(self.num_servers) self.ew_result.set(self.ew) self.en_result.set(self.en) self.ens_result.set(self.ens) self.write_to_excel() elif method == "main-menu": self.root.destroy() from main_menu import MainMenu m_menu = MainMenu(self.f_path) m_menu.root.mainloop() else: # reset self.num_servers = 0
def main(): pygame.init() screen = pygame.display.set_mode(config['screen']['size']) elem = MainMenu(Rect((0, 0), config['screen']['size']), Color('white')) m = MainLoop(elem, screen) m.loop()
def initMainMenu(self,customMainMenu = None): '''Call this to initialize and show main menu''' if not self.mainMenu: if not customMainMenu: self.mainMenu = MainMenu() else: self.mainMenu = customMainMenu self.mainMenu.open()
def build(self): sm = ScreenManager() sm.add_widget(Login(name='login')) sm.add_widget(MainMenu(name='main_menu')) sm.add_widget(Profile(name='profile')) sm.add_widget(Results(name='results')) sm.add_widget(Tests(name='tests')) return sm
def __menu_window(self): if type(self.__menu_window)==MainMenu: self.__menu_window.start() self.__fsm.set_menu_window(self.__menu_window) self.__menu_window.run() else: self.__menu_window = MainMenu() self.__menu_window.start() self.__fsm.set_menu_window(self.__menu_window) self.__menu_window.run()
def __init__(self): self.root = Tk() self.root.geometry('{}x{}'.format(1000, 600)) self.root.wm_title("CMPUT 291 Database Application") #self.page = LogInPage(self.root) self.page = MainMenu(self.root) self.root.after(300, self.mainTask) self.root.mainloop()
class Game: """run the whole game""" def __init__(self): self.display = pg.display.set_mode([640, 480]) self.next_screen = None self.running = True # menu = menu.Menu() self.screen = MainMenu() # screen = Lore() self.screen.bake() self.clock = pg.time.Clock() def main(self): """Run the main tickloop""" while self.running: #handle events events = pg.event.get() for event in events: if event.type == pg.QUIT: self.running = False if event.type == SCREEN_TRANSITION: if event.new_screen is not None: self.next_screen = event.new_screen self.screen = self.next_screen self.screen.handle_events(events) self.display.fill((0, 0, 0)) self.screen.draw(self.display) self.clock.tick(60) pg.display.update() print("goodbye!") pg.quit()
def init_ui(self): self.main_menu = MainMenu(self) self.setting_dialog = SettingDialog(self) self.title_widget = TitleWidget(self) self.btn_mainmenu = self.title_widget.btn_mainmenu self.btn_min = self.title_widget.btn_min self.btn_max = self.title_widget.btn_max self.btn_close = self.title_widget.btn_close self.controlbar = ControlBar() self.controlbar.setFixedHeight(48) self.btn_open = self.controlbar.btn_open self.btn_play = self.controlbar.btn_play self.btn_pause = self.controlbar.btn_pause self.btn_stop = self.controlbar.btn_stop self.btn_fullscreen = self.controlbar.btn_fullscreen self.btn_playlist = self.controlbar.btn_playlist self.lab_time = self.controlbar.lab_time self.seekslider = self.controlbar.seekslider self.volumeslider = self.controlbar.volumeslider self.video.setMinimumSize(650, 350) #self.playlist = PlayList(_('PlayList')) self.playlist = PlayList() self.playlist.setFixedSize(150, 850) # playlist is hidden by default #self.playlist.hide() title_layout = QtGui.QHBoxLayout() title_layout.addWidget(self.title_widget) center_layout = QtGui.QHBoxLayout() center_layout.addWidget(self.video) center_layout.setSpacing(0) center_layout.addWidget(self.playlist) bottom_layout = QtGui.QHBoxLayout() bottom_layout.addWidget(self.controlbar) main_layout = QtGui.QGridLayout(self) main_layout.addLayout(title_layout, 0, 0) main_layout.addLayout(center_layout, 1, 0) main_layout.setSpacing(0) main_layout.addLayout(bottom_layout, 2, 0, 1, 2) # Fill the window with all contents, no gap in border. main_layout.setContentsMargins(0, 0, 0, 0) self.setLayout(main_layout)
def mainTask(self): if self.page.successor != -1: if self.page.successor == 0: self.page.quit() self.page.successor = -1 # Reset flag self.page = MainMenu(self.root) if self.page.successor == 1: self.page.quit() self.page.successor = -1 # Reset flag self.page = VehicleRegPage(self.root) elif self.page.successor == 2: self.page.quit() self.page.successor = -1 # Reset flag self.page = AutoTransactionPage(self.root) elif self.page.successor == 3: self.page.quit() self.page.successor = -1 # Reset flag self.page = DriverLicencePage(self.root) elif self.page.successor == 4: self.page.quit() self.page.successor = -1 # Reset flag self.page = ViolationRecordPage(self.root) elif self.page.successor == 5: self.page.quit() self.page.successor = -1 # Reset flag self.page = MainSearchPage(self.root) elif self.page.successor == 6: self.page.quit() self.page.successor = -1 # Reset flag self.page = GeneralSearchPage(self.root) elif self.page.successor == 7: self.page.quit() self.page.successor = -1 # Reset flag self.page = ViolationsSearchPage(self.root) elif self.page.successor == 8: self.page.quit() self.page.successor = -1 # Reset flag self.page = VehicleHistorySearchPage(self.root) self.root.after(300, self.mainTask) # reschedule event in 0.3 seconds
def mainMenu(self): m = MainMenu(self.screen, self.screen_settings) clock = pygame.time.Clock() while True: clock.tick() action = m.checkEvents() if action == "singleplayer": self.runSinglePlayer() m.need_screen_changes = True m.need_draw_changes = True continue elif action == "multiplayer": self.runMultiPlayer() elif action == "settings": self.runSettings() m.need_screen_changes = True m.need_draw_changes = True continue elif action == "quit": pygame.quit() exit() if m.need_draw_changes: m.draw() m.need_draw_changes = False
def __init__(self): Tk.__init__(self) self.app_version = '0.1' self.title('DCS Kneeboard Maker ' + self.app_version) self.main_menu = MainMenu(self) self.status_bar = StatusBar(self) self.status_bar.set_status('Ready') self.info_bar = InfoBar(self) x_scrollbar = Scrollbar(self, orient=HORIZONTAL) x_scrollbar.pack(side=BOTTOM, fill=X) y_scrollbar = Scrollbar(self, orient=VERTICAL) y_scrollbar.pack(side=RIGHT, fill=Y) self.x_scrollbar = x_scrollbar self.y_scrollbar = y_scrollbar self.file_path = '' self.display_scale = 4 self.min_display_scale = 1 self.max_display_scale = 8 w = 800 h = 600 self.img = np.ones((h, w, 3), dtype=np.uint8) * 127 empty_preview = PIL_Image.fromarray(self.img) empty_preview = ImageTk.PhotoImage(empty_preview) preview_canvas = Canvas(self, width=w, height=h, bd=2, relief=SUNKEN, bg='gray', xscrollcommand=x_scrollbar.set, yscrollcommand=y_scrollbar.set, scrollregion=(0, 0, w, h)) preview_canvas.create_image(0, 0, image=empty_preview, anchor=NW) preview_canvas.pack(side=TOP, expand=True, fill=BOTH) self.preview_canvas = preview_canvas self.preview_canvas.bind('<Motion>', self.mouse_move) self.preview_canvas.bind('<Button-1>', self.left_click) self.preview_canvas.bind('<Button-3>', self.right_click) self.preview_canvas.bind('<MouseWheel>', self.mouse_wheel) self.preview_canvas.bind('<Button-4>', self.mouse_wheel) self.preview_canvas.bind('<Button-5>', self.mouse_wheel) self.preview = empty_preview x_scrollbar.config(command=preview_canvas.xview) y_scrollbar.config(command=preview_canvas.yview) warnings.filterwarnings('ignore') self.mainloop()
def run_main_menu(self): """Call the main method of main_menu. If the instance has no 'main_menu' attribute or it is not properly initialized a new one is instantiated. Game.loop_main_menu(): return: EXIT if the user(s) quitted the game CHARACTER_MENU if the user(s) pressed the Play button OPTIONS_MENU if the user(s) pressed the Options button """ if not hasattr(self, "main_menu"): self.main_menu = MainMenu() else: self.main_menu.reinit() return self.main_menu.main(self.screen)
def build(self): screen_manager = ScreenManager() main_menu_screen = MainMenu(name='main_menu') questions_screen = Questions(name='questions') evidence_unique_screen = EvidenceUnique(name='evidence_unique') test_screen = Test(name='test') result_screen = Result(name='result') answers_screen = Answers(name='answers') evidence_screen = Evidence(name='evidence') screen_manager.add_widget(main_menu_screen) screen_manager.add_widget(questions_screen) screen_manager.add_widget(evidence_unique_screen) screen_manager.add_widget(test_screen) screen_manager.add_widget(result_screen) screen_manager.add_widget(answers_screen) screen_manager.add_widget(evidence_screen) return screen_manager
def setUp(self): # pygame.display.set_mode() self.main_menu = MainMenu() self.surface = pygame.Surface((0, 0)) self.event_quit = pygame.event.Event(pygame.QUIT) self.event_enter1 = pygame.event.Event(pygame.KEYDOWN, {'key': MAIN_CONTROLS[0]}) self.event_enter2 = pygame.event.Event(pygame.KEYDOWN, {'key': MAIN_CONTROLS[1]}) self.event_escape = pygame.event.Event(pygame.KEYDOWN, {'key': MAIN_CONTROLS[2]}) self.event_up1 = pygame.event.Event(pygame.KEYDOWN, {'key': P1_CONTROLS[2]}) self.event_up2 = pygame.event.Event(pygame.KEYDOWN, {'key': P2_CONTROLS[2]}) self.event_down1 = pygame.event.Event(pygame.KEYDOWN, {'key': P1_CONTROLS[3]}) self.event_down2 = pygame.event.Event(pygame.KEYDOWN, {'key': P2_CONTROLS[3]})
def main(): Configs.config.override({ "firebase_admin_key_file": "./FirebaseAdminKey.json", }) add_data_view = Views.add_data_view() show_header() fb_manager = FirebaseClient while True: action = MainMenu.show()['initial_action'] if action == 'Exit': break if action == 'Add new data': clear() add_data_view.execute()
def update(self, method): if method == "calculate": self.pb = float(self.pb_entry.get()) self.l = float(self.l_entry.get()) self.u = float(self.u_entry.get()) result = erlang_b(self.pb, self.l, self.u) self.num_servers = result['c'] self.pb_actual = result['pb_actual'] self.num_servers_result.set(self.num_servers) self.pb_actual_result.set(self.pb_actual) self.write_to_excel() elif method == "main-menu": self.root.destroy() from main_menu import MainMenu m_menu = MainMenu(self.f_path) m_menu.root.mainloop() else: # reset self.num_servers = 0
def update(self, method): if method == "calculate": self.u2 = float(self.u2_entry.get()) self.l = float(self.l_entry.get()) self.u1 = float(self.u1_entry.get()) result = two_servers(self.l, self.u1, self.u2) self.utilization = result['utilization'] self.p_idle = result['p_idle'] self.utilization_result.set(self.utilization) self.p_idle_result.set(self.p_idle) self.write_to_excel() elif method == "main-menu": self.root.destroy() from main_menu import MainMenu m_menu = MainMenu(self.f_path) m_menu.root.mainloop() else: # reset self.utilization = 0
def update(self, method): if method == "calculate": self.capacity = float(self.capacity_entry.get()) self.l = float(self.l_entry.get()) self.u = float(self.u_entry.get()) result = mm1k(self.l, self.capacity, self.u) self.utilization = result['utilization'] self.en = result['en'] self.utilization_result.set(self.utilization) self.en_result.set(self.en) self.write_to_excel() elif method == "main-menu": self.root.destroy() from main_menu import MainMenu m_menu = MainMenu(self.f_path) m_menu.root.mainloop() else: # reset self.utilization = 0
def main(): """Main game loop. Loop until events returns false.""" global START_TIME, MAIN_MENU pygame.init() pygame.display.set_caption('Path Finder') pygame.display.set_mode((600, 650), pygame.SRCALPHA) MAIN_MENU = MainMenu() running = True setup() clock = pygame.time.Clock() START_TIME = pygame.time.get_ticks() while running: clock.tick(60) pygame.time.wait(1) running = events() update() render() pygame.quit()
class Game: def __init__(self): self.gameover = False self.screen = pygame.display.set_mode(constants.SIZE) self.phase = 0 self.phases = [MainMenu, Play, GameOver] self.inter = Interactor() self.cur_phase = MainMenu(self.inter.get_top_5()) def process_drawing(self): self.cur_phase.draw(self.screen) pygame.display.flip() def process_logic(self): if self.cur_phase.is_changed: self.phase = (self.phase + 1) % 3 if self.phase == 1: self.cur_phase = self.phases[self.phase]( self.cur_phase.settings["speed"], self.cur_phase.settings["frequency"]) elif self.phase == 2: pygame.time.wait(10**3) self.inter.write(self.cur_phase.score * self.cur_phase.speed) self.cur_phase = self.phases[self.phase](self.cur_phase.score * self.cur_phase.speed) else: self.cur_phase = self.phases[self.phase]( self.inter.get_top_5()) self.cur_phase.logic() def process_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.gameover = True self.inter.close() self.cur_phase.event(event) def main_loop(self): clock = pygame.time.Clock() while not self.gameover: self.process_events() self.process_logic() self.process_drawing() clock.tick(constants.FPS)
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()): super(MainWindow, self).__init__(parent=parent) self.setWindowTitle(u"CDATGUI") self.spreadsheet = SpreadsheetWindow(f=QtCore.Qt.Widget) self.setCentralWidget(self.spreadsheet) var_widget = VariableWidget(parent=self) self.add_left_dock(var_widget) gm_widget = GraphicsMethodWidget(parent=self) self.add_left_dock(gm_widget) tmpl_widget = TemplateWidget(parent=self) self.add_left_dock(tmpl_widget) inspector = InspectorWidget(self.spreadsheet, parent=self) self.add_right_dock(inspector) con = ConsoleDockWidget(self.spreadsheet, parent=self) self.add_right_dock(con) self.setMenuBar( MainMenu(self.spreadsheet, var_widget, gm_widget, tmpl_widget))
from gameplay import Gameplay from main_menu import MainMenu while True: MainMenu().run_menu() currentGameplay = Gameplay() currentGameplay.run_gameplay()
class Game: """Class that consists of main, character, options and play menu and implements the communication between them. """ def __init__(self): """Initialize a pygame.display and a MainMenu member variables.""" pygame.init() self.screen = pygame.display.set_mode(SCREEN_SIZE) self.status = MAIN_MENU def run_main_menu(self): """Call the main method of main_menu. If the instance has no 'main_menu' attribute or it is not properly initialized a new one is instantiated. Game.loop_main_menu(): return: EXIT if the user(s) quitted the game CHARACTER_MENU if the user(s) pressed the Play button OPTIONS_MENU if the user(s) pressed the Options button """ if not hasattr(self, "main_menu"): self.main_menu = MainMenu() else: self.main_menu.reinit() return self.main_menu.main(self.screen) def run_character_menu(self): """Call the main method of character_menu. If the instance has no 'character_menu' attribute or it is not properly initialized a new one is instantiated. Game.loop_character_menu(): return: EXIT if the user(s) quitted the game MAIN_MENU if the user(s) when back to the main menu PLAY_MENU if the user(s) properly selected their characters and advanced to play the game """ if not hasattr(self, "character_menu"): self.character_menu = CharacterMenu() else: self.character_menu.reinit() return self.character_menu.main(self.screen) def run_options_menu(self): """Call the main method of options_menu. If the instance has no 'options_menu' attribute or it is not properly initialized a new one is instantiated. Game.loop_options_menu(): return: EXIT if the user(s) quitted the game MAIN_MENU if the user(s) when back to the main menu """ if not hasattr(self, "options_menu"): self.options_menu = OptionsMenu() return self.options_menu.main(self.screen) def run_play_menu(self): """Call the main method of play_menu. If the instance has 'play_menu' it is deleted and a new one is instantiated. Game.loop_play_menu(): return: EXIT if the display has been closed CHARACTER_MENU if the round has ended (a player died or the timer reached ROUND_TIME) """ if hasattr(self, "play_menu"): del self.play_menu self.play_menu = PlayMenu(self.character_menu.get_characters()) return self.play_menu.main(self.screen) def play(self): """Make the menus communicated with each other until an EXIT value is returned by the main method of a menu. The returned values are held in the status attribute. Game.play(): return None """ while self.status != EXIT: if self.status == MAIN_MENU: self.status = self.run_main_menu() elif self.status == CHARACTER_MENU: self.status = self.run_character_menu() elif self.status == OPTIONS_MENU: self.status = self.run_options_menu() elif self.status == PLAY_MENU: self.status = self.run_play_menu() pygame.quit()
def main_menu(self): menu = MainMenu(self) menu.run()
def main(): main_menu = MainMenu() while True: main_menu.display()
class MainMenuTest(unittest.TestCase): def setUp(self): # pygame.display.set_mode() self.main_menu = MainMenu() self.surface = pygame.Surface((0, 0)) self.event_quit = pygame.event.Event(pygame.QUIT) self.event_enter1 = pygame.event.Event(pygame.KEYDOWN, {'key': MAIN_CONTROLS[0]}) self.event_enter2 = pygame.event.Event(pygame.KEYDOWN, {'key': MAIN_CONTROLS[1]}) self.event_escape = pygame.event.Event(pygame.KEYDOWN, {'key': MAIN_CONTROLS[2]}) self.event_up1 = pygame.event.Event(pygame.KEYDOWN, {'key': P1_CONTROLS[2]}) self.event_up2 = pygame.event.Event(pygame.KEYDOWN, {'key': P2_CONTROLS[2]}) self.event_down1 = pygame.event.Event(pygame.KEYDOWN, {'key': P1_CONTROLS[3]}) self.event_down2 = pygame.event.Event(pygame.KEYDOWN, {'key': P2_CONTROLS[3]}) def tearDown(self): # pygame.display.quit() del self.main_menu del self.surface del self.event_quit del self.event_escape del self.event_enter1 del self.event_enter2 del self.event_up1 del self.event_up2 del self.event_down1 del self.event_down2 def test_sound(self): pygame.event.post(self.event_quit) self.main_menu.main(self.surface) self.assertFalse(pygame.mixer.get_busy()) def test_reinit(self): pygame.event.post(self.event_up1) pygame.event.post(self.event_enter2) self.main_menu.main(self.surface) self.assertFalse(self.main_menu.pointer == 0) self.assertIsNot(self.main_menu.get_pressed_button(), None) self.main_menu.reinit() self.assertTrue(self.main_menu.pointer == 0) self.assertIs(self.main_menu.get_pressed_button(), None) def test_update(self): self.main_menu.pointer = 182732 self.main_menu.update() self.assertTrue(self.main_menu.pointer >= 0 and self.main_menu.pointer < len(self.main_menu.buttons)) self.assertTrue(self.main_menu.buttons[self.main_menu.pointer]. is_flagged) for index in range(len(self.main_menu.buttons)): if index != self.main_menu.pointer: self.assertFalse(self.main_menu.buttons[index].is_flagged) def test_main(self): pygame.event.post(self.event_quit) result = self.main_menu.main(self.surface) self.assertEqual(result, EXIT) self.main_menu.reinit() pygame.event.post(self.event_escape) resutl = self.main_menu.main(self.surface) self.assertEqual(resutl, EXIT) self.main_menu.reinit() pygame.event.post(self.event_enter1) result = self.main_menu.main(self.surface) self.assertEqual(result, CHARACTER_MENU) self.main_menu.reinit() pygame.event.post(self.event_enter2) result = self.main_menu.main(self.surface) self.assertEqual(result, CHARACTER_MENU) self.main_menu.reinit() pygame.event.post(self.event_down1) pygame.event.post(self.event_enter1) result = self.main_menu.main(self.surface) self.assertEqual(result, OPTIONS_MENU) self.main_menu.reinit() pygame.event.post(self.event_up2) pygame.event.post(self.event_up1) pygame.event.post(self.event_enter2) result = self.main_menu.main(self.surface) self.assertEqual(result, OPTIONS_MENU) self.main_menu.reinit() pygame.event.post(self.event_up1) pygame.event.post(self.event_enter1) result = self.main_menu.main(self.surface) self.assertEqual(result, EXIT) self.main_menu.reinit() pygame.event.post(self.event_down1) pygame.event.post(self.event_down2) pygame.event.post(self.event_enter2) result = self.main_menu.main(self.surface) self.assertEqual(result, EXIT)
#!/usr/bin/env python from card_config import * from main_menu import MainMenu from analog_menu import AnalogMenu from gpio_blink_menu import GpioBlinkMenu from pwm_dim_menu import PwmDimMenu from uart_read_write_menu import UartReadWriteMenu import curses def init_screen(): screen = curses.initscr() screen.nodelay(True) curses.noecho() return screen if __name__ == '__main__': screen = init_screen() main_menu = MainMenu(screen, { 'Test Analog Jacks': (lambda: AnalogMenu(screen, JACK_TO_ANALOG)), 'Test GPIO Outputs': (lambda: GpioBlinkMenu(screen, JACK_TO_GPIO)), 'Test PWM Outputs': (lambda: PwmDimMenu(screen, JACK_TO_PWM)), 'Test UART Outputs': (lambda: UartReadWriteMenu(screen, UART_TX_TO_UART_RX)), }) main_menu.show()
#!/usr/bin/python3 # -*- coding: utf-8 -*- __author__ = 'Anton Vanke <*****@*****.**>' import sys from PyQt5.Qt import * from main_menu import MainMenu from game import GameBoard from hc_menu import ModeSelection if __name__ == '__main__': app = QApplication(sys.argv) mainmenu = MainMenu() def hc_menu(): hc_choice = ModeSelection(mainmenu) hc_choice.show() hc_choice.return_mainmenu_singal.connect(hc_choice.hide) def human_computer_mode(): # 人机对战模式 hc_game = GameBoard(mainmenu) hc_game.show() hc_game.return_mainmenu_singal.connect(hc_game.hide) mainmenu.human_computer_mode_singal.connect(hc_menu) mainmenu.show() sys.exit(app.exec_())
class SogalBase(ShowBase): """The ShowBase of the sogal Attributes: supportedResolutions: player's system supported resolutions, Note that it is constructed after the initialization of ShowBase. """ def __init__(self): "初始化" dir = os.path.dirname(game_settings['save_folder']) if not os.path.exists(dir): os.makedirs(dir) self.initGameSettings() #读取设置文件 loadPrcFile("config/PandaConfig.prc") loadPrcFileData('', 'win-size ' + str(game_settings['screen_resolution'][0]) + ' ' + str(game_settings['screen_resolution'][1]) ) #构造Panda3D的ShowBase ShowBase.__init__(self) #Retrieving available resolutions #self.makeDefaultPipe() di = self.pipe.getDisplayInformation() self.supportedResolutions = [] for index in range(di.getTotalDisplayModes()): self.supportedResolutions.append((di.getDisplayModeWidth(index), di.getDisplayModeHeight(index))) color_themes.initStyles() props = WindowProperties( self.win.getProperties() ) props.setSize(int(game_settings['screen_resolution'][0]),int(game_settings['screen_resolution'][1])) if game_settings['full_screen'] and not props.getFullscreen(): props.setFullscreen(True) props.setTitle(game_settings['window_title']) self.win.requestProperties(props) self.cam2dp.node().getDisplayRegion(0).setSort(-20) #Set render2dp to background self.disableMouse() #Disable panda3d's default mouse control self.cam.node().getDisplayRegion(0).setActive(0) #disable default camera self.audioPlayer = AudioPlayer() self.focusStack = [] #a stack that shows windowstop window gets focus self._loadReadText() self._loadGlobalData() #add event handlers self.accept('alt-enter', self.toggleFullScreen) self.accept('save_data', self.save) self.accept('load_data', self.load) self.accept('load_memory', self.loadMemory) self.accept('request_focus', self.grantFocus) self.accept('remove_focus', self.cancelFocus) self.accept('return_to_title', self.returnToTitle) self.accept('start_game', self.startGame) self.accept('load_game', self.loadGame) self.accept('config_form', self.showConfig) self.accept('exit_game', self.exit) self.accept('quick_save', self.quickSave) self.accept('quick_load', self.quickLoad) self.accept('auto_save', self.autoSave) self.accept('print_screen', self.takeScrnShot) self.accept('f10', self.takeScrnShot) #Font setting self.textFont = color_themes.default_font #背景设置 self.setBackgroundColor(0,0,0,1); self.backgroundImage = None self.initGameWindows() self.mainMenu = None self.storyManager = None def initGameWindows(self): ''' Initializing the common save, load and config forms if you want better customization with them, override this! ''' self.saveForm = SaveForm() self.loadForm = LoadForm() self.configForm = ConfigForm() def initGameSettings(self): ''' Initializing game settings some complex game settings can be written here This will run before panda3d ShowBase constructed ''' loadDefaultSettings('config/default.sconf') self._loadSettings() def initMainMenu(self,customMainMenu = None): '''Call this to initialize and show main menu''' if not self.mainMenu: if not customMainMenu: self.mainMenu = MainMenu() else: self.mainMenu = customMainMenu self.mainMenu.open() def isStarted(self): return bool(self.storyManager) def getCurrentFocus(self): if len(self.focusStack) > 0: return self.focusStack[-1] else: return None def hasFocus(self,obj): '''returns whether the object is the current focus''' return self.getCurrentFocus() == obj def grantFocus(self,obj): pre = self.getCurrentFocus() if obj in self.focusStack: self.focusStack.remove(obj) self.focusStack.append(obj) else: self.focusStack.append(obj) if pre != obj: if pre: pre.defocused() obj.focused() def cancelFocus(self,obj): if obj in self.focusStack: self.focusStack.remove(obj) obj.defocused() cur = self.getCurrentFocus() if cur != obj and cur: cur.focused() def setGameBackgroundImage(self,path): ''' Load a total background image ''' if self.backgroundImage: self.backgroundImage.destroy() self.backgroundImage = OnscreenImage(parent=aspect2dp, image=path) # @UndefinedVariable def save(self,saving,fileName,message): info = SavingInfo(message,datetime.now()) try: save_data(game_settings['save_folder'] + fileName + game_settings['save_type'], saving) save_data(game_settings['save_folder'] + fileName + game_settings['save_infotype'], info) except Exception as error: safeprint(error) return self.saveForm.reloadMember(fileName) self.loadForm.reloadMember(fileName) self._saveReadText() self._saveGlobalData() def quickSave(self, saving, message): global_data['currentQuicksave'] += 1 if global_data['currentQuicksave'] > MAX_QUICKSAVE: global_data['currentQuicksave'] = 1 currentqs = global_data['currentQuicksave'] self.save(saving, 'quick_save' + str(currentqs), message) def autoSave(self, saving, message): global_data['currentAutosave'] += 1 if global_data['currentAutosave'] > MAX_AUTOSAVE: global_data['currentAutosave'] = 1 currentas = global_data['currentAutosave'] self.save(saving, 'auto_save' + str(currentas), message) def load(self,fileName): try: savedData = load_data(game_settings['save_folder'] + fileName + game_settings['save_type']) except Exception as error: safeprint(error) return if self.mainMenu: self.mainMenu.close() if self.storyManager: self.storyManager.destroy() self.audioPlayer.stopAll(0.5) restoreRuntimeData(savedData) self.audioPlayer.reload() self.storyManager = StoryManager() def quickLoad(self): if self.hasQuickData(): self.load('quick_save' + str(global_data['currentQuicksave'])) def hasQuickData(self): return exists(game_settings['save_folder'] + 'quick_save' + str(global_data['currentQuicksave']) + game_settings['save_type']) def loadMemory(self,dumped): try: loaded = pickle.loads(dumped) except Exception as exp: safeprint(exp) return self.storyManager.destroy() self.audioPlayer.stopAll(0.5) restoreRuntimeData(loaded) self.audioPlayer.reload() self.storyManager = StoryManager() def getStyle(self, sheet = None): return rgetStyle(sheet) def setStyle(self,value): return rsetStyle(value) def toggleFullScreen(self): props = WindowProperties( self.win.getProperties() ) if not props.getFullscreen(): props.setSize(int(game_settings['screen_resolution'][0]),int(game_settings['screen_resolution'][1])) props.setFullscreen(True) else: props.setFullscreen(False) self.win.requestProperties(props) game_settings['full_screen'] = not game_settings['full_screen'] if self.configForm: self.configForm.refreshSettings() messenger.send('window-event', [self]) def exitfunc(self, *args, **kwargs): self._saveReadText() self._saveGlobalData() self._saveSettings() return ShowBase.exitfunc(self, *args, **kwargs) def startGame(self,scene): if self.mainMenu: self.mainMenu.close() if self.storyManager: self.storyManager.destroy() self.audioPlayer.stopAll(0.5) self.storyManager = StoryManager() self.storyManager.beginScene(scene) def loadGame(self): self.loadForm.show() def showConfig(self): self.configForm.show() def exit(self): sys.exit() def returnToTitle(self): if self.storyManager: self.storyManager.destroy() self.audioPlayer.stopAll(0.5) if self.mainMenu: self.mainMenu.open() def takeScrnShot(self): '''Take a screenshot''' dir = os.path.dirname('screenshots/') if not os.path.exists(dir): os.makedirs(dir) self.screenshot(namePrefix = 'screenshots/screenshot', defaultFilename = 1) def setScreenResolution(self, resolution = None, fullscreen = None): game_settings['screen_resolution'] = resolution or game_settings['screen_resolution'] if fullscreen is not None: game_settings['full_screen'] = fullscreen self._applyScreenResolution() def _loadReadText(self): if not exists(game_settings['save_folder']+ 'read.dat'): return try: read = load_data(game_settings['save_folder']+ 'read.dat') except Exception as exp: safeprint(exp) return restoreReadText(read) def _loadGlobalData(self): if not exists(game_settings['save_folder']+ 'global.dat'): return try: gdata = load_data(game_settings['save_folder']+ 'global.dat') except Exception as exp: safeprint(exp) return restoreGlobalData(gdata) def _loadSettings(self): if not exists(game_settings['save_folder']+ 'config.dat'): return try: settings = load_data(game_settings['save_folder'] + 'config.dat') except Exception as error: safeprint(error) return restoreSettings(settings) def _saveReadText(self): try: save_data(game_settings['save_folder']+ 'read.dat', read_text) except Exception as exp: safeprint(exp) def _saveGlobalData(self): try: save_data(game_settings['save_folder']+ 'global.dat', global_data) except Exception as exp: safeprint(exp) def _saveSettings(self): try: save_data(game_settings['save_folder']+ 'config.dat', game_settings) except Exception as exp: safeprint(exp) def _applyScreenResolution(self): props = WindowProperties( self.win.getProperties() ) if not props.getFullscreen: props.setSize(int(game_settings['screen_resolution'][0]),int(game_settings['screen_resolution'][1])) props.setFullscreen(game_settings['full_screen']) else: props.setFullscreen(game_settings['full_screen']) props.setSize(int(game_settings['screen_resolution'][0]),int(game_settings['screen_resolution'][1])) self.win.requestProperties(props) if self.configForm: self.configForm.refreshSettings() messenger.send('window-event', [self])