예제 #1
0
 def startDisplay(self):
     self.main_menu = MainMenu()
     self.main_menu.init()
     self.main_menu.secretsCallback = self.listSecrets
     self.main_menu.secretCallback = self.retrieveSecret
     self.main_menu.saltCallback = self.initEncryption
     self.main_menu.display()
예제 #2
0
class CreateGUI(tk.Tk):
    """The main class for the program

        Instance variables:
            edof: An noe x 7 array on the form array([[el_1, dof1, dof2...dof6],
            [el_noe, dof1, dof2...dof6]])
    """
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Frame 2000")
        self.state('zoomed')
        self.iconbitmap('icon_beam_2000.ico')
        self.resizable(False, False)

        # Create a list for storing instances of the element class
        self.element_list = []

        # Create a dictionary to store the topology information
        self.edof = np.empty((0, 7), float)

        # Create instances of window content
        self.menubar = Menubar(self)
        self.canvas = Canvas(self)
        self.main_menu = MainMenu(self)

        # Place the instances in the window
        self.canvas.pack(side="left", fill="both", expand=1, pady=20, padx=20)
        self.main_menu.pack(side="right", fill=tk.Y, padx=10)
예제 #3
0
    def test_add_task(self, mock_stdout):
        # Test adding task with a date provided
        main_menu = MainMenu()
        test_name = "John Doe"
        task_title = "Testing Task Title2"
        task_timespent = "30"
        task_notes = "coding!"
        datestr = "03/18/1981"

        prompts = [
            test_name, datestr, task_title, task_timespent, task_notes, 'y',
            'q'
        ]
        with mock.patch('builtins.input', side_effect=prompts):
            added_successfully = main_menu.add_task()
        self.assertTrue(added_successfully)

        # test adding task without date
        task_title = "Testing Task Title3"
        prompts = [
            test_name, "", task_title, task_timespent, task_notes, 'y', 'q'
        ]
        with mock.patch('builtins.input', side_effect=prompts):
            added_successfully = main_menu.add_task()
        self.assertTrue(added_successfully)
예제 #4
0
    def test_delete_task(self, mock_stdout):
        main_menu = MainMenu()
        test_name = "John Doe"
        task_title = "Testing Task To be deleted"
        task_timespent = "1"
        task_notes = "to be deleted"
        datestr = "07/04/1776"

        prompts = [
            test_name, datestr, task_title, task_timespent, task_notes, 'y',
            'q'
        ]
        with mock.patch('builtins.input', side_effect=prompts):
            main_menu.add_task()

        task_search = TaskSearch()
        prompts = ["07/04/1776", 'd', 'y', 'q', 'q']
        with mock.patch('builtins.input', side_effect=prompts):
            task_search.search_by_taskdate()

        sdate = convertdate("07/04/1976")
        tasks = Task.select().where(
                      Task.timestamp.year == sdate.year \
                      and Task.timestamp.month == sdate.month \
                      and Task.timestamp.day == sdate.day)

        self.assertEquals(len(tasks), 0)
예제 #5
0
class MyApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.root_node = None
        self.clean_up()
        self.set_background_color(0, 0, 0)
        self.game = Game(self, self.main_menu)
        self.mm = MainMenu(self, self.start_game)
        self.main_menu()

    def clean_up(self):
        self.ignore_all()
        if self.root_node is not None:
            self.root_node.remove_node()
        for child in self.aspect2d.get_children():
            child.remove_node()
        self.root_node = NodePath('root_node')
        self.root_node.reparent_to(self.render)
        self.accept("escape", sys.exit)  # Escape quits

    def start_game(self):
        self.clean_up()
        self.game.run(self.root_node, self.start_game)

    def main_menu(self):
        self.clean_up()
        self.mm.show()
예제 #6
0
파일: belda.py 프로젝트: samjar/Belda
 def start_screen(self):
     funcs = {'New Game': self.new,
              'Load': self.load_game,
              'Options': self.options,
              'Quit': self.quit}
     mm = MainMenu(self.screen, funcs.keys(), funcs)
     mm.menu_run()
예제 #7
0
 def __init__(self):
     ShowBase.__init__(self)
     self.root_node = None
     self.clean_up()
     self.set_background_color(0, 0, 0)
     self.game = Game(self, self.main_menu)
     self.mm = MainMenu(self, self.start_game)
     self.main_menu()
예제 #8
0
    def test_add_task_employee_not_found(self, mock_stdout):
        main_menu = MainMenu()
        test_name = "Employee Notfound"
        task_title = "Testing Task Title"
        task_timespent = "30"
        task_notes = "Testing out code"

        prompts = [
            test_name, " ", task_title, task_timespent, task_notes, 'y', 'q'
        ]
        with mock.patch('builtins.input', side_effect=prompts):
            added_successfully = main_menu.add_task()
        self.assertFalse(added_successfully)
예제 #9
0
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Frame 2000")
        self.state('zoomed')
        self.iconbitmap('icon_beam_2000.ico')
        self.resizable(False, False)

        # Create instances of window content
        self.menubar = Menubar(self)
        self.canvas = Canvas(self)
        self.main_menu = MainMenu(self)

        # Place the instances in the window
        self.canvas.pack(side="left", fill="both", expand=1, pady=20, padx=20)
        self.main_menu.pack(side="right", fill=tk.Y, padx=10)
예제 #10
0
 def __init__(self):
     pygame.init()
     # Initialize screen, and sets screen size
     self.surface = pygame.display.set_mode(size=(720, 640), flags=pygame.DOUBLEBUF)
     pygame.display.set_caption('Testing Game')
     self.game_state_manager = GameStateManager(self.surface, MainMenu(self.surface))
     self.clock = pygame.time.Clock()  # Creates instance of clock class
예제 #11
0
    def __init__(self):
        themed_tk.ThemedTk.__init__(self)
        self.set_theme("arc")
        ttk.Style(self)

        self.horizontal_panel = ttk.PanedWindow(self, orient="horizontal")
        self.vertical_panel = ttk.PanedWindow(self, orient="vertical")
        self.side_view = Notebook(self, has_labels=True)

        self.node = NodeEditor(self)
        self.console = Interpreter(self)
        self.modules = ModuleTree(self)
        self.objects = ObjectTree(self)

        self.vertical_panel.add(self.node.frame)
        self.vertical_panel.add(self.console.frame)
        self.side_view.add("Modules", self.modules)
        self.side_view.add("Objects", self.objects)
        self.horizontal_panel.add(self.side_view.frame)
        self.horizontal_panel.add(self.vertical_panel)
        self.horizontal_panel.pack(side="left", fill="both", expand=True)

        self.animate = Animation(self)
        self.project = SaveData(self)
        self.menu = MainMenu(self)
        self.config(menu=self.menu)
        self.project.load(is_first_load=True)
예제 #12
0
def main():
    pygame.init()

    pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('pyAsteroids')
    screen = pygame.display.get_surface()

    MainMenu(screen)
예제 #13
0
파일: game.py 프로젝트: vinla/FinalFlautist
 def __init__(self):
     self.screenSize = (800, 600)
     self.backgroundColor = (230, 230, 230)
     self.screen = pygame.display.set_mode(self.screenSize)
     self.clock = pygame.time.Clock()
     self.sceneStack = Stack()
     self.sceneStack.push(MainMenu(self))
     pygame.display.set_caption("Final Flautist")
예제 #14
0
def main():
    while True:
        #Setup objects
        mainMenu = MainMenu(surface)
        game = Levels(surface)
        timeline = Timeline(surface, mainClock)

        #Load music and play it if sound is on
        pygame.mixer.music.load('data\\sound\\Godbless.mid')
        if sound:
            pygame.mixer.music.play(-1, 0.0)

        #Display main menu
        mainMenu.menu(mainClock)
        #Select level
        timeline.timeline()
        #Run level 1620
        game.Y1620(mainClock)
예제 #15
0
class PasswordVault:

    storage_file = "/home/pi/password-vault-server/vault.json" if not debug.isDebug(
    ) else "vault.json"

    storage = None
    encryption = None
    main_menu = None

    def __init__(self):
        self.storage = Storage(self.storage_file)

    def startDisplay(self):
        self.main_menu = MainMenu()
        self.main_menu.init()
        self.main_menu.secretsCallback = self.listSecrets
        self.main_menu.secretCallback = self.retrieveSecret
        self.main_menu.saltCallback = self.initEncryption
        self.main_menu.display()

    def initEncryption(self, salt):
        self.encryption = Encryption(salt)
        # Validation
        secrets = self.storage.read()
        keys = list(secrets)
        if len(keys) > 0:
            return self.encryption.validate(secrets[keys[0]])
        return False

    def addSecret(self, key, secret):
        encoded_secret = self.encryption.encode(secret)
        secrets = self.storage.read()
        secrets[key] = encoded_secret
        self.storage.save(secrets)

    def listSecrets(self):
        secrets = self.storage.read()
        return list(secrets.keys())

    def retrieveSecret(self, key):
        secrets = self.storage.read()
        hashed_secret = secrets[key]
        decoded_secret = self.encryption.decode(hashed_secret)
        return decoded_secret
예제 #16
0
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Frame 2000")
        self.state('zoomed')
        self.iconbitmap('icon_beam_2000.ico')
        self.resizable(False, False)

        # Create a list for storing instances of the element class
        self.element_list = []

        # Create a dictionary to store the topology information
        self.edof = np.empty((0, 7), float)

        # Create instances of window content
        self.menubar = Menubar(self)
        self.canvas = Canvas(self)
        self.main_menu = MainMenu(self)

        # Place the instances in the window
        self.canvas.pack(side="left", fill="both", expand=1, pady=20, padx=20)
        self.main_menu.pack(side="right", fill=tk.Y, padx=10)
예제 #17
0
파일: main.py 프로젝트: H3LLB0Y/Centipede
class Main(ShowBase):
	def __init__(self):
		ShowBase.__init__(self)
		self.login = Login(self)
	
	def startMainmenu(self):
		self.login.hide()
		self.mainmenu = MainMenu(self)
		self.pregame = Pregame(self)
		self.mainmenu.show()
	
	def startPregame(self):
		self.mainmenu.hide()
		self.pregame.reset()
		self.pregame.show()

	def returnToMenu(self):
		self.pregame.hide()
		self.mainmenu.show()
	
	def startRound(self):
		self.pregame.hide()
		self.round = Round(self)
	
	def endRound(self):
		self.round.destroy()
		del self.round
		self.pregame.show()
		
	def hostGame(self, params):
		pid = Popen(["python", "server.py", params]).pid
		print 'Server Process ID:', pid
	
	def quit(self):
		sys.exit()
예제 #18
0
파일: game.py 프로젝트: Dylan3250/PyDragon
    def main(self):
        """ Lancement du jeu """
        pygame.init()  # Lance de Pygame
        screen = pygame.display.set_mode(
            (self.width, self.height))  # Crée la fenêtre
        pygame.display.set_caption(
            'PyDragon v0.4')  # Donne un nom à la fenêtre
        pygame.display.set_icon(pygame.image.load(
            self.favicon))  # Favicon du jeu
        self.son = pygame.mixer.Sound(
            "ressources/sounds/DBZFighter.wav")  # Défini le son du jeu
        self.son.set_volume(0.3)  # Permet de diminuer le son par défaut du jeu

        clock = pygame.time.Clock()  # Calcule le temps de départ pour les FPS

        while Niveau.WHILE_GAME:  # Boucle principale qui sert aux importations de maps
            if Niveau.LVL == 'while_main_menu':  # Nom défini qui orchestre tous les imports liés
                main_menu = MainMenu(
                    screen, clock, self.fps, self.son
                )  # Instancie la class qui affiche le menu de départ
                main_menu.while_menu()  # Boucle sur le menu
            elif Niveau.LVL == 'while_map_kamehouse':
                map_kamehouse = Kamehouse(self.width, self.height, screen,
                                          clock, self.fps, self.avancer)
                map_kamehouse.while_kamehouse()  # Boucle sur la map
            elif Niveau.LVL == 'while_map_kamehouse_in':
                map_kamehouse_in = KamehouseIn(self.width, self.height, screen,
                                               clock, self.fps, self.avancer)
                map_kamehouse_in.while_kamehouse_in()  # Boucle sur la map
            elif Niveau.LVL == 'while_map_town':
                map_world = WorldTown(self.width, self.height, screen, clock,
                                      self.fps, self.avancer)
                map_world.while_town()  # Boucle sur la map
            elif Niveau.LVL == 'while_map_town_in':
                map_world = WorldTownIn(self.width, self.height, screen, clock,
                                        self.fps, self.avancer)
                map_world.while_town_in()  # Boucle sur la map

        pygame.quit()  # Arrête le processus de PyGame
예제 #19
0
    def build(self):
        sm = ScreenManager()
        menu = MainMenu(name='menu')
        sed = StartEndDate(name='sed')
        settingscreen = SettingsScreen(name="settingscreen")
        task = TaskScreen(name='task')
        task_results = TaskResultsScreen(name='task_results')

        sm.add_widget(menu)
        sm.add_widget(task)
        sm.add_widget(settingscreen)
        sm.add_widget(sed)
        sm.add_widget(task_results)
        return sm
예제 #20
0
파일: mainwindow.py 프로젝트: mralphs/ace
    def initPages(self):
        self.mode_stack = QtGui.QStackedWidget()

        main_menu = MainMenu(self)  #0
        self.stats = Statistics(self)  #1
        self.trainer = Trainer(self, self.stats)  #2
        self.generator = Generator(self)  #3

        self.mode_stack.addWidget(main_menu)
        self.mode_stack.addWidget(self.stats)
        self.mode_stack.addWidget(self.trainer)
        self.mode_stack.addWidget(self.generator)

        self.setCentralWidget(self.mode_stack)
예제 #21
0
 def __init__(self):
   super().__init__()
   self.mainMenu = MainMenu()
   self.selectGame = SelectGame()
   self.settings = Settings()
   self.installGames = InstallGames()
   self.manageCharacters = ManageCharacters()
   self.viewCharacter = ViewCharacter()
   self.addWidget(self.mainMenu)
   self.addWidget(self.selectGame)
   self.addWidget(self.settings)
   self.addWidget(self.installGames)
   self.addWidget(self.manageCharacters)
   self.addWidget(self.viewCharacter)
   self.mainMenu.setCreateCharacterCallback(self.showSelectGame)
   self.mainMenu.setManageCharactersCallback(self.showManageCharacters)
   self.mainMenu.setSettingsCallback(self.showSettings)
   self.selectGame.setBackCallback(self.showMainMenu)
   self.selectGame.setInstallGamesCallback(self.showInstallGames)
   self.settings.setBackCallback(self.showMainMenu)
   self.installGames.setBackCallback(self.showSelectGame)
   self.manageCharacters.setBackCallback(self.showMainMenu)
   self.manageCharacters.setViewCallback(self.showViewCharacter)
   self.viewCharacter.setBackCallback(self.showManageCharacters)
예제 #22
0
def run_game():
    '''Run Game of Life.'''
    pygame.init()
    game_settings = Settings()

    screen = pygame.display.set_mode((game_settings.screen_width, 
                                      game_settings.screen_height))
    pygame.display.set_caption("Game of Life")

    # There is only one cell.
    cell = Cell(screen, game_settings)
    # Set main menu.
    main = MainMenu()
    # Set available options.
    options = Options(screen, game_settings)
    # Set speed and speed bar.
    speed = Speed(screen, game_settings)
    to_drop = [speed.actual_drop]
    # Set pause menu.
    state = Status(screen)

    # Build the matrix for live cells coordinates.
    mat_rows = game_settings.screen_height // game_settings.cell_height + 2
    mat_cols = game_settings.screen_width // game_settings.cell_width + 2
    cells_matrix = np.zeros(shape = (mat_rows, mat_cols)).astype(bool)

    xmouse, ymouse = None, None
    # Set to False the single step option.
    move_to_next_step = [False]

    while 1:
        gf.check_events(state, speed, main, options, xmouse, ymouse, 
                        move_to_next_step)
        if main.menu:
            xmouse, ymouse = pygame.mouse.get_pos()
            gf.main_menu(xmouse, ymouse, game_settings, state, speed, 
                         main, options, cells_matrix)
        elif not state.pause or move_to_next_step[0]:
            gf.game(move_to_next_step, cells_matrix, 
                    game_settings, state, speed, to_drop)

        gf.update_screen(game_settings, screen, cells_matrix, 
                         state, speed, main, options, cell)
예제 #23
0
def main():
    
    ### Initialize status variables
    done = False
    inMenu = True
    
    ### Initialize pygame
    pygame.init()
    screen = pygame.display.set_mode(WINDOW_SIZE)
    pygame.display.set_caption("Boston Cream")
    screen.fill(BLACK)
    
    ### Create game clock
    clock = pygame.time.Clock()
    
    ### Create menu and game objects
    print("Building menu")
    menu = MainMenu(screen)
    print("Building game")
    game = Game(screen)
    
    
    
    while not done:
        
        if inMenu:
            done, inMenu = menu.handle_events()
            menu.handle_logic()
            menu.handle_graphics()
        
        elif not inMenu:
            done, inMenu = game.handle_events()
            game.handle_logic()
            game.handle_graphics()
            
        else:
            print("Error: Neither in menu or in game...")
            
        clock.tick(FPS)
    
    pygame.quit()
예제 #24
0
from searchspreadsheet import SearchSpreadsheet
from countcolumninstances import CountColumnInstances
from createcertificates import CreateCertificates
from mainmenu import MainMenu

main_menu = MainMenu()

if main_menu.choice == "1":
    SearchSpreadsheet()

if main_menu.choice == "2":
    CountColumnInstances()

if main_menu.choice == "3":
    CreateCertificates()


예제 #25
0
def NodeAdmin():
    MainMenu()
예제 #26
0
파일: main.py 프로젝트: H3LLB0Y/Centipede
	def startMainmenu(self):
		self.login.hide()
		self.mainmenu = MainMenu(self)
		self.pregame = Pregame(self)
		self.mainmenu.show()
예제 #27
0
    def postInit(self):
        # Some game related variables
        self.currentLevel = 1
        self.youWon = False

        # Set esc to force exit $ remove
        self.accept('escape', self.exitApp)

        # Menu Events
        self.accept("menu_StartGame", self.startGame)
        self.accept("menu_Options", self.request, ["Options"])
        self.accept("menu_QuitGame", self.exitApp)
        self.accept("menu_Back", self.request, ["Menu"])
        self.accept("n", self.playNextTrack)

        ## Load Menu
        self.mainMenu = MainMenu()
        self.optionsMenu = OptionsMenu()

        ## Load music list
        self.musicList = [
            [
                "Housewell - Housewell - Sea  Sun  Fun",
                loader.loadMusic(
                    "music/Housewell_-_Housewell_-_Sea__Sun__Fun.ogg")
            ],
            [
                "KontrastE - LISTEN TO NIGHT",
                loader.loadMusic("music/KontrastE_-_LISTEN_TO_NIGHT.ogg")
            ],
            [
                "LukHash - THE OTHER SIDE",
                loader.loadMusic("music/LukHash_-_THE_OTHER_SIDE.ogg")
            ],
            [
                "Axl & Arth - Breathe",
                loader.loadMusic("music/Axl__amp__Arth_-_Breathe.ogg")
            ],
            [
                "Lyonn - The Symphony",
                loader.loadMusic("music/Lyonn_-_The_Symphony.ogg")
            ],
        ]
        self.lblNowPlaying = DirectLabel(text="No track running!",
                                         text_align=TextNode.ARight,
                                         text_fg=(240 / 255.0, 255 / 255.0,
                                                  240 / 255.0, 0.75),
                                         pos=(base.a2dRight - 0.05, 0,
                                              base.a2dBottom + 0.1),
                                         scale=0.04,
                                         frameColor=(0, 0, 0, 0.5),
                                         sortOrder=10)
        self.lblNowPlaying.hide()

        # The games Intro
        def create16To9LogoCard(logoPath, tsName):
            cm = CardMaker("fade")
            scale = abs(base.a2dLeft) / 1.7776
            cm.setFrame(-1, 1, -1 * scale, 1 * scale)
            logo = NodePath(cm.generate())
            logo.setTransparency(TransparencyAttrib.MAlpha)
            logoTex = loader.loadTexture(logoPath)
            logoTs = TextureStage(tsName)
            logoTs.setMode(TextureStage.MReplace)
            logo.setTexture(logoTs, logoTex)
            logo.setBin("fixed", 5000)
            logo.reparentTo(render2d)
            logo.hide()
            return logo

        self.gfLogo = create16To9LogoCard("intro/GrimFangLogo.png", "gfLogoTS")
        self.pandaLogo = create16To9LogoCard("intro/Panda3DLogo.png",
                                             "pandaLogoTS")
        self.gameLogo = create16To9LogoCard("intro/GameLogo.png", "gameLogoTS")

        def createFadeIn(logo):
            return LerpColorScaleInterval(logo, 2,
                                          LVecBase4f(0.0, 0.0, 0.0, 1.0),
                                          LVecBase4f(0.0, 0.0, 0.0, 0.0))

        def createFadeOut(logo):
            return LerpColorScaleInterval(logo, 2,
                                          LVecBase4f(0.0, 0.0, 0.0, 0.0),
                                          LVecBase4f(0.0, 0.0, 0.0, 1.0))

        gfFadeInInterval = createFadeIn(self.gfLogo)
        gfFadeOutInterval = createFadeOut(self.gfLogo)
        p3dFadeInInterval = createFadeIn(self.pandaLogo)
        p3dFadeOutInterval = createFadeOut(self.pandaLogo)
        gameFadeInInterval = createFadeIn(self.gameLogo)
        gameFadeOutInterval = createFadeOut(self.gameLogo)
        self.introFadeInOutSequence = Sequence(Func(self.gfLogo.show),
                                               gfFadeInInterval,
                                               Wait(1.0),
                                               gfFadeOutInterval,
                                               Wait(0.5),
                                               Func(self.gfLogo.hide),
                                               Func(self.pandaLogo.show),
                                               p3dFadeInInterval,
                                               Wait(1.0),
                                               p3dFadeOutInterval,
                                               Wait(0.5),
                                               Func(self.pandaLogo.hide),
                                               Func(self.gameLogo.show),
                                               gameFadeInInterval,
                                               Wait(1.0),
                                               gameFadeOutInterval,
                                               Wait(0.5),
                                               Func(self.gameLogo.hide),
                                               Func(self.messenger.send,
                                                    "intro_done"),
                                               Func(self.startMusic),
                                               name="fadeInOut")
        # game intro end

        # story intro
        self.storyImage1 = create16To9LogoCard("intro1.png", "storyIntro1TS")
        story1FadeInInterval = createFadeIn(self.storyImage1)
        story1FadeOutInterval = createFadeOut(self.storyImage1)
        self.storySequence = Sequence(Func(self.storyImage1.show),
                                      story1FadeInInterval,
                                      Wait(8.0),
                                      story1FadeOutInterval,
                                      Func(self.request, "Game"),
                                      name="story")

        # Outros
        self.outroImage1 = create16To9LogoCard("outro1.png", "storyOutro1TS")
        outro1FadeInInterval = createFadeIn(self.outroImage1)
        outro1FadeOutInterval = createFadeOut(self.outroImage1)
        self.outroWonSequence = Sequence(Func(self.outroImage1.show),
                                         outro1FadeInInterval,
                                         Wait(8.0),
                                         outro1FadeOutInterval,
                                         Func(self.request, "Game"),
                                         name="OutroWon")

        self.outroImage2 = create16To9LogoCard("outro2.png", "storyOutro2TS")
        outro2FadeInInterval = createFadeIn(self.outroImage2)
        outro2FadeOutInterval = createFadeOut(self.outroImage2)
        self.outroLostSequence = Sequence(Func(self.outroImage2.show),
                                          outro2FadeInInterval,
                                          Wait(8.0),
                                          outro2FadeOutInterval,
                                          Func(self.request, "Menu"),
                                          name="OutroLost")

        self.outroImage3 = create16To9LogoCard("outro3.png", "storyOutro3TS")
        outro3FadeInInterval = createFadeIn(self.outroImage3)
        outro3FadeOutInterval = createFadeOut(self.outroImage3)
        self.outroWonGameSequence = Sequence(Func(self.outroImage3.show),
                                             outro3FadeInInterval,
                                             Wait(8.0),
                                             outro3FadeOutInterval,
                                             Func(self.request, "Menu"),
                                             name="OutroWonGame")

        #
        # Start with the menu after the intro has been played
        #
        self.introFadeInOutSequence.start()
        self.accept("intro_done", self.request, ["Menu"])
예제 #28
0
파일: main.py 프로젝트: Aeryes/Demented
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            self.state.get_event(event)

    def main_game_loop(self):
        while not self.done:
            delta_time = self.clock.tick(60) / 1000
            self.event_loop()
            self.update(delta_time)
            pg.display.update()


#Settings from above dictionary get passed into Control class
#Control creates app object.
#Then, each state (Menu & Game) object get assigned to a dicitonary.
#This allows control to be able to switch to and from any state as needed.
app = Control()

#State Dictionary. Include all state classes here.
state_dict = {'mainmenu': MainMenu(), 'game': Game(), 'gameover': GameOver()}

#Setup State is called and sets the initial state of the program
app.setup_states(state_dict, 'mainmenu')

#Call main game loop that runs whole program
app.main_game_loop()

pg.quit()
sys.exit()
예제 #29
0
 def build(self):
     return MainMenu()
예제 #30
0
파일: main.py 프로젝트: PlumpMath/Warlocks
class Main(ShowBase):
    def __init__(self):
        self.created_client = False
        ShowBase.__init__(self)
        self.login = Login(self)
        self.client = Client(LOGIN_IP, LOGIN_PORT, compress=True)
        if not self.client.getConnected():
            self.login.updateStatus("Could not connect to the Login server")
            self.client = False

    def attempt_login(self, username, password):
        # check if processing a request already so if multiple presses of button it wont break this lol...
        # set a variable in login_packetReader() and check here

        # attempt to connect again if it failed on startup
        if not self.client:
            self.client = Client(LOGIN_IP, LOGIN_PORT, compress=True)
        if self.client.getConnected():
            self.username = username
            # Setup the un/up sendpacket, this will be changed. later :P
            data = {}
            data[0] = 'login_request'
            data[1] = {}
            data[1][0] = username
            data[1][1] = password
            self.client.sendData(data)
            # Add the handler for the login stage.
            taskMgr.doMethodLater(0.2, self.login_packetReader, 'Update Login')
            return True
        else:
            # client not connected to login/auth server so display message
            self.login.updateStatus("Could not connect to the Login server")
            self.client = False

    def create_account(self, username, password):
        # should be similar to attempt_login() but sends 'create_request' rather than 'login_request'
        # similarly need a create_packetReader() task to check for account_created success packet
        # then automatically call attempt_login with the username and password
        pass

    def login_packetReader(self, task):
        # setup some sort of timeout checker which will unset the checker variable in attempt_login function so it can go again
        # i think also for the 'db_reply' instead use the hex codes like you were thinking, and have each seperate code like 'already logged' 'wrong password/username' 'whatever else'
        # so on a return of a failure aswell, it will need to stop this task (return task.done)
        temp = self.client.getData()
        if temp != []:
            for i in range(len(temp)):
                valid_packet = False
                package = temp[i]
                if len(package) == 2:
                    print "Received: " + str(package)
                    print "Connected to login server"
                    # updates warlocks in game
                    """if package[0]=='error':
						print package
						print "User already logged"
						self.login.updateStatus(package[1])
						valid_packet=True
						break"""
                    if package[0] == 'db_reply':
                        print "DB: " + str(package[1])
                        self.login.updateStatus(package[1])
                        valid_packet = True
                    elif package[0] == 'login_valid':
                        print "Login valid: " + str(package[1])
                        self.login.updateStatus(package[1][0])
                        print "success: " + str(package[1][1])
                        valid_packet = True
                        print "I should move to main menu now..."
                        taskMgr.doMethodLater(0.3, self.start_mainmenu,
                                              'Start Main Menu')
                        return task.done
                    """if not valid_packet:
						data = {}
						data[0] = "error"
						data[1] = "Fail Server"
						self.client.sendData(data)
						print "Bad packet from server"""
                else:
                    print "Packet wrong size"
        return task.again

    def start_mainmenu(self, task):
        self.login.destroy()
        self.mainmenu = MainMenu(self)
        return task.done

    def join_server(self, address):
        # Store connection to lobby and chat i guess eventually
        self.lobby_con = self.client
        # attempt to connect to the game server
        self.client = Client(address, 9099, compress=True)
        if self.client.getConnected():
            print "Connected to server"
            data = {}
            data[0] = "username"
            data[
                1] = self.username  # This will end up being the selected server?
            self.client.sendData(data)
            taskMgr.doMethodLater(
                0.03, self.start_pregame,
                'Start Pregame')  # I guess this should change to Pregame.
            return True
        else:
            return False

    def start_pregame(self, task):
        self.mainmenu.hide()
        self.pregame = Pregame(self)
        return task.done

    def begin_preround(self):
        print "Game Starting"
        taskMgr.doMethodLater(0.01, self.start_preround, 'Start Preround')

    def start_preround(self, task):
        self.pregame.hide()
        self.preround = Preround(self)
        return task.done

    def begin_round(self):
        print "Round Starting"
        taskMgr.doMethodLater(0.01, self.start_round, 'Start Round')

    def start_round(self, task):
        self.preround.hide()
        self.round = Round(self)
        return task.done

    def quit(self):
        sys.exit()
예제 #31
0
파일: main.py 프로젝트: MJ-meo-dmt/Warlocks
class Main(ShowBase):
	def __init__(self):
		self.created_client=False
		ShowBase.__init__(self)
		self.prelobby=PreLobby(self)
	
	def login(self,username,password):
		self.username=username
		self.status=OnscreenText(text = "Attempting to login...", pos = Vec3(0, -0.4, 0), scale = 0.05, fg = (1, 0, 0, 1), align=TextNode.ACenter)
		# simulate authentication by delaying before continuing
		# if authentication fails, create prelobby again with status text "LOGIN FAILED!"
		#self.prelobby=PreLobby(self,"LOGIN FAILED!")
		# else proceed to lobby state
		taskMgr.doMethodLater(0.01, self.start_mainmenu, 'Start MainMenu')
		
	def start_mainmenu(self,task):
		self.prelobby.destroy()
		self.status.destroy()
		self.mainmenu=MainMenu(self)
		return task.done
		
	def join_server(self,address):
		# Connect to our server
		self.client = Client(address, 9099, compress=True)
		if self.client.getConnected():
			self.created_client=True
			data = {}
			data[0]="username"
			data[1]=self.username
			self.client.sendData(data)
			taskMgr.doMethodLater(0.01, self.start_lobby, 'Start Lobby')
			return True
		else:
			return False
		
	def start_lobby(self,task):
		self.mainmenu.hide()
		self.status.destroy()
		self.lobby=Lobby(self)
		return task.done
		
	def join_game(self):
		print "Game Starting"
		taskMgr.doMethodLater(0.01, self.start_game, 'Start Game')
	
	def start_game(self,task):
		self.lobby.hide()
		self.status.destroy()
		self.pregame=Pregame(self)
		return task.done
		
	def begin_round(self):
		print "Game Starting"
		taskMgr.doMethodLater(0.01, self.start_round, 'Start Round')
	
	def start_round(self,task):
		#self.pregame.hide()
		#self.status.destroy()
		self.playstate=Playstate(self)
		return task.done
	
	def quit(self):
		sys.exit()
예제 #32
0
    pygame.display.set_caption('Glarf')
    #pygame.mouse.set_visible(0)

    #Create The Backgound
    bgMangr = SeamedBackgroundManager(screen)

    #Display The Background
    screen.blit(bgMangr.GetBackground(), (0, 0))
    pygame.display.flip()

    #Prepare Game Objects
    clock = pygame.time.Clock()

    musicMangr = MusicManager()

    displayer = MainMenu(bgMangr, musicMangr)

    #Main Loop
    oldfps = 0
    while 1:
        timeChange = clock.tick(40)
        newfps = int(clock.get_fps())
        #if newfps != oldfps:
        #print "fps: ", newfps
        #oldfps = newfps

        #Handle Input Events
        remainingEvents = pygame.event.get()
        for event in remainingEvents:
            upKeys = filter(allKUPs, remainingEvents)
            if event.type == QUIT:
예제 #33
0
class Main(ShowBase, FSM):
    def __init__(self):
        ShowBase.__init__(self)
        FSM.__init__(self, "mainStateMachine")

        # some basic enhancements
        # window background color
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # hide the mouse cursor
        hide_cursor()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()

        base.sfxManagerList[0].setVolume(
            ConfigVariableDouble("audio-volume-sfx", 1.0).getValue())
        base.difficulty = ConfigVariableInt("difficulty", 0).getValue()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(w, h)
            # request the new properties
            base.win.requestProperties(props)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        elif base.appRunner:
            # When the application is started as appRunner instance, it
            # doesn't respect our loadPrcFiles configurations specific
            # to the window as the window is already created, hence we
            # need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                # check if we have the fullscreen variable
                if mainConfig.getVariableName(dec) == "fullscreen":
                    setFullscreen()
        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig

        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()

    def postInit(self):
        # Some game related variables
        self.currentLevel = 1
        self.youWon = False

        # Set esc to force exit $ remove
        self.accept('escape', self.exitApp)

        # Menu Events
        self.accept("menu_StartGame", self.startGame)
        self.accept("menu_Options", self.request, ["Options"])
        self.accept("menu_QuitGame", self.exitApp)
        self.accept("menu_Back", self.request, ["Menu"])
        self.accept("n", self.playNextTrack)

        ## Load Menu
        self.mainMenu = MainMenu()
        self.optionsMenu = OptionsMenu()

        ## Load music list
        self.musicList = [
            [
                "Housewell - Housewell - Sea  Sun  Fun",
                loader.loadMusic(
                    "music/Housewell_-_Housewell_-_Sea__Sun__Fun.ogg")
            ],
            [
                "KontrastE - LISTEN TO NIGHT",
                loader.loadMusic("music/KontrastE_-_LISTEN_TO_NIGHT.ogg")
            ],
            [
                "LukHash - THE OTHER SIDE",
                loader.loadMusic("music/LukHash_-_THE_OTHER_SIDE.ogg")
            ],
            [
                "Axl & Arth - Breathe",
                loader.loadMusic("music/Axl__amp__Arth_-_Breathe.ogg")
            ],
            [
                "Lyonn - The Symphony",
                loader.loadMusic("music/Lyonn_-_The_Symphony.ogg")
            ],
        ]
        self.lblNowPlaying = DirectLabel(text="No track running!",
                                         text_align=TextNode.ARight,
                                         text_fg=(240 / 255.0, 255 / 255.0,
                                                  240 / 255.0, 0.75),
                                         pos=(base.a2dRight - 0.05, 0,
                                              base.a2dBottom + 0.1),
                                         scale=0.04,
                                         frameColor=(0, 0, 0, 0.5),
                                         sortOrder=10)
        self.lblNowPlaying.hide()

        # The games Intro
        def create16To9LogoCard(logoPath, tsName):
            cm = CardMaker("fade")
            scale = abs(base.a2dLeft) / 1.7776
            cm.setFrame(-1, 1, -1 * scale, 1 * scale)
            logo = NodePath(cm.generate())
            logo.setTransparency(TransparencyAttrib.MAlpha)
            logoTex = loader.loadTexture(logoPath)
            logoTs = TextureStage(tsName)
            logoTs.setMode(TextureStage.MReplace)
            logo.setTexture(logoTs, logoTex)
            logo.setBin("fixed", 5000)
            logo.reparentTo(render2d)
            logo.hide()
            return logo

        self.gfLogo = create16To9LogoCard("intro/GrimFangLogo.png", "gfLogoTS")
        self.pandaLogo = create16To9LogoCard("intro/Panda3DLogo.png",
                                             "pandaLogoTS")
        self.gameLogo = create16To9LogoCard("intro/GameLogo.png", "gameLogoTS")

        def createFadeIn(logo):
            return LerpColorScaleInterval(logo, 2,
                                          LVecBase4f(0.0, 0.0, 0.0, 1.0),
                                          LVecBase4f(0.0, 0.0, 0.0, 0.0))

        def createFadeOut(logo):
            return LerpColorScaleInterval(logo, 2,
                                          LVecBase4f(0.0, 0.0, 0.0, 0.0),
                                          LVecBase4f(0.0, 0.0, 0.0, 1.0))

        gfFadeInInterval = createFadeIn(self.gfLogo)
        gfFadeOutInterval = createFadeOut(self.gfLogo)
        p3dFadeInInterval = createFadeIn(self.pandaLogo)
        p3dFadeOutInterval = createFadeOut(self.pandaLogo)
        gameFadeInInterval = createFadeIn(self.gameLogo)
        gameFadeOutInterval = createFadeOut(self.gameLogo)
        self.introFadeInOutSequence = Sequence(Func(self.gfLogo.show),
                                               gfFadeInInterval,
                                               Wait(1.0),
                                               gfFadeOutInterval,
                                               Wait(0.5),
                                               Func(self.gfLogo.hide),
                                               Func(self.pandaLogo.show),
                                               p3dFadeInInterval,
                                               Wait(1.0),
                                               p3dFadeOutInterval,
                                               Wait(0.5),
                                               Func(self.pandaLogo.hide),
                                               Func(self.gameLogo.show),
                                               gameFadeInInterval,
                                               Wait(1.0),
                                               gameFadeOutInterval,
                                               Wait(0.5),
                                               Func(self.gameLogo.hide),
                                               Func(self.messenger.send,
                                                    "intro_done"),
                                               Func(self.startMusic),
                                               name="fadeInOut")
        # game intro end

        # story intro
        self.storyImage1 = create16To9LogoCard("intro1.png", "storyIntro1TS")
        story1FadeInInterval = createFadeIn(self.storyImage1)
        story1FadeOutInterval = createFadeOut(self.storyImage1)
        self.storySequence = Sequence(Func(self.storyImage1.show),
                                      story1FadeInInterval,
                                      Wait(8.0),
                                      story1FadeOutInterval,
                                      Func(self.request, "Game"),
                                      name="story")

        # Outros
        self.outroImage1 = create16To9LogoCard("outro1.png", "storyOutro1TS")
        outro1FadeInInterval = createFadeIn(self.outroImage1)
        outro1FadeOutInterval = createFadeOut(self.outroImage1)
        self.outroWonSequence = Sequence(Func(self.outroImage1.show),
                                         outro1FadeInInterval,
                                         Wait(8.0),
                                         outro1FadeOutInterval,
                                         Func(self.request, "Game"),
                                         name="OutroWon")

        self.outroImage2 = create16To9LogoCard("outro2.png", "storyOutro2TS")
        outro2FadeInInterval = createFadeIn(self.outroImage2)
        outro2FadeOutInterval = createFadeOut(self.outroImage2)
        self.outroLostSequence = Sequence(Func(self.outroImage2.show),
                                          outro2FadeInInterval,
                                          Wait(8.0),
                                          outro2FadeOutInterval,
                                          Func(self.request, "Menu"),
                                          name="OutroLost")

        self.outroImage3 = create16To9LogoCard("outro3.png", "storyOutro3TS")
        outro3FadeInInterval = createFadeIn(self.outroImage3)
        outro3FadeOutInterval = createFadeOut(self.outroImage3)
        self.outroWonGameSequence = Sequence(Func(self.outroImage3.show),
                                             outro3FadeInInterval,
                                             Wait(8.0),
                                             outro3FadeOutInterval,
                                             Func(self.request, "Menu"),
                                             name="OutroWonGame")

        #
        # Start with the menu after the intro has been played
        #
        self.introFadeInOutSequence.start()
        self.accept("intro_done", self.request, ["Menu"])

    def exitApp(self):
        if self.state == "Off":
            self.introFadeInOutSequence.finish()
        elif self.state == "Menu":
            self.userExit()
        elif self.state == "Intro":
            self.storySequence.finish()
        elif self.state == "Outro":
            if self.youWon:
                if self.currentLevel == 2:
                    self.outroWonSequence.finish()
                else:
                    self.outroWonGameSequence.finish()
            else:
                self.outroLostSequence.finish()
        else:
            self.request("Menu")

    def startMusic(self):
        self.lblNowPlaying.show()
        self.lastPlayed = None
        self.currentTrack = [None]
        self.playNextTrack()
        base.taskMgr.add(self.musicTask, "music playlist")

    def playNextTrack(self):
        if self.currentTrack[0] is not None:
            self.currentTrack[1].stop()
        while self.lastPlayed == self.currentTrack[0]:
            self.currentTrack = random.choice(self.musicList)
        self.lastPlayed = self.currentTrack[0]
        self.lblNowPlaying[
            "text"] = "Press 'N' for Next ~\nNOW PLAYING: {}".format(
                self.currentTrack[0])
        self.lblNowPlaying.resetFrameSize()
        self.currentTrack[1].play()

    def musicTask(self, task):
        if not base.AppHasAudioFocus: return task.cont
        track = self.currentTrack[1]
        if track.status() != track.PLAYING:
            self.playNextTrack()
        return task.cont

    def startGame(self):
        self.acceptWinLoose()
        self.currentLevel = 1
        self.request("Intro")

    def enterMenu(self):
        show_cursor()
        self.mainMenu.show()

    def exitMenu(self):
        self.mainMenu.hide()

    def enterOptions(self):
        self.optionsMenu.show()

    def exitOptions(self):
        self.optionsMenu.hide()

    def enterIntro(self):
        self.storySequence.start()

    def enterGame(self):
        self.youWon = False
        hide_cursor()
        ## Load/Start GameBase
        self.gamebase = GameBase()
        ## Load/Start Game
        self.game = Game()
        self.gamebase.start()
        self.game.setPhysicsWorld(self.gamebase.physics_world)
        if base.difficulty == 0:
            self.game.start(self.currentLevel, 25)
        elif base.difficulty == 1:
            self.game.start(self.currentLevel, 50)
        else:
            self.game.start(self.currentLevel, 100)
        self.acceptWinLoose()

        # Debug #
        #self.gamebase.enablePhysicsDebug()
        #print (render.ls())

    def exitGame(self):
        self.ignoreWinLoose()
        self.game.stop()
        self.gamebase.stop()
        del self.game
        del self.gamebase
        self.game = None
        self.gamebase = None

    def enterOutro(self):
        if self.youWon:
            if self.currentLevel == 1:
                self.outroWonSequence.start()
            else:
                self.outroWonGameSequence.start()
        else:
            self.outroLostSequence.start()

    def wonGame(self):
        self.ignoreWinLoose()
        self.youWon = True
        self.request("Outro")
        self.currentLevel += 1

    def lostGame(self):
        self.ignoreWinLoose()
        self.youWon = False
        self.request("Outro")

    def acceptWinLoose(self):
        self.accept("wonGame", self.wonGame)
        self.accept("lostGame", self.lostGame)

    def ignoreWinLoose(self):
        self.ignore("wonGame")
        self.ignore("lostGame")

    def __writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        volume = str(round(base.musicManager.getVolume(), 2))
        volumeSfx = str(round(base.sfxManagerList[0].getVolume(), 2))
        mute = "#f" if base.AppHasAudioFocus else "#t"
        difficuty = str(base.difficulty)
        customConfigVariables = [
            "", "audio-mute", "audio-volume", "audio-volume-sfx", "difficulty"
        ]
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(prcFile)
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base or other
                #       manual config changes by the user
                if page.getVariableName(dec) in customConfigVariables:
                    decl = page.modifyDeclaration(dec)
                    removeDecls.append(decl)
            for dec in removeDecls:
                page.deleteDeclaration(dec)
            # NOTE: audio-mute are custom variables and
            #       have to be loaded by hand at startup
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-volume-sfx", volumeSfx)
            page.makeDeclaration("audio-mute", mute)
            page.makeDeclaration("difficulty", difficuty)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("App Pandaconfig")
            # set OpenGL to be the default
            page.makeDeclaration("load-display", "pandagl")
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set the window size in the config file
            page.makeDeclaration("win-size", "%d %d" % (w, h))
            # set the default to fullscreen in the config file
            page.makeDeclaration("fullscreen", "1")
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-volume-sfx", volumeSfx)
            page.makeDeclaration("audio-mute", "#f")
            page.makeDeclaration("sync-video", "1")
            page.makeDeclaration("textures-auto-power-2", "1")
            page.makeDeclaration("framebuffer-multisample", "1")
            page.makeDeclaration("multisamples", "2")
            page.makeDeclaration("texture-anisotropic-degree", "0")
            page.makeDeclaration("difficulty", 0)
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
예제 #34
0
파일: main.py 프로젝트: H3LLB0Y/Warlocks
	def start_mainmenu(self,task):
		self.login.destroy()
		self.mainmenu=MainMenu(self)
		return task.done
예제 #35
0
파일: main.py 프로젝트: H3LLB0Y/Warlocks
class Main(ShowBase):
	def __init__(self):
		self.created_client=False
		ShowBase.__init__(self)
		self.login=Login(self)
		self.client = Client(LOGIN_IP, LOGIN_PORT, compress=True)
		if not self.client.getConnected():
			self.login.updateStatus("Could not connect to the Login server")
			self.client=False
		
	def attempt_login(self, username, password):
		# check if processing a request already so if multiple presses of button it wont break this lol...
		# set a variable in login_packetReader() and check here
		
		# attempt to connect again if it failed on startup
		if not self.client:
			self.client = Client(LOGIN_IP, LOGIN_PORT, compress=True)
		if self.client.getConnected():
			self.username=username
			# Setup the un/up sendpacket, this will be changed. later :P
			data = {}
			data[0] = 'login_request'
			data[1] = {}
			data[1][0] = username
			data[1][1] = password
			self.client.sendData(data)
			# Add the handler for the login stage.
			taskMgr.doMethodLater(0.2, self.login_packetReader, 'Update Login')
			return True
		else:
			# client not connected to login/auth server so display message
			self.login.updateStatus("Could not connect to the Login server")
			self.client=False
	
	def create_account(self, username, password):
		# should be similar to attempt_login() but sends 'create_request' rather than 'login_request'
		# similarly need a create_packetReader() task to check for account_created success packet
		# then automatically call attempt_login with the username and password
		pass
	
	def login_packetReader(self, task):
		# setup some sort of timeout checker which will unset the checker variable in attempt_login function so it can go again
		# i think also for the 'db_reply' instead use the hex codes like you were thinking, and have each seperate code like 'already logged' 'wrong password/username' 'whatever else'
		# so on a return of a failure aswell, it will need to stop this task (return task.done)
		temp=self.client.getData()
		if temp!=[]:
			for i in range(len(temp)):
				valid_packet=False
				package=temp[i]
				if len(package)==2:
					print "Received: " + str(package)
					print "Connected to login server"
					# updates warlocks in game
					"""if package[0]=='error':
						print package
						print "User already logged"
						self.login.updateStatus(package[1])
						valid_packet=True
						break"""
					if package[0]=='db_reply':
						print "DB: "+str(package[1])
						self.login.updateStatus(package[1])
						valid_packet=True
					elif package[0]=='login_valid':
						print "Login valid: "+str(package[1])
						self.login.updateStatus(package[1][0])
						print "success: "+str(package[1][1])
						valid_packet=True
						print "I should move to main menu now..."
						taskMgr.doMethodLater(0.3, self.start_mainmenu, 'Start Main Menu')
						return task.done
					"""if not valid_packet:
						data = {}
						data[0] = "error"
						data[1] = "Fail Server"
						self.client.sendData(data)
						print "Bad packet from server"""
				else:
					print "Packet wrong size"
		return task.again
	
	def start_mainmenu(self,task):
		self.login.destroy()
		self.mainmenu=MainMenu(self)
		return task.done
		
	def join_server(self,address):
		# Store connection to lobby and chat i guess eventually
		self.lobby_con=self.client
		# attempt to connect to the game server
		self.client = Client(address, 9099, compress=True)
		if self.client.getConnected():
			print "Connected to server"
			data = {}
			data[0]="username"
			data[1]=self.username # This will end up being the selected server?
			self.client.sendData(data)
			taskMgr.doMethodLater(0.03, self.start_pregame, 'Start Pregame') # I guess this should change to Pregame.
			return True
		else:
			return False
		
	def start_pregame(self,task):
		self.mainmenu.hide()
		self.pregame=Pregame(self)
		return task.done
		
	def begin_preround(self):
		print "Game Starting"
		taskMgr.doMethodLater(0.01, self.start_preround, 'Start Preround')
	
	def start_preround(self,task):
		self.pregame.hide()
		self.preround=Preround(self)
		return task.done
		
	def begin_round(self):
		print "Round Starting"
		taskMgr.doMethodLater(0.01, self.start_round, 'Start Round')
	
	def start_round(self,task):
		self.preround.hide()
		self.round=Round(self)
		return task.done
	
	def quit(self):
		sys.exit()
예제 #36
0
 def test_menu_loop(self, mock_stdout):
     main_menu = MainMenu()
     with mock.patch('builtins.input', side_effect=['s', 'q', 'q']):
         return_value = main_menu.menu_loop()
     self.assertTrue(return_value)
예제 #37
0
파일: main.py 프로젝트: MJ-meo-dmt/Warlocks
	def start_mainmenu(self,task):
		self.prelobby.destroy()
		self.status.destroy()
		self.mainmenu=MainMenu(self)
		return task.done