示例#1
0
class Header(clutter.Box):

    def __init__(self, title):
        super(Header, self).__init__(
            clutter.BinLayout(clutter.BIN_ALIGNMENT_CENTER,
                              clutter.BIN_ALIGNMENT_START,)
            )
        layout = self.get_layout_manager()
        #layout.set_vertical(False)

        # Setup default header elements.
        self.logo = LogoSmall()
        self.title = clutter.Text(settings.HEADER_TITLE_FONT, title)
        self.title.set_color(FONT_COLOR)
        self.credits = Credits()
        layout.add(self.logo,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.title,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.credits,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_START)

    def update(self):
        """
        Update the contents of oneself, specifically the credits information.
        """
        self.credits.update()
    def _credits_option(self):

        fullname = file_path(
            constants.FILES['texts']['menu']['credits']['text'][0],
            constants.TEXTS_DIR)

        if os.access(fullname, os.F_OK) and os.access(fullname, os.R_OK):
            if self.game_opts.verbose:
                print('Go to the credits screen.')

            c = Credits(self.screen,
                        self.game_opts,
                        self.window_frame,
                        self.menu_settings_bg,
                        self.select_option_snd,
                        fullname)

            if not c.run():
                # quit if the close button is
                # pressed (inside the credits)
                self._quit_option()
        else:
            path = os.path.basename(__file__)
            print("{0}: couldn't read text file: {1}".format(path, fullname))
            raise SystemExit
示例#3
0
文件: menu.py 项目: delmoras/tct
    def _credits_option(self):

        # get the path of the filename
        fullname = file_path(
            constants.FILES['texts']['menu']['credits']['text'][0],
            constants.TEXTS_DIR)

        # if credits text file exists and is readable
        if os.access(fullname, os.F_OK) and os.access(fullname, os.R_OK):
            if self.game_opts.verbose:
                print 'Go to the credits screen.'

            # create the credits screen
            c = Credits(self.screen,
                        self.game_opts,
                        self.window_frame,
                        self.menu_settings_bg,
                        self.select_option_snd,
                        fullname)

            # run the credits screen
            if not c.run():
                # quit if the close button is
                # pressed (inside the credits)
                self._quit_option()
        else:
            print ''.join(["Couldn't text file: ", fullname])
示例#4
0
def view_onboarded_users(user_id, session_token, offset=0, limit=20):
    if session_token:
        offset = int(offset)
        limit = int(limit)
        user_id = int(user_id)
        if offset < 0 or limit < 0:
            raise ValueError

        db = database.Database()
        db.logger = current_app.logger
        session_user_id = db.validate_session(session_token)
        if session_user_id == user_id:
            displayed_users = db.list_onboarded_users(session_user_id,
                                                      offset,
                                                      limit)
            user_count = len(displayed_users)
            augmented_user_data = []
            for each_user in displayed_users:
                new_obj = dict(each_user)
                new_obj["email"] = new_obj["email_address"]
                ledger = TransactionLedger(each_user['user_id'], db, current_app.logger)
                user_credits = Credits(each_user['user_id'], db, current_app.logger)
                new_obj['transactions'] = ledger.get_transaction_count()
                new_obj['credits_balance'] = user_credits.get_credit_balance()
                new_obj['owned_tokens'] = ledger.get_owned_token_count()
                augmented_user_data.append(new_obj)
            return render_template("admin/admin_users.jinja2",
                                   session_token=session_token,
                                   users=augmented_user_data,
                                   view_wallet=True,
                                   user_count=user_count,
                                   limit=limit,
                                   offset=offset)
        else:
            abort(403)
示例#5
0
    def postInit(self):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")
示例#6
0
class Header(clutter.Box):
    def __init__(self, title):
        super(Header, self).__init__(
            clutter.BinLayout(
                clutter.BIN_ALIGNMENT_CENTER,
                clutter.BIN_ALIGNMENT_START,
            ))
        layout = self.get_layout_manager()
        #layout.set_vertical(False)

        # Setup default header elements.
        self.logo = LogoSmall()
        self.title = clutter.Text(settings.HEADER_TITLE_FONT, title)
        self.title.set_color(FONT_COLOR)
        self.credits = Credits()
        layout.add(self.logo, clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.title, clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.credits, clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_START)

    def update(self):
        """
        Update the contents of oneself, specifically the credits information.
        """
        self.credits.update()
示例#7
0
class About(QDialog):

    """
    This screen shows the resume of the project
    """

    def __init__(self, parent=None):
        super(About, self).__init__(parent)
        self.setupUi()
        self.connectActions()

        self.parent = parent

    #===================================================================================================================
    def setupUi(self):

        self.ui = Ui_aboutscreen()
        self.ui.setupUi(self)

        icon_path = os.path.join(os.path.dirname(__file__), "../images/tool-animator.png")
        self.ui.lblimageicon.setPixmap(QPixmap(icon_path))
        self.ui.lblimageicon.setMaximumSize(QSize(220, 340))
        self.ui.lblimageicon.setScaledContents(True)

        project_name = ("<b>{} - {}</b>".format(app_name, app_version))
        self.ui.lblprojectname.setText(project_name)

        version_program = ("<b>Python {} - Qt {} - PyQt {}</b>".format(platform.python_version(), QT_VERSION_STR, PYQT_VERSION_STR))
        self.ui.lblversionplateform.setText(version_program)

    #===================================================================================================================
    def connectActions(self):

        """
        Connect actions to the ui file

        """

        self.ui.btncredits.clicked.connect(self.runCredits)

    #===================================================================================================================
    def runCredits(self):

        """
        Run the Credits Dialog

        """

        self.windo = Credits()
        self.windo.exec_()
示例#8
0
def homepage_create_user():
    if request.method == "POST":
        if EMAIL_REGEX.match(request.form['email_address']) is None:
            error = "Invalid e-mail address."
            return render_template("create_user.jinja2", error_msg=error)
        if len(request.form['passwd']) < 8:
            error = "Passwords must consist of at least 8 characters."
            return render_template("create_user.jinja2", error_msg=error)
        if request.form["passwd"] == request.form["passwd_repeat"]:
            ip_addr = request.access_route[-1]
            user_passwd = request.form["passwd"]
            full_name = request.form["full_name"]
            db = Database()
            result = db.create_user(full_name,
                                    request.form['email_address'],
                                    user_passwd,
                                    ip_addr)
            if result:
                if result[0] == -1:
                    error = "User with this e-mail address already exists."
                    return render_template("create_user.jinja2", error_msg=error)
                session_id = result[1]
                # log event
                create_user_event = events.Event("Users Create User",
                                                 db,
                                                 logger=current_app.logger)
                metadata = {"ip_addr": ip_addr, "created_by": "self"}
                create_user_event.log_event(result[0], json.dumps(metadata))

                user_ctx = users.UserContext(result[0], db=db, logger=current_app.logger)
                # default permissions
                user_ctx.add_permission("onboard-users")
                user_ctx.add_permission("launch-ico")
                user_ctx.add_permission("ethereum-network")

                db.update_user_permissions(result[0], user_ctx.acl())

                config_stream = open("config.json", "r")
                config_data = json.load(config_stream)
                config_stream.close()
                if config_data["new_user_tokens"] > 0:
                    cr = Credits(result[0], db, current_app.logger)
                    cr.issue_credits(config_data["new_user_tokens"],
                                     {"ip_addr": ip_addr, "reason": "New User Bonus"})
                return redirect(url_for("admin.admin_main", session_token=session_id))
        else:
            error = "Passwords did not match."
            return render_template("create_user.jinja2", error_msg=error)

    return render_template("create_user.jinja2")
示例#9
0
def admin_tokens(session_token):
    if session_token:
        db = database.Database(logger=current_app.logger)
        user_id = db.validate_session(session_token)
        ctx = UserContext(user_id, db=db, logger=db.logger)
        can_launch_ico = ctx.check_acl("launch-ico")

        erc20_mined = Event("ERC20 Token Mined", db, logger=current_app.logger)
        mined_count = erc20_mined.get_event_count(user_id)
        mined_ids = []

        if mined_count:
            mined_erc20_events = erc20_mined.get_latest_events(mined_count, user_id)
            for each in mined_erc20_events:
                json_data = json.loads(each[0])
                token_id = json_data["token_id"]
                if token_id not in mined_ids:
                    mined_ids.append(token_id)

        if can_launch_ico or len(ctx.acl()["management"]) > 0:
            owned_tokens = []
            for key in ctx.acl()["management"].keys():
                token_id = ctx.acl()["management"][key]["token_id"]
                token_info = db.get_smart_contract_info(token_id)
                owned_tokens.append(token_info)
            owned_tokens.extend(get_owned_tokens(user_id, db, current_app.logger))
            if len(owned_tokens) == 0:
                owned_tokens = None
            email_address = ctx.user_info["email_address"]
            last_logged_in = ctx.user_info["last_logged_in"].isoformat()
            last_logged_in_ip = ctx.user_info["last_logged_in_ip"]
            credit_ctx = Credits(user_id, db, current_app.logger)
            credit_balance = credit_ctx.get_credit_balance()
            if owned_tokens:
                for each in owned_tokens:
                    if each["token_id"] in mined_ids:
                        if each["eth_address"] is None:
                            each["pending"] = True
                        else:
                            each["pending"] = False

            return render_template("admin/admin_tokens.jinja2",
                                   session_token=session_token,
                                   owned_tokens=owned_tokens,
                                   can_launch_ico=can_launch_ico,
                                   email_address=email_address,
                                   last_logged_in=last_logged_in,
                                   last_logged_in_ip=last_logged_in_ip,
                                   credit_balance=credit_balance)
    abort(403)
示例#10
0
def admin_main(session_token, transactions=False):
    db = database.Database(logger=current_app.logger)
    user_id = db.validate_session(session_token)
    if user_id:
        user_ctx = UserContext(user_id, db, current_app.logger)
        launch_ico = user_ctx.check_acl("launch-ico")
        onboard_users = user_ctx.check_acl("onboard-users")
        reset_passwords = user_ctx.check_acl("reset-passwords")
        ethereum_network = user_ctx.check_acl("ethereum-network")
        view_event_log = user_ctx.check_acl("view-event-log")
        issue_credits = user_ctx.check_acl("issue-credits")
        manager = len(user_ctx.acl()["administrator"]) > 0 or len(user_ctx.get_manager_tokens()) > 0
        if user_ctx.user_info["email_address"] == "admin":
            manager = True
        charting = Charting(db, logger=current_app.logger)
        eth_nodes = db.list_ethereum_nodes()

        epoch = datetime.datetime.now() - datetime.timedelta(hours=24)
        node_gas_prices = {}
        moving_average_gas_price_data = charting.get_gas_price_moving_average(start=epoch)
        for node in eth_nodes:
            node_gas_prices[node["node_identifier"]] = charting.get_gas_price_for_node_id(node["id"], start=epoch)

        graphing_metrics = {
            "moving_average": {"gas_price": json.dumps(moving_average_gas_price_data)},
        }

        for each in node_gas_prices.keys():
            graphing_metrics[each] = json.dumps(node_gas_prices[each])

        cr = Credits(user_id, db, current_app.logger)

        return render_template("admin/admin_main.jinja2",
                               full_name=user_ctx.user_info['full_name'],
                               email_address=user_ctx.user_info['email_address'],
                               last_logged_in=user_ctx.user_info['last_logged_in'],
                               credits=cr.get_credit_balance(),
                               session_token=session_token,
                               launch_ico=launch_ico,
                               onboard_users=onboard_users,
                               reset_passwords=reset_passwords,
                               ethereum_network=ethereum_network,
                               view_event_log=view_event_log,
                               issue_credits=issue_credits,
                               manager=manager,
                               metrics=graphing_metrics,
                               user_id=user_id)
    else:
        return render_template("admin/admin_login.jinja2", error="Invalid session.")
示例#11
0
    def __init__(self):
        super(FrontScreen, self).__init__(
            clutter.BinLayout(clutter.BIN_ALIGNMENT_CENTER,
                              clutter.BIN_ALIGNMENT_CENTER)
            )
        layout = self.get_layout_manager()

        self.credits = Credits()
        layout.add(self.credits,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_END)

        self.right_arrow = RightArrow()
        layout.add(self.right_arrow,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)

        self.boxed_contents = clutter.Box(clutter.BoxLayout())
        box_layout = self.boxed_contents.get_layout_manager()
        box_layout.set_use_animations(True)
        box_layout.set_vertical(True)
        box_layout.set_spacing(100)

        self.header = LogoLarge()
        box_layout.pack(self.header, True, False, False,
                        clutter.BOX_ALIGNMENT_CENTER,
                        clutter.BOX_ALIGNMENT_CENTER)

        self.labels = (
            clutter.Text(settings.FRONT_SCREEN_FONT, 'songs'),
            clutter.Text(settings.FRONT_SCREEN_FONT, 'artists'),
            )

        self.selected = self.labels[0]

        for label in self.labels:
            label.set_color(FONT_COLOR)
            label.set_opacity(FONT_OPACITY)
            label.set_property('scale-gravity', clutter.GRAVITY_CENTER)
            box_layout.pack(label, True, False, False,
                            clutter.BOX_ALIGNMENT_CENTER,
                            clutter.BOX_ALIGNMENT_CENTER)

        layout.add(self.boxed_contents,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.highlight(self.selected)
示例#12
0
    def postInit(self):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")
示例#13
0
    def main(self, screen):
        pygame.mixer.init()
        clock = pygame.time.Clock()
        background = load_image('menu_background.png')
        music = load_sound('music_credits.ogg')
        menu = kezmenu.KezMenu(
            ['Engage', lambda: Quantum().mainLoop(40)],
            ['Enlighten', lambda: Tutorial().mainLoop(40)],
            ['Archive', lambda: Highscore().mainLoop(40)],
            ['Collaborating Minds', lambda: Credits().mainLoop(40)],
            ['Abort', lambda: setattr(self, 'running', False)],
        )
        menu.x = 10
        menu.y = 10
        menu.enableEffect('raise-col-padding-on-focus', enlarge_time=0.1)
        menu.color = (0, 0, 255)
        menu.focus_color = (174, 23, 92)
        menu.font = load_font('adelle.ttf', 20)

        music.play(-1)

        while self.running:
            menu.update(pygame.event.get(), clock.tick(30) / 1000.)
            screen.blit(background, (0, 0))
            menu.draw(screen)
            pygame.display.flip()
示例#14
0
def create_main_menu():
    global main_menu, scores_menu, saves_menu

    # Main menu
    main_menu = pygame_menu.Menu(300, 300, 'Deadline', theme=fd_theme)

    # Table of SCORES
    scores_menu = Scores(int(window_width / 1.3), int(window_height / 1.3),
                         fd_theme)
    scores_menu.menu.set_onclose(create_main_menu)

    # Table of SAVES
    saves_menu = Saves(int(window_width / 1.3), int(window_height / 1.3),
                       start_game, fd_theme)

    main_menu.add_button('Play', start_game)
    main_menu.add_button('Scores', scores_menu.menu)
    main_menu.add_button('Saves', saves_menu.menu)
    credit_list = [
        "Deadline - Fire Maze", " ", " Menues", "Timofey Katkov", " ",
        "Game play", "Daniil Nesterenko", "Timofey Katkov", " ", "Maze",
        "Daniil Nesterenko"
        " ", " ", "Music", "Timofey Katkov, EROZZION Music", " ",
        "P.S. : inspired by all deadlines and fire dungeons",
        "Thanks for playing"
    ]
    c = Credits(credit_list, surface, 'Sigma Five.otf')
    main_menu.add_button('About', c.main)
    main_menu.add_button('Quit', pygame_menu.events.EXIT)
示例#15
0
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)
示例#16
0
    def creDits(self):

        """
        run the Credits dialog

        """
        self.windo = Credits()
        self.windo.show()
示例#17
0
    def runCredits(self):

        """
        Run the Credits Dialog

        """

        self.windo = Credits()
        self.windo.exec_()
示例#18
0
def erc20_publish():
    session_token = request.form["session_token"]
    token_id_form_field = request.form["token_id"]
    confirmation = request.form["confirmation"]
    db = database.Database()
    user_id = db.validate_session(session_token)
    if user_id:
        token_id = int(token_id_form_field)
        if token_id < 1:
            raise ValueError
        sc = SmartContract(smart_token_id=token_id)
        if sc.smart_contract_id < 1:
            abort(404)
        if confirmation == "true":
            credits = Credits(user_id, db, current_app.logger)
            current_balance = credits.get_credit_balance()
            if current_balance < credits.erc20_publish_price:
                message = "Your credit balance of <span class=\"credit_balance\">"
                message += str(current_balance) + "</span> is less than the <span class=\"credit_price\">"
                message += str(credits.erc20_publish_price) + "</span> required to publish an ERC20 token."
                message += "<p>[ <a class=\"login_anchor\" href=\"/admin/credits/purchase/"
                message += session_token + "\">purchase credits</a> ]</p>"
                return render_template("admin/admin_confirmation.jinja2",
                                       title="Unable to publice ERC20 contract",
                                       session_token=session_token,
                                       confirmation_value=token_id,
                                       confirmation_title="Insufficient Credits",
                                       confirmation_type="insufficient_credits",
                                       confirmation_message=message,
                                       default_choice="Cancel")
            message = "Are you sure you want to publish <em>" + sc.token_name + "</em> permanently to the Ethereum "
            message += "blockchain, costing <span class=\"credit_price\">"
            message += str(credits.erc20_publish_price) + "</span> credits?"
            return render_template("admin/admin_confirmation.jinja2",
                                   title="Confirm",
                                   session_token=session_token,
                                   confirmation_value=token_id,
                                   confirmation_title="Publish ERC20 contract?",
                                   confirmation_message=message,
                                   confirmation_type="erc20_publish",
                                   choices=["Cancel"],
                                   default_choice="Publish")
示例#19
0
    def __init__(self, title):
        super(Header, self).__init__(
            clutter.BinLayout(
                clutter.BIN_ALIGNMENT_CENTER,
                clutter.BIN_ALIGNMENT_START,
            ))
        layout = self.get_layout_manager()
        #layout.set_vertical(False)

        # Setup default header elements.
        self.logo = LogoSmall()
        self.title = clutter.Text(settings.HEADER_TITLE_FONT, title)
        self.title.set_color(FONT_COLOR)
        self.credits = Credits()
        layout.add(self.logo, clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.title, clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.credits, clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_START)
示例#20
0
def view_users(session_token, offset=0, limit=20):
    if session_token:
        offset = int(offset)
        limit = int(limit)
        if offset < 0 or limit < 0:
            raise ValueError
        db = database.Database()
        db.logger = current_app.logger
        user_id = db.validate_session(session_token)
        if user_id:
            user_ctx = UserContext(user_id, db, current_app.logger)
            user_data = db.list_users(offset, limit)
            user_count = db.get_user_count()
            can_reset_password = user_ctx.check_acl("reset-passwords")
            can_change_permissions = user_ctx.check_acl("change-permissions")
            can_issue_credits = user_ctx.check_acl("issue-credits")
            can_view_wallet = user_ctx.check_acl("assign-tokens") or user_ctx.check_acl("remove-tokens")

            augmented_user_data = []
            for each_user in user_data:
                new_obj = dict(each_user)
                ledger = TransactionLedger(each_user['user_id'], db, current_app.logger)
                user_credits = Credits(each_user['user_id'], db, current_app.logger)
                new_obj['transactions'] = ledger.get_transaction_count()
                new_obj['credits_balance'] = user_credits.get_credit_balance()
                new_obj['owned_tokens'] = ledger.get_owned_token_count()
                augmented_user_data.append(new_obj)
            return render_template("admin/admin_users.jinja2",
                                   session_token=session_token,
                                   users=augmented_user_data,
                                   reset_password=can_reset_password,
                                   change_permissions=can_change_permissions,
                                   issue_credits=can_issue_credits,
                                   view_wallet=can_view_wallet,
                                   user_count=user_count,
                                   limit=limit,
                                   offset=offset)
示例#21
0
    def _credits_option(self):

        # get the path of the filename
        fullname = file_path(
            constants.FILES['texts']['menu']['credits']['text'][0],
            constants.TEXTS_DIR)

        # if credits text file exists and is readable
        if os.access(fullname, os.F_OK) and os.access(fullname, os.R_OK):
            if self.game_opts.verbose:
                print('Go to the credits screen.')

            # create the credits screen
            c = Credits(self.screen, self.game_opts, self.window_frame,
                        self.menu_settings_bg, self.select_option_snd,
                        fullname)

            # run the credits screen
            if not c.run():
                # quit if the close button is
                # pressed (inside the credits)
                self._quit_option()
        else:
            print((' '.join(("Couldn't read text file:", fullname))))
示例#22
0
    def __init__(self, title):
        super(Header, self).__init__(
            clutter.BinLayout(clutter.BIN_ALIGNMENT_CENTER,
                              clutter.BIN_ALIGNMENT_START,)
            )
        layout = self.get_layout_manager()
        #layout.set_vertical(False)

        # Setup default header elements.
        self.logo = LogoSmall()
        self.title = clutter.Text(settings.HEADER_TITLE_FONT, title)
        self.title.set_color(FONT_COLOR)
        self.credits = Credits()
        layout.add(self.logo,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.title,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)
        layout.add(self.credits,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_START)
示例#23
0
 def display_credits(self):
     self.button_back.display()
     Credits.display()
示例#24
0
class FrontScreen(Screen):

    def __init__(self):
        super(FrontScreen, self).__init__(
            clutter.BinLayout(clutter.BIN_ALIGNMENT_CENTER,
                              clutter.BIN_ALIGNMENT_CENTER)
            )
        layout = self.get_layout_manager()

        self.credits = Credits()
        layout.add(self.credits,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_END)

        self.right_arrow = RightArrow()
        layout.add(self.right_arrow,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)

        self.boxed_contents = clutter.Box(clutter.BoxLayout())
        box_layout = self.boxed_contents.get_layout_manager()
        box_layout.set_use_animations(True)
        box_layout.set_vertical(True)
        box_layout.set_spacing(100)

        self.header = LogoLarge()
        box_layout.pack(self.header, True, False, False,
                        clutter.BOX_ALIGNMENT_CENTER,
                        clutter.BOX_ALIGNMENT_CENTER)

        self.labels = (
            clutter.Text(settings.FRONT_SCREEN_FONT, 'songs'),
            clutter.Text(settings.FRONT_SCREEN_FONT, 'artists'),
            )

        self.selected = self.labels[0]

        for label in self.labels:
            label.set_color(FONT_COLOR)
            label.set_opacity(FONT_OPACITY)
            label.set_property('scale-gravity', clutter.GRAVITY_CENTER)
            box_layout.pack(label, True, False, False,
                            clutter.BOX_ALIGNMENT_CENTER,
                            clutter.BOX_ALIGNMENT_CENTER)

        layout.add(self.boxed_contents,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.highlight(self.selected)

    def on_timeline_completed(self, timeline, behaviour):
        """
        """
        behaviour.remove_all()

    def get_selected(self):
        """
        """
        return self.selected.get_text()

    def highlight(self, actor):
        """
        """
        actor.animate(clutter.LINEAR, HIGHLIGHT_RATE,
                      "opacity", 255,
                      "scale-x", 1.3,
                      "scale-y", 1.3,
                      )

    def blink(self, actor):
        animation = actor.animate(clutter.LINEAR, BLINK_RATE,
                                  'color', clutter.Color(255, 0, 0, 255))
        animation.connect_after('completed', self.on_blink_completed, actor)
        #animation.set_loop(True)

    def unhighlight(self, actor):
        """
        """
        actor.animate(clutter.LINEAR, HIGHLIGHT_RATE,
                      "scale-x", 1,
                      "scale-y", 1,
                      "opacity", FONT_OPACITY,
                      )

    def on_blink_completed(self, animation, actor):
        if actor.get_color() == clutter.Color(255, 0, 0, 255):
            animation = actor.animate(clutter.LINEAR, BLINK_RATE,
                                       'color', clutter.Color(0, 255, 0, 255))
        elif actor.get_color() == clutter.Color(0, 255, 0, 255):
            animation = actor.animate(clutter.LINEAR, BLINK_RATE,
                                       'color', clutter.Color(0, 0, 255, 255))
        elif actor.get_color() == clutter.Color(0, 0, 255, 255):
            animation = actor.animate(clutter.LINEAR, BLINK_RATE,
                                       'color', clutter.Color(255, 0, 0, 255))

        animation.connect_after('completed', self.on_blink_completed, actor)

    def on_press(self, actor, event):
        """
        Keyboard button press callback.
        """
        if event.keyval == clutter.keysyms.Up:
            index = self.labels.index(self.selected)
            if index > 0:
                self.unhighlight(self.selected)
                self.selected = self.labels[index - 1]
                self.highlight(self.selected)

        elif event.keyval == clutter.keysyms.Down:
            index = self.labels.index(self.selected)
            if index < len(self.labels) - 1:
                self.unhighlight(self.selected)
                self.selected = self.labels[index + 1]
                self.highlight(self.selected)

        elif event.keyval == clutter.keysyms.Right:
            if self.selected.get_text() == 'songs':
                self.get_parent().new_screen(SongListScreen())
            elif self.selected.get_text() == 'artists':
                self.get_parent().new_screen(ArtistListScreen())

    def update(self):
        """
        Update the contents of oneself, specifically the credits information.
        """
        self.credits.update()
示例#25
0
	def menu(self, screen):
		pygame.mixer.music.play()
		Beaten.level1 = False
		Beaten.level2 = False
		Beaten.level3 = False
		Beaten.level4 = False
		Options.boyleft = True
		Options.boyright = False
		Options.girlleft = False
		Options.girlright = True
		Options.soundon = True
		Options.name1 = ""
		Options.name1true = False
		Options.name2 = ""
		Options.name2true = False
		state = 0
		fonts = pygame.font.get_fonts()
		firstfont = pygame.font.SysFont("Default",65)
		secondfont = pygame.font.SysFont("Default",65)
		thirdfont = pygame.font.SysFont("Default",45)
		fourthfont = pygame.font.SysFont("Default",45)
		fifthfont = pygame.font.SysFont("Default",48)
		setting_font = "OPTIONS"
		how_font = "HOW TO"
		play_font = "PLAY"
		quit_font = "QUIT"
		credit_font = "CREDITS"
		quit_write = firstfont.render(quit_font, 1, [255,255,255])
		play_write = secondfont.render(play_font,1,[255,255,255])
		how_write1 = thirdfont.render(how_font,1,[255,255,255])
		how_write2 = thirdfont.render(play_font,1,[255,255,255])
		setting_write = fourthfont.render(setting_font,1,[255,255,255])
		credit_write = fifthfont.render(credit_font,1,[255,255,255])
		while state == 0:
			if Options.soundon == False:
				pygame.mixer.music.stop()
			mpos = pygame.mouse.get_pos()
			screen.blit(hi, (0,0))
			screen.blit(instruct,(185,5))
			screen.blit(box,(100,200))
			screen.blit(box1,(450,200))
			screen.blit(box2,(800,200))
			screen.blit(box3,(280,420))
			screen.blit(box4,(630,420))
			screen.blit(quit_write,(675,468))
			screen.blit(play_write,(145,248))
			screen.blit(how_write1,(490,235))
			screen.blit(how_write2,(515,275))
			screen.blit(setting_write,(832,253))
			screen.blit(credit_write,(307,472))
			for event in pygame.event.get():
				if event.type == QUIT:
					pygame.quit()
				keys = pygame.key.get_pressed()
				if keys[pygame.K_b]:
					Beaten.level1 = True
					Beaten.level2 = True
					Beaten.level3 = True
					Beaten.level4 = True
				if((mpos[0]<452 and mpos[0]>295) and (mpos[1]<532 and mpos[1]>439)):
					fifthfont.set_italic(True)
					credit_write = fifthfont.render(credit_font,1,[255,0,0])
					if event.type == MOUSEBUTTONDOWN:
						Credits().run(screen)
				else:
					fifthfont.set_italic(False)
					credit_write = fifthfont.render(credit_font,1,[255,255,255])

				if (mpos[0]<837 and mpos[0]>630) and (mpos[1]<567 and mpos[1]>420):
					firstfont.set_italic(True)
					quit_write = firstfont.render(quit_font,1,[255,0,0])
					if event.type == MOUSEBUTTONDOWN:
						pygame.quit()
				else:
					firstfont.set_italic(False)
					quit_write = firstfont.render(quit_font,1,[255,255,255])
				if(mpos[0]<307 and mpos[0]>100) and (mpos[1]<347 and mpos[1]>200):
					secondfont.set_italic(True)
					play_write = secondfont.render(play_font,1,[255,0,0])
					if event.type == MOUSEBUTTONDOWN:
						#pygame.mixer.music.load("click_one.ogg")
						#pygame.mixer.music.play()
						LevelSelection().run(screen)
				else:
					secondfont.set_italic(False)
					play_write = secondfont.render(play_font,1,[255,255,255])
				if(mpos[0]<657 and mpos[0]>450) and (mpos[1]<347 and mpos[1]>200):
					thirdfont.set_italic(True)
					how_write1 = thirdfont.render(how_font,1,[255,0,0])
					how_write2 = thirdfont.render(play_font,1,[255,0,0])
					if event.type == MOUSEBUTTONDOWN:
						#pygame.mixer.music.load("click_one.ogg")
						#pygame.mixer.music.play()
						HowtoPlay().run(screen)
				else:
					thirdfont.set_italic(False)
					how_write1 = thirdfont.render(how_font,1,[255,255,255])
					how_write2 = thirdfont.render(play_font,1,[255,255,255])
				if(mpos[0]<1007 and mpos[0]>800) and (mpos[1]<347 and mpos[1]>200):
					fourthfont.set_italic(True)
					setting_write = fourthfont.render(setting_font,1,[255,0,0])
					if event.type == MOUSEBUTTONDOWN:
						#pygame.mixer.music.load("click_one.ogg")
						#pygame.mixer.music.play()
						Settings().run(screen)
				else:
					fourthfont.set_italic(False)
					setting_write = fourthfont.render(setting_font,1,[255,255,255])

			pygame.display.flip()
示例#26
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set background color to black
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()

        #
        # 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()
        # check if particles should be enabled
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()
        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            # 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)
        elif base.appRunner:
            # As when the application is started as appRunner instance
            # it doesn't respect our loadPrcFile configurations specific
            # to the window, hence we need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                #TODO: Check for all window specific variables like
                #      fullscreen, screen size, title and window
                #      decoration that you have in your configuration
                #      and set them by your own.
                if mainConfig.getVariableName(dec) == "fullscreen":
                    if not mainConfig.getDeclaration(dec).getBoolWord(0): break
                    # 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)
                    break

        # 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):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Start", self.request, ["CharSelection"])
        self.accept("Menu-Credits", self.request, ["Credits"])
        self.accept("Menu-Quit", self.quit)
        self.ignore("KoScreen-Back")
        self.koScreen.hide()
        self.menu.show()
        if self.menuMusic.status() != AudioSound.PLAYING:
            self.menuMusic.play()
        if self.fightMusic.status() == AudioSound.PLAYING:
            self.fightMusic.stop()

    def exitMenu(self):
        self.ignore("Menu-Start")
        self.ignore("Menu-Credits")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterCredits(self):
        self.accept("Credits-Back", self.request, ["Menu"])
        self.koScreen.hide()
        self.credits.show()

    def exitCredits(self):
        self.ignore("Credits-Back")
        self.credits.hide()

    def enterCharSelection(self):
        self.accept("CharSelection-Back", self.request, ["Menu"])
        self.accept("CharSelection-Start", self.request, ["LevelSelection"])
        self.charSelection.show()

    def exitCharSelection(self):
        self.ignore("CharSelection-Start")
        self.ignore("CharSelection-Back")
        self.charSelection.hide()
        self.selectedChar1 = self.charSelection.selectedCharacter1
        self.selectedChar2 = self.charSelection.selectedCharacter2

    def enterLevelSelection(self):
        self.accept("LevelSelection-Back", self.request, ["CharSelection"])
        self.accept("LevelSelection-Start", self.request, ["Game"])
        self.levelSelection.show()

    def exitLevelSelection(self):
        self.ignore("LevelSelection-Start")
        self.ignore("LevelSelection-Back")
        self.levelSelection.hide()

    def enterGame(self):
        # main game code should be called here
        self.arena = Arena(self.levelSelection.selectedLevel)
        self.arena.start()
        self.camera.setPos(0, -5, 1.25)
        self.player = Player(0, self.selectedChar1, "p1")
        self.player2 = Player(1, self.selectedChar2, "p2")
        self.player.setEnemy(self.player2.collisionNodeName)
        self.player2.setEnemy(self.player.collisionNodeName)
        self.player.start(self.arena.getStartPos(1))
        self.player2.start(self.arena.getStartPos(2))
        self.taskMgr.add(self.updateWorldCam, "world camera update task")
        self.accept("gameOver", self.gameOver)
        self.hud.show()

        def lifeChanged(charId, health):
            base.messenger.send("hud_setLifeBarValue", [charId, health])

        self.accept("lifeChanged", lifeChanged)
        hide_cursor()
        if self.fightMusic.status() != AudioSound.PLAYING:
            self.fightMusic.play()
        if self.menuMusic.status() == AudioSound.PLAYING:
            self.menuMusic.stop()

    def exitGame(self):
        # cleanup for game code
        self.taskMgr.remove("world camera update task")
        self.player.stop()
        self.player2.stop()
        del self.player
        del self.player2
        self.arena.stop()
        self.ignore("gameOver")
        self.ignore("lifeChanged")
        self.hud.hide()

    #
    # FSM PART END
    #

    #
    # BASIC FUNCTIONS
    #
    def gameOver(self, LoosingCharId):
        show_cursor()
        winningChar = 1
        if LoosingCharId == 0:
            winningChar = 2
        self.accept("KoScreen-Back", self.request, ["Credits"])
        self.koScreen.show(winningChar)

    def updateWorldCam(self, task):
        playerVec = self.player.getPos() - self.player2.getPos()
        playerDist = playerVec.length()
        x = self.player.getX() + playerDist / 2.0
        self.camera.setX(x)

        zoomout = False
        if not self.cam.node().isInView(self.player.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not self.cam.node().isInView(self.player2.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not zoomout:
            if self.camera.getY() < -5:
                camPosUpdate = 2 * globalClock.getDt()
                self.camera.setY(self.camera, camPosUpdate)
        return task.cont

    def __escape(self):
        if self.state == "Menu":
            self.quit()
        elif self.state == "LevelSelection":
            self.request("CharSelection")
        else:
            self.request("Menu")

    def quit(self):
        """This function will stop the application"""
        self.userExit()

    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

        #TODO: get values of configurations here
        particles = "#f" if not base.particleMgrEnabled else "#t"
        volume = str(round(base.musicManager.getVolume(), 2))
        mute = "#f" if base.AppHasAudioFocus else "#t"
        #TODO: add any configuration variable name that you have added
        customConfigVariables = [
            "", "particles-enabled", "audio-mute", "audio-volume"
        ]
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(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: particles-enabled and audio-mute are custom variables and
            #       have to be loaded by hand at startup
            # Particles
            page.makeDeclaration("particles-enabled", particles)
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", mute)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("%s Pandaconfig" % appName)
            # 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")
            # particles
            page.makeDeclaration("particles-enabled", "#t")
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", "#f")
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
示例#27
0
class PreFerences(QDialog):
    def __init__(self, parent=None):
        super(PreFerences, self).__init__()

        self.parent = parent

        self.setupUi()
        self.connectActions()
        self.updateUi()

        QTimer.singleShot(0, self.loadSettings)
        # QTimer.singleShot(1000, self.dvgrabPath)

        format_capture = ["Dv Raw (.dv)", "DV 2 (.avi)", "Dv (.avi)", "Hdv (.m2t)", "Mpeg 2 (.mpg)", "Mov (.mov)"]
        for format in format_capture:
            self.ui.cmbformatcapture.addItem(format)
            self.ui.cmbformatcapture.setCurrentIndex(0)

        # populate the dvgrab path
        dvgrab_path = shutil.which("dvgrab")
        if dvgrab_path is not None:
            self.ui.lnedvgrab.setText(dvgrab_path)
        else:
            QMessageBox.information(self, self.tr("QDvGrab"), self.tr("Dvgrab is not installed"))

        # populate the transcode path
        transcode_path = shutil.which("transcode")
        if transcode_path is not None:
            self.ui.lnetranscode.setText(transcode_path)
        else:
            QMessageBox.information(self, self.tr("QDvGrab"), self.tr("Transcode is not installed"))

    # ===================================================================================================================
    def setupUi(self):

        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        # Set Tooltips for preferences
        self.ui.cmblanguages.setToolTip(self.tr(" Change languages here "))
        self.ui.btnchoosefile.setToolTip(self.tr(" Choose here another directory other than this one by default "))
        self.ui.btndvgrab.setToolTip(
            self.tr(" Choose here another path other than this one by default if this one has failed ")
        )
        self.ui.btntranscode.setToolTip(
            self.tr(" Choose here another path other than this one by default if this one has failed ")
        )
        self.ui.btncredits.setToolTip(self.tr(" Set the Credits Screen "))
        self.ui.cmbformatcapture.setToolTip(self.tr(" Select another format than this one by default"))
        self.ui.chknone.setToolTip(self.tr(" Select no conversion when acquisition is done "))
        self.ui.chkdvraw.setToolTip(self.tr(" Select Raw conversion when acquisition is done "))
        self.ui.chkdv2.setToolTip(self.tr(" Select Dv2 conversion when acquisition is done "))
        self.ui.chkhdv.setToolTip(self.tr(" Select Dv conversion when acquisition is done "))
        self.ui.chkdetection.setToolTip(self.tr(" Select only file when acquisition is done "))
        self.ui.chkautomatic.setToolTip(self.tr(" Set several files following hour and date when acquisition is done "))
        self.ui.chkscene.setToolTip(self.tr(" Creation of a scene when acquisition is done "))
        self.ui.chkautomaticrecord.setToolTip(self.tr("  Stop acquisition if not enought free space disk "))
        self.ui.chkmanualrecord.setToolTip(self.tr(" Planning the time of acquisition "))
        self.ui.chkactivepreview.setToolTip(self.tr(" See in real time when acquisition is done "))

    # ===================================================================================================================
    def connectActions(self):

        """
        connection of all events
        """
        self.ui.btncredits.clicked.connect(self.creDits)
        self.ui.btndvgrab.clicked.connect(self.dvgrabPath)
        self.ui.btntranscode.clicked.connect(self.transcodePath)
        self.ui.btnchoosefile.clicked.connect(self.outputPath)
        self.ui.cmblanguages.currentIndexChanged.connect(self.languageSelected)
        self.ui.cmbformatcapture.currentIndexChanged.connect(self.chooseFormatCapture)
        self.ui.chknone.toggled.connect(self.chooseAutomaticConversion)
        self.ui.chkdvraw.toggled.connect(self.chooseAutomaticConversion)
        self.ui.chkdv2.toggled.connect(self.chooseAutomaticConversion)
        self.ui.chkhdv.toggled.connect(self.chooseAutomaticConversion)
        self.ui.chkdetection.toggled.connect(self.chooseDetectionScene)
        self.ui.chkautomatic.toggled.connect(self.chooseDetectionScene)
        self.ui.chkscene.toggled.connect(self.chooseDetectionScene)
        self.ui.spbscene.valueChanged.connect(self.chooseDetectionScene)
        self.ui.chkautomaticrecord.toggled.connect(self.captureExtraParameters)
        self.ui.chkmanualrecord.toggled.connect(self.captureExtraParameters)
        self.ui.lnehours.textChanged.connect(self.captureExtraParameters)
        self.ui.lneminutes.textChanged.connect(self.captureExtraParameters)
        self.ui.chkactivepreview.toggled.connect(self.runActivePreview)

    # ===================================================================================================================
    def updateUi(self):

        """
        Update the ui and desactive all widgets that we don't need for the moment

        """
        self.ui.lbltranscode.setEnabled(False)
        self.ui.lnetranscode.setEnabled(False)
        self.ui.btntranscode.setEnabled(False)
        self.ui.chkactivepreview.setVisible(True)
        self.ui.chknone.setChecked(True)
        self.ui.chkdetection.setChecked(True)
        self.ui.chkautomaticrecord.setChecked(True)
        self.ui.lneoutputfile.setText("My Awesome Movie")
        self.ui.lneoutputfile.setFocus()
        self.ui.lneoutputfile.selectAll()

        # 3 tab
        self.ui.chkmanualrecord.setEnabled(False)
        self.ui.lnehours.setEnabled(False)
        self.ui.lneminutes.setEnabled(False)
        self.ui.label_4.setEnabled(False)
        self.ui.label_5.setEnabled(False)
        self.ui.chkactivepreview.setEnabled(False)

        # 2 tab
        self.ui.chkautomatic.setEnabled(False)
        self.ui.chkscene.setEnabled(False)
        self.ui.spbscene.setEnabled(False)
        self.ui.label_3.setEnabled(False)

        self.ui.chkdvraw.setEnabled(False)
        self.ui.chkdv2.setEnabled(False)
        self.ui.chkhdv.setEnabled(False)

    # ===================================================================================================================
    def creDits(self):

        """
        run the Credits dialog

        """
        self.windo = Credits()
        self.windo.show()

    # ===================================================================================================================
    def dvgrabPath(self):

        """
        Display the new path of dvgrab if he is not displayed by default

        """

        # select this folder by default when the QFileDialog is opened
        direct_repository = "/usr/bin"
        base_repository = QDir(direct_repository).absolutePath()

        new_dvgrab_path = QFileDialog.getOpenFileName(
            self, self.tr("QdvGrab - Choose a different path "), (QDir.rootPath() + base_repository)
        )

        if new_dvgrab_path is not None:
            new_dvgrab_path = ""
            # clear the lineedit
            self.ui.lnedvgrab.clear()
            result = QDir(new_dvgrab_path).absolutePath()
            # result = self.ui.lnedvgrab.text(base_repository)
            self.ui.lnedvgrab.setText(result)

    # ===================================================================================================================
    def transcodePath(self):

        """
        Display the new path of transcode if he is not displayed by default

        """

        # select this folder by default when the QFileDialog is opened
        direct_repository = "/usr/bin"
        base_repository = QDir(direct_repository).absolutePath()

        new_transcode_path = QFileDialog.getOpenFileName(
            self, self.tr("QdvGrab - Choose a different path"), (QDir.rootPath() + base_repository)
        )

        if new_transcode_path is not None:
            new_transcode_path = ""
            # clear the lineedit
            self.ui.lnetranscode.clear()
            result = QDir(new_transcode_path).absolutePath()
            self.ui.lnetranscode.setText(result)

    # ===================================================================================================================
    def outputPath(self):

        """
        Display the output path by default and after this one choose by the user

        """
        new_output_path = QFileDialog.getExistingDirectory(
            self, self.tr("QDvGab - Open a Directory"), os.path.join(QDir.homePath() + "/Videos/")
        )
        new_output_path = str(self.ui.lneoutputfile.text())

        if new_output_path:
            self.ui.lneoutputfile.setText(new_output_path)

    # ===================================================================================================================
    def languageSelected(self, value):
        """
        Display the language by default and if not or if the user would like to change it do it here without changing
        this one of his desktop

        """
        pass

    # ===================================================================================================================
    def chooseFormatCapture(self):

        """
        Choose the capture format i.e either dv format or hdv format. And the main interface change thanks to this choice

        """

        pass

    # ===================================================================================================================
    def loadSettings(self):

        """
        Here we load user settings and if none a basic config by default is loaded

        """

        settings = QSettings()

        language = settings.value("language", type=str)

        new_output_path = settings.value("new_output_path", type=str)
        name_camcorder = settings.value("name_camcorder", type=str)

        formats_choose = settings.value("formats_choose", True, type=str)
        automatic_conversion = settings.value("automatic_conversion", True, type=bool)
        detection_scene = settings.value("detection_scene", True, type=bool)

        automatic_record = settings.value("automatic_record", True, type=bool)

        if language:
            value = self.ui.cmblanguages.addItem(language)
            self.ui.cmblanguages.setCurrentText(value)
        else:
            self.ui.cmblanguages.setCurrentText(language)
        if new_output_path:
            self.ui.lneoutputfile.setText(new_output_path)
        if name_camcorder:
            self.ui.lnenamecamcorder.setText(name_camcorder)
        if formats_choose:
            format = self.ui.cmbformatcapture.addItem(formats_choose)
            self.ui.cmbformatcapture.setCurrentText(format)
        else:
            self.ui.cmbformatcapture.setCurrentText(formats_choose)
        if automatic_conversion:
            self.ui.chknone.setChecked(True)
        if detection_scene:
            self.ui.chkdetection.setChecked(True)
        if automatic_record:
            self.ui.chkautomaticrecord.setChecked(True)

    # ===================================================================================================================
    def saveSettings(self):

        """
        Here we save users setting when the application is closed and if none a basic config by default is loaded

        """

        # MainWindowSettings
        language = QLocale.system().name()

        # GeneralSettings
        new_output_path = os.path.join(QDir.homePath() + "/Videos/")
        name_camcorder = self.ui.lnenamecamecorder.text()
        formats_choose = self.ui.cmbformatcapture.setCurrentIndex()

        # ConversionSettings
        automatic_conversion = self.ui.chknone.isChecked()
        detection_scene = self.ui.chkdetection.isChecked()

        # CaptureSettings
        automatic_record = self.ui.chkautomaticrecord.isChecked()

        settings = QSettings(QSettings.SystemScope, "eCreate", "qdvgrab")

        # settings.beginGroup('MainWindowSettings')
        # settings.setValue()
        # settings.setValue()
        # settings.endGroup()

        settings.beginGroup("GeneralSettings")
        settings.setValue("language", language)
        settings.setValue("new_output_path", new_output_path)
        settings.setValue("name_camcorder", name_camcorder)
        settings.endGroup()

        settings.beginGroup("ConversionSettings")
        settings.setValue("formats_choose", formats_choose)
        settings.setValue("automatic_conversion", automatic_conversion)
        settings.setValue("detection_scene", detection_scene)
        settings.endGroup()

        settings.beginGroup("CaptureSettings")
        settings.setValue("automatic_record", automatic_record)
        settings.endGroup()

    # ===================================================================================================================
    def chooseAutomaticConversion(self):

        """
        Several choices if the user would like to get directly his file in mpeg2 (not passing by a conversion tool after
        grabbing his film

        """
        pass

    # ===================================================================================================================
    def chooseDetectionScene(self):

        """
        The user can choose if he would like one file or severals

        """
        pass

    # ===================================================================================================================
    def runActivePreview(self):

        """
        the user can run the active preview here

        """
        pass

    # ===================================================================================================================
    def captureExtraParameters(self):

        """
        The user can choose several parameters that he can't do anywhere like:
        - stop the grab if not enought space disks
        - program a time for the grab i.e for 50 minutes

        """
        pass
示例#28
0
    def handle_events(self):

        keep_going = True
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keep_going = False
            elif self.in_prompt:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    button_pressed = event.dict['button']
                    mouse_pos = event.dict['pos']
                    clicked_obj = self.prompt.check_collisions(mouse_pos)
                    if button_pressed == 1:
                        if isinstance(clicked_obj, Button):
                            if clicked_obj.action is "okay":
                                self.in_prompt = False
                            elif clicked_obj.action is "exit":
                                keep_going = False
                            elif clicked_obj.action is "restart":
                                keep_going = False
                                __main__.main()
                            elif clicked_obj.action is "artifact":
                                self.in_prompt = False
                                self.user.members[0].abilities += [LastHope()]
                            elif clicked_obj.action is "credits":
                                keep_going = False
                                credits = Credits()
                                credits.run()
                elif event.type == pygame.KEYDOWN:
                    key_pressed = event.dict['key'] % 256
                    self.prompt.handle_keydown(key_pressed)

            elif event.type == pygame.KEYDOWN:
                key_pressed = event.dict['key'] % 256
                if key_pressed == pygame.K_a:
                    self.dx += -Campaign.USER_SPEED
                elif key_pressed == pygame.K_d:
                    self.dx += Campaign.USER_SPEED
                elif key_pressed == pygame.K_w:
                    self.dy += -Campaign.USER_SPEED
                elif key_pressed == pygame.K_s:
                    self.dy += Campaign.USER_SPEED
                elif key_pressed == pygame.K_ESCAPE:
                    if self.fullscreen:
                        self.fullscreen = False
                        self.init_screen()
                        self.init_camera()
                    else:
                        self.fullscreen = True
                        self.init_screen()
                        self.init_camera()
            elif event.type == pygame.KEYUP:
                key_released = event.dict['key'] % 256
                if key_released == pygame.K_a:
                    self.dx -= -Campaign.USER_SPEED
                elif key_released == pygame.K_d:
                    self.dx -= Campaign.USER_SPEED
                elif key_released == pygame.K_w:
                    self.dy -= -Campaign.USER_SPEED
                elif key_released == pygame.K_s:
                    self.dy -= Campaign.USER_SPEED
            elif event.type == pygame.MOUSEBUTTONDOWN:
                button_pressed = event.dict['button']

                if button_pressed == 5:
                    self.camera.zoom_out()

                elif button_pressed == 4:
                    self.camera.zoom_in()

        return keep_going
示例#29
0
def admin_confirm():
    session_token = request.form["session_token"]
    confirmation_type = request.form["confirmation_type"]
    confirmation_val = request.form["confirmation_value"]
    choice = request.form["choice"]
    if confirmation_type == "recover_email":
        if choice == "Send E-mail":
            email_address = request.form['email_address']
            mailer = Mailer(email_address, request.access_route[-1], current_app.logger)
            mailer.recover_password()
            return render_template("admin/admin_login.jinja2", error="""
            If the e-mail address is in the database, instructions have been sent on how to recover 
            your password. Please check your spam/junk mail folder.
            """)
        return redirect(url_for('homepage'))
    elif confirmation_type == "no_erc20_tokens":
        return redirect(url_for('admin.admin_tokens', session_token=session_token))
    elif confirmation_type == "erc20_publish" and choice == "Cancel":
        return redirect(url_for('admin.admin_tokens', session_token=session_token))
    elif confirmation_type == "create_erc20_failed" and choice == "OK":
        return redirect(url_for('admin.admin_tokens', session_token=session_token))
    elif confirmation_type == "onboarded_new_user":
        if choice == "Administration":
            return redirect(url_for('admin.admin_main', session_token=session_token))
        else:
            return redirect(url_for('admin.create_user', session_token=session_token))
    elif confirmation_type == "reset-password":
        if choice == "Cancel":
            return redirect(url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
    elif confirmation_type == "acl_updated":
        if choice == "OK":
            return redirect(url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
    db = database.Database(logger=current_app.logger)
    user_id = db.validate_session(session_token)
    if user_id:
        user_ctx = UserContext(user_id, db, current_app.logger)
        if confirmation_type == "erc20_publish":
            token_id = int(confirmation_val)
            sc = SmartContract(smart_token_id=token_id)
            credits = Credits(user_id, db, logger=current_app.logger)
            if sc.smart_contract_id > 0:
                event_data = {"token_name": sc.token_name,
                              "token_symbol": sc.token_symbol,
                              "token_count": sc.tokens,
                              "token_id": sc.smart_contract_id,
                              "ip_address": request.access_route[-1]}
                if user_ctx.check_acl("launch-ico"):
                    credits_balance = credits.get_credit_balance()
                    if credits_balance >= credits.erc20_publish_price:
                        new_event = Event("ERC20 Token Mined", db, logger=current_app.logger)
                        event_id = new_event.log_event(user_id, event_data)
                        event_data["event_id"] = event_id
                        credits.debit(credits.erc20_publish_price, event_data)
                        command_id = db.post_command(json.dumps({"erc20_function":"publish",
                                                                 "token_name":sc.token_name,
                                                                 "token_symbol":sc.token_symbol,
                                                                 "token_count":sc.tokens,
                                                                 "token_id":sc.smart_contract_id}), 100)
                        if command_id:
                            return redirect(url_for("admin.admin_tokens", session_token=session_token))
                        else:
                            abort(500)
                    else:
                        credits.logger.error("Insufficient credits for ERC20 Publish: "
                                             + user_ctx.user_info["email_address"])
                abort(403)
        elif confirmation_type == "reset-password":
            user_id = int(confirmation_val)
            if request.form["password"] != request.form["repeat_password"]:
                return render_template("admin/admin_confirmation.jinja2",
                                       confirmation_type="reset-password",
                                       confirmation_value=user_id,
                                       title="Reset Password",
                                       confirmation_title="Reset Password",
                                       confirmation_message="Passwords must match both times.",
                                       new_password=True,
                                       choices=["Cancel"],
                                       default_choice="Reset Password",
                                       session_token=session_token)
            if db.reset_password(int(confirmation_val), request.form["password"]):
                return redirect(url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
        elif confirmation_type == "issue-credits":
            if choice == "Issue Credits" and user_ctx.check_acl("issue-credits"):
                user_credits = Credits(confirmation_val, db, current_app.logger)
                amount = int(request.form["credits"])
                # max issued credits 10,000
                if 0 < amount < 100000:
                    user_credits.issue_credits(amount, {"ip_addr": request.access_route[-1], "admin": user_id})
                    return redirect(
                        url_for("admin.view_users", session_token=session_token, limit=PAGE_LIMIT, offset=0))
                else:
                    raise ValueError

    abort(403)
示例#30
0
class Game():
    def __init__(self):

        # variables -----------------------------------------------

        # load background
        self.backg = Background(BKG_FOLDER + "stars.png")

        # set initial score
        self.score = 0

        # load sound and music volume from file
        # if there's a problem with the file, simply create a new one with default values
        try:
            volume = pickle.load(open("volume.p", "rb"))
        except:
            volume = {"sound": 100, "music": 30}
            pickle.dump(volume, open("volume.p", "wb"))

        # sounds
        self.laserSnd = pygame.mixer.Sound(SND_FOLDER + "laser.wav")
        self.explodeSnd = pygame.mixer.Sound(SND_FOLDER + "explosion.wav")
        self.powerUpSnd = pygame.mixer.Sound(SND_FOLDER + "powerUp.wav")

        # put everything into a list so it's easier to change the volume
        # the list elements are the same objects as the initial ones
        # as python copies by reference and not by value (I would have
        # preferred to use pointers, to avoid ambiguity, but oh well...)
        self.sounds = [self.laserSnd, self.explodeSnd, self.powerUpSnd]

        # set volume for all sound objects
        for snd in self.sounds:
            snd.set_volume(volume["sound"] / 100.)  # set new volume

        # music
        self.music = pygame.mixer.music.load(MUS_FOLDER +
                                             "reachingForTheSun.mp3")
        pygame.mixer.music.play(-1)  # loop
        pygame.mixer.music.set_volume(volume["music"] / 100.)

        # creating user ship
        self.userShip1 = ShipY001()
        self.userShip2 = ShipY002()
        self.userShip3 = ShipY003()
        self.userShip1.speed = 10
        self.userShip2.speed = 10
        self.userShip3.speed = 10
        # group of all sprites
        self.userSprites1 = pygame.sprite.Group()
        self.userSprites2 = pygame.sprite.Group()
        self.userSprites3 = pygame.sprite.Group()
        self.laserSprites = pygame.sprite.Group()
        self.aiSprites = pygame.sprite.Group()
        self.powerUpSprites = pygame.sprite.Group()

        # add to groups
        self.userSprites1.add(self.userShip1)
        self.userSprites2.add(self.userShip2)
        self.userSprites3.add(self.userShip3)

        # Creating main menu
        self.menu = Menu(["Quit", "Credits", "Volume", "Play"], self.backg)

        # Creating game_mode
        self.mode = Menu(["HELL", "HARD", "NORMAL"], self.backg)
        self.modeBack = 0

        # Creating pause menu (could be generated later, but shouldn't impact performance)
        self.pause = Menu(["Quit", "Volume", "Restart", "Continue"],
                          self.backg)

        # Creating volume menu (could be generated later, but shouldn't impact performance)
        self.volume = Volume(self.backg, volume)
        self.volumeBack = 0  # some stupid flag to tell us whether we came from the main menu
        # of from the pause menu

        # Creating credits
        self.credits = Credits([
            "Sound: Obtained from Freesound",
            "Music: 'Reaching for the Sun' by Deshiel and Bacon92",
            "Graphics: Filipa Silva", "Code: Alexandre Lopes"
        ], self.backg)

        # gameState
        # Available states: menu, credits ,game, gameOver
        self.gameState = "menu"

        # -----------------------------------------------

    def handle(self, event):

        # some flags (this could be re-done in a better way, but for now it works)
        wasPressedNow = 0  # this is for some stupid hack, see below
        # Menu ===============================================================
        if self.gameState == "menu":

            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.menu.press() == 3:  # play pressed
                        self.gameState = "mode"  # show mode
                        wasPressedNow = 1
                    elif self.menu.press() == 2:  # volume pressed
                        self.gameState = "volume"  # show volume menu
                        wasPressedNow = 1
                        self.volumeBack = 1
                    elif self.menu.press() == 1:  # credits pressed
                        self.gameState = "credits"  # show credits
                        wasPressedNow = 1  # stupid hack to prevent event from being
                        # read here and in the credits
                        # probably the best solution would be to change
                        # the way everything is structured
                        # but this proved to be easier
                    elif self.menu.press() == 0:  # quit pressed
                        pygame.quit()
                        sys.exit()
                    else:
                        pass  # throw exception
                if event.key == pygame.K_DOWN:
                    self.menu.down()
                if event.key == pygame.K_UP:
                    self.menu.up()
        #  mode===================================================================
        if self.gameState == "mode" and wasPressedNow == 0:

            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.mode.press() == 2:
                        self.modeBack = 0
                        print(self.modeBack)
                        self.gameState = "game_Normal"
                    elif self.mode.press() == 1:
                        self.modeBack = 1
                        self.gameState = "game_Hard"
                    elif self.mode.press() == 0:
                        self.modeBack = 2
                        self.gameState = "game_Hell"
                    else:
                        pass
                if event.key == pygame.K_DOWN:
                    self.mode.down()
                if event.key == pygame.K_UP:
                    self.mode.up()

        # Pause===============================================================
        if self.gameState == "pause":

            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.pause.press() == 3:  # continue pressed
                        if self.modeBack == 0:
                            self.gameState = "game_Normal"
                        elif self.modeBack == 1:
                            self.gameState = "game_Hard"
                        elif self.modeBack == 2:
                            self.gameState = "game_Hell"
                    elif self.pause.press() == 2:
                        self.__init__()
                        if self.modeBack == 0:
                            self.gameState = "game_Normal"
                        elif self.modeBack == 1:
                            self.gameState = "game_Hard"
                        elif self.modeBack == 2:
                            self.gameState = "game_Hell"

                    elif self.pause.press() == 1:
                        self.gameState = "volume"
                        self.volumeBack = 0
                        wasPressedNow = 1
                    elif self.pause.press() == 0:  # quit pressed
                        pygame.quit()
                        sys.exit()
                    else:
                        pass  # throw exception
                if event.key == pygame.K_DOWN:
                    self.pause.down()
                if event.key == pygame.K_UP:
                    self.pause.up()
        #  ===================================================================

        # Volume =============================================================
        if self.gameState == "volume" and wasPressedNow == 0:

            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.volume.press() == 0:  # back pressed
                        if self.volumeBack == 1:  # then we should go back to menu
                            self.gameState = "menu"
                        elif self.volumeBack == 0:  # then we should go back to the pause menu
                            self.gameState = "pause"
                    else:
                        pass  # throw exception
                # move "cursor" down
                if event.key == pygame.K_DOWN:
                    self.volume.down()
                # move "cursor" up
                if event.key == pygame.K_UP:
                    self.volume.up()

                # raise music volume if it is selected
                if event.key == pygame.K_RIGHT and self.volume.press() == 2:
                    pygame.mixer.music.set_volume(
                        self.volume.right())  # update volume

                    # newVolume = pygame.mixer.music.get_volume() + .1 # get current volume and increment
                    # if newVolume > 1.:    # if it exceeds the maximum
                    # newVolume = 1.
                    # pygame.mixer.music.set_volume(newVolume)
                    # #save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(),
                    # "music": pygame.mixer.music.get_volume()},
                    # open( "volume.p", "wb" ) )

                # lower music volume if it is selected
                if event.key == pygame.K_LEFT and self.volume.press() == 2:
                    pygame.mixer.music.set_volume(
                        self.volume.left())  # update volume

                    # if newVolume < 0.:    # if it exceeds the maximum
                    # newVolume = 0.
                    # pygame.mixer.music.set_volume(newVolume)
                    # # save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(),
                    # "music": pygame.mixer.music.get_volume()},
                    # open( "volume.p", "wb" ) )

                # raise volume if it is selected
                if event.key == pygame.K_RIGHT and self.volume.press() == 1:
                    newVolume = self.volume.right()
                    for snd in self.sounds:
                        snd.set_volume(newVolume)  # set new volume

                    # newVolume = self.sounds[0].get_volume() + .1 # get current volume and increment
                    # if newVolume > 1.:    # if it exceeds the maximum
                    # newVolume = 1.
                    # # set now for every sound object we have

                    # # save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(),
                    # "music": pygame.mixer.music.get_volume()},
                    # open( "volume.p", "wb" ) )

                # lower volume if it is selected
                if event.key == pygame.K_LEFT and self.volume.press() == 1:
                    newVolume = self.volume.left()
                    for snd in self.sounds:
                        snd.set_volume(newVolume)  # set new volume

                    # newVolume = self.sounds[0].get_volume() - .1 # get current volume and increment
                    # if newVolume < 0.:    # if it exceeds the maximum
                    # newVolume = 0.
                    # # set now for every sound object we have
                    # for snd in self.sounds:
                    # snd.set_volume(newVolume) # set new volume
                    # # save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(),
                    # "music": pygame.mixer.music.get_volume()},
                    # open( "volume.p", "wb" ) )

        #  ===================================================================

        # Credits=============================================================
        if self.gameState == "credits" and wasPressedNow == 0:

            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    self.gameState = "menu"  # return to menu
                else:
                    pass  # throw exception
        #  ===================================================================

        # Game ===============================================================
        elif self.gameState == "game_Normal":
            self.modeBack = 0
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # only on KEYDOWN event
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    x = self.userShip1.rect.x
                    y = self.userShip1.rect.y
                    self.laserSprites.add(Laser(x + 12, y + 28))
                    self.laserSnd.play()
                elif event.key == pygame.K_ESCAPE:
                    self.gameState = "pause"

        elif self.gameState == "game_Hard":
            self.modeBack = 1
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # only on KEYDOWN event
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    x = self.userShip2.rect.x
                    y = self.userShip2.rect.y
                    self.laserSprites.add(Laser(x + 12, y + 28))
                    self.laserSnd.play()
                elif event.key == pygame.K_ESCAPE:
                    self.gameState = "pause"

        elif self.gameState == "game_Hell":
            self.modeBack = 2
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # only on KEYDOWN event
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    x = self.userShip3.rect.x
                    y = self.userShip3.rect.y
                    self.laserSprites.add(Laser(x + 12, y + 28))
                    self.laserSnd.play()
                elif event.key == pygame.K_ESCAPE:
                    self.gameState = "pause"

        #  ===================================================================
        # Game Over ==========================================================

        elif self.gameState == "gameOver":
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # only on KEYDOWN event - restart game with return or quit with escape
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if self.modeBack == 0:
                        self.__init__()
                        self.gameState = "game_Normal"
                    elif self.modeBack == 1:
                        self.__init__()
                        self.gameState = "game_Hard"
                    elif self.modeBack == 2:
                        self.__init__()
                        self.gameState = "game_Hell"

                elif event.key == pygame.K_ESCAPE:
                    self.__init__()
                    self.gameState = "menu"

        else:
            pass  # throw exception!
        #  ===================================================================

    def keys(self, keys):
        #  Game ==============================================================

        if self.gameState == "game_Normal":
            self.modeBack = 0
            if keys[pygame.K_UP]:
                if self.userShip1.rect.y >= 0:
                    # prevent sprite from leaving window
                    self.userShip1.up()
            if keys[pygame.K_DOWN]:
                if self.userShip1.rect.y + self.userShip1.rect.height <= WINDOW_HEIGHT:
                    # prevent sprite from leaving window
                    self.userShip1.down()
            if keys[pygame.K_LEFT]:
                if self.userShip1.rect.x >= 0:
                    # prevent sprite from leaving window
                    self.userShip1.left()
            if keys[pygame.K_RIGHT]:
                if self.userShip1.rect.x + self.userShip1.rect.width <= WINDOW_WIDTH:
                    # prevent sprite from leaving window
                    self.userShip1.right()

        elif self.gameState == "game_Hard":
            self.modeBack = 1
            if keys[pygame.K_UP]:
                if self.userShip2.rect.y >= 0:
                    # prevent sprite from leaving window
                    self.userShip2.up()
            if keys[pygame.K_DOWN]:
                if self.userShip2.rect.y + self.userShip2.rect.height <= WINDOW_HEIGHT:
                    # prevent sprite from leaving window
                    self.userShip2.down()
            if keys[pygame.K_LEFT]:
                if self.userShip2.rect.x >= 0:
                    # prevent sprite from leaving window
                    self.userShip2.left()
            if keys[pygame.K_RIGHT]:
                if self.userShip2.rect.x + self.userShip2.rect.width <= WINDOW_WIDTH:
                    # prevent sprite from leaving window
                    self.userShip2.right()

        elif self.gameState == "game_Hell":
            self.modeBack = 2
            if keys[pygame.K_UP]:
                if self.userShip3.rect.y >= 0:
                    # prevent sprite from leaving window
                    self.userShip3.up()
            if keys[pygame.K_DOWN]:
                if self.userShip3.rect.y + self.userShip3.rect.height <= WINDOW_HEIGHT:
                    # prevent sprite from leaving window
                    self.userShip3.down()
            if keys[pygame.K_LEFT]:
                if self.userShip3.rect.x >= 0:
                    # prevent sprite from leaving window
                    self.userShip3.left()
            if keys[pygame.K_RIGHT]:
                if self.userShip3.rect.x + self.userShip3.rect.width <= WINDOW_WIDTH:
                    # prevent sprite from leaving window
                    self.userShip3.right()
        #  ===================================================================

    def update(self):
        # Menu ===============================================================
        if self.gameState == "menu":
            pass
        # Mode====================================================================
        if self.gameState == "mode":
            pass
        # Pause ==============================================================
        if self.gameState == "pause":
            pass
        # ====================================================================

        # Volume ==============================================================
        if self.gameState == "volume":
            pass
        # ====================================================================

        # Credits ============================================================
        if self.gameState == "credits":
            pass
        # ====================================================================

        # Game ===============================================================
        if self.gameState == "game_Normal":
            self.modeBack = 0
            # Spawning ====================================================

            # Spawn X001 enemy ships at random in a random y position
            # Probability: 1 in 60 per frame.
            if randint(1, 70) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX001(WINDOW_WIDTH, 0, -6)
                # random y position on the screen
                enemyObj.rect.y = randint(0,
                                          WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)

            # Spawn X002 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame.
            if randint(1, 70) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX002(WINDOW_WIDTH, 0, -4)
                # random y position on the screen
                enemyObj.rect.y = randint(0,
                                          WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)

            # Spawn X003 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame.
            if randint(1, 70) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX003(WINDOW_WIDTH, 0, -4)
                # random y position on the screen
                enemyObj.yInitial = randint(
                    0, WINDOW_HEIGHT - enemyObj.rect.height)
                enemyObj.rect.y = enemyObj.yInitial
                self.aiSprites.add(enemyObj)
                # Movement ====================================================
            # Move enemy ships forward according to their speed
            for enemy in self.aiSprites:
                enemy.update()

            # Move lasers forward according to their speed
            for laser in self.laserSprites:
                laser.update()

            #Move powerUps forward according to their speed
            for powerUp in self.powerUpSprites:
                powerUp.update()
            # =============================================================

            # Erasing =====================================================
            # Erase lasers that are out of the screen
            for laser in self.laserSprites:
                if laser.rect.x > WINDOW_WIDTH:
                    self.laserSprites.remove(laser)

            # Erase enemy ships that are out of the screen
            for enemy in self.aiSprites:
                if enemy.rect.x < -10:
                    self.aiSprites.remove(enemy)

            # Erase powerUps that are out of the screen
            for powerUp in self.powerUpSprites:
                if powerUp.rect.x < -10:
                    self.powerUpSprites.remove(powerUp)
            # =============================================================

            # Collisions ==================================================

            # check for collisions between user lasers and enemy sprites
            for laser in self.laserSprites:
                enemyHitList = pygame.sprite.spritecollide(
                    laser, self.aiSprites, True)

                # if there was a collision
                if enemyHitList:
                    self.laserSprites.remove(laser)  # remove laser
                    self.explodeSnd.play()
                # iterate over all enemy ships that collided
                for enemy in enemyHitList:
                    thereIsPowerUp = 0  # enemy ship has not spawned power up
                    self.score = self.score + enemy.score  # add to score
                    # Spawn Health 25 at random in the place of destroyed enemy ship
                    # Probability: 1 per 50 destroyed enemies
                    if randint(1, 50) == 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health25(WINDOW_WIDTH, 0, -5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj)
                        thereIsPowerUp = 1  # to prevent enemy ship from spawning two powerups
                    # Spawn Health 100 random in the place of destroyed enemy ship
                    # but only if enemy ship has not spawned another powerUp
                    # Probability: 1 per 125 destroyed enemies
                    if randint(1, 125) == 1 and thereIsPowerUp != 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health100(WINDOW_WIDTH, 0, -5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj)

            # check for collisions between enemyShips and the user
            for enemy in self.aiSprites:
                userHit = pygame.sprite.spritecollide(
                    enemy, self.userSprites1, False,
                    pygame.sprite.collide_mask)

                # if there was a collision
                if userHit:
                    self.aiSprites.remove(enemy)  # remove object
                    self.userShip1.shield -= 25
                    self.score = self.score + enemy.score  # add to score
                    self.explodeSnd.play()

            # check for collisions between powerUps and the user
            for powerUp in self.powerUpSprites:
                userHit = pygame.sprite.spritecollide(powerUp,
                                                      self.userSprites1, False)

                # if there was a collision
                if userHit:
                    self.powerUpSprites.remove(powerUp)  # remove object
                    powerUp.pickUp(self.userShip1)
                    self.powerUpSnd.play()  # no sound yet!!
            # =============================================================

            # if user is dead
            if self.userShip1.shield <= 0:
                self.userShip1.shield = 0  # round shield to 0
                self.modeBack = 0
                self.gameState = "gameOver"  # change state to gameOver

        elif self.gameState == "game_Hard":
            self.modeBack = 1
            # Spawning ====================================================

            # Spawn X001 enemy ships at random in a random y position
            # Probability: 1 in 60 per frame.
            if randint(1, 50) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX001(WINDOW_WIDTH, 0, -6)
                # random y position on the screen
                enemyObj.rect.y = randint(0,
                                          WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)

            # Spawn X002 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame.
            if randint(1, 50) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX002(WINDOW_WIDTH, 0, -4)
                # random y position on the screen
                enemyObj.rect.y = randint(0,
                                          WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)

            # Spawn X003 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame.
            if randint(1, 50) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX003(WINDOW_WIDTH, 0, -4)
                # random y position on the screen
                enemyObj.yInitial = randint(
                    0, WINDOW_HEIGHT - enemyObj.rect.height)
                enemyObj.rect.y = enemyObj.yInitial
                self.aiSprites.add(enemyObj)

            # Movement ====================================================
            # Move enemy ships forward according to their speed
            for enemy in self.aiSprites:
                enemy.update()

            # Move lasers forward according to their speed
            for laser in self.laserSprites:
                laser.update()

            #Move powerUps forward according to their speed
            for powerUp in self.powerUpSprites:
                powerUp.update()
            # =============================================================

            # Erasing =====================================================
            # Erase lasers that are out of the screen
            for laser in self.laserSprites:
                if laser.rect.x > WINDOW_WIDTH:
                    self.laserSprites.remove(laser)

            # Erase enemy ships that are out of the screen
            for enemy in self.aiSprites:
                if enemy.rect.x < -10:
                    self.aiSprites.remove(enemy)

            # Erase powerUps that are out of the screen
            for powerUp in self.powerUpSprites:
                if powerUp.rect.x < -10:
                    self.powerUpSprites.remove(powerUp)
            # =============================================================

            # Collisions ==================================================

            # check for collisions between user lasers and enemy sprites
            for laser in self.laserSprites:
                enemyHitList = pygame.sprite.spritecollide(
                    laser, self.aiSprites, True)

                # if there was a collision
                if enemyHitList:
                    self.laserSprites.remove(laser)  # remove laser
                    self.explodeSnd.play()
                # iterate over all enemy ships that collided
                for enemy in enemyHitList:
                    thereIsPowerUp = 0  # enemy ship has not spawned power up
                    self.score = self.score + enemy.score  # add to score
                    # Spawn Health 25 at random in the place of destroyed enemy ship
                    # Probability: 1 per 50 destroyed enemies
                    if randint(1, 50) == 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health25(WINDOW_WIDTH, 0, -5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj)
                        thereIsPowerUp = 1  # to prevent enemy ship from spawning two powerups
                    # Spawn Health 100 random in the place of destroyed enemy ship
                    # but only if enemy ship has not spawned another powerUp
                    # Probability: 1 per 125 destroyed enemies
                    if randint(1, 125) == 1 and thereIsPowerUp != 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health100(WINDOW_WIDTH, 0, -5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj)

            # check for collisions between enemyShips and the user
            for enemy in self.aiSprites:
                userHit = pygame.sprite.spritecollide(
                    enemy, self.userSprites2, False,
                    pygame.sprite.collide_mask)

                # if there was a collision
                if userHit:
                    self.aiSprites.remove(enemy)  # remove object
                    self.userShip2.shield -= 50
                    self.score = self.score + enemy.score  # add to score
                    self.explodeSnd.play()

            # check for collisions between powerUps and the user
            for powerUp in self.powerUpSprites:
                userHit = pygame.sprite.spritecollide(powerUp,
                                                      self.userSprites2, False)

                # if there was a collision
                if userHit:
                    self.powerUpSprites.remove(powerUp)  # remove object
                    powerUp.pickUp(self.userShip2)
                    self.powerUpSnd.play()  # no sound yet!!
            # =============================================================

            # if user is dead
            if self.userShip2.shield <= 0:
                self.userShip2.shield = 0  # round shield to 0
                self.modeBack = 1
                self.gameState = "gameOver"  # change state to gameOver

        elif self.gameState == "game_Hell":
            self.modeBack = 2
            # Spawning ====================================================

            # Spawn X001 enemy ships at random in a random y position
            # Probability: 1 in 60 per frame.
            if randint(1, 20) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX001(WINDOW_WIDTH, 0, -6)
                # random y position on the screen
                enemyObj.rect.y = randint(0,
                                          WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)

            # Spawn X002 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame.
            if randint(1, 20) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX002(WINDOW_WIDTH, 0, -4)
                # random y position on the screen
                enemyObj.rect.y = randint(0,
                                          WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)

            # Spawn X003 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame.
            if randint(1, 20) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX003(WINDOW_WIDTH, 0, -4)
                # random y position on the screen
                enemyObj.yInitial = randint(
                    0, WINDOW_HEIGHT - enemyObj.rect.height)
                enemyObj.rect.y = enemyObj.yInitial
                self.aiSprites.add(enemyObj)

            # =============================================================

            # Movement ====================================================
            # Move enemy ships forward according to their speed
            for enemy in self.aiSprites:
                enemy.update()

            # Move lasers forward according to their speed
            for laser in self.laserSprites:
                laser.update()

            #Move powerUps forward according to their speed
            for powerUp in self.powerUpSprites:
                powerUp.update()
            # =============================================================

            # Erasing =====================================================
            # Erase lasers that are out of the screen
            for laser in self.laserSprites:
                if laser.rect.x > WINDOW_WIDTH:
                    self.laserSprites.remove(laser)

            # Erase enemy ships that are out of the screen
            for enemy in self.aiSprites:
                if enemy.rect.x < -10:
                    self.aiSprites.remove(enemy)

            # Erase powerUps that are out of the screen
            for powerUp in self.powerUpSprites:
                if powerUp.rect.x < -10:
                    self.powerUpSprites.remove(powerUp)
            # =============================================================

            # Collisions ==================================================

            # check for collisions between user lasers and enemy sprites
            for laser in self.laserSprites:
                enemyHitList = pygame.sprite.spritecollide(
                    laser, self.aiSprites, True)

                # if there was a collision
                if enemyHitList:
                    self.laserSprites.remove(laser)  # remove laser
                    self.explodeSnd.play()
                # iterate over all enemy ships that collided
                for enemy in enemyHitList:
                    thereIsPowerUp = 0  # enemy ship has not spawned power up
                    self.score = self.score + enemy.score  # add to score
                    # Spawn Health 25 at random in the place of destroyed enemy ship
                    # Probability: 1 per 50 destroyed enemies
                    if randint(1, 50) == 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health25(WINDOW_WIDTH, 0, -5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj)
                        thereIsPowerUp = 1  # to prevent enemy ship from spawning two powerups
                    # Spawn Health 100 random in the place of destroyed enemy ship
                    # but only if enemy ship has not spawned another powerUp
                    # Probability: 1 per 125 destroyed enemies
                    if randint(1, 125) == 1 and thereIsPowerUp != 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health100(WINDOW_WIDTH, 0, -5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj)

            # check for collisions between enemyShips and the user
            for enemy in self.aiSprites:
                userHit = pygame.sprite.spritecollide(
                    enemy, self.userSprites3, False,
                    pygame.sprite.collide_mask)

                # if there was a collision
                if userHit:
                    self.aiSprites.remove(enemy)  # remove object
                    self.userShip3.shield -= 100
                    self.score = self.score + enemy.score  # add to score
                    self.explodeSnd.play()

            # check for collisions between powerUps and the user
            for powerUp in self.powerUpSprites:
                userHit = pygame.sprite.spritecollide(powerUp,
                                                      self.userSprites3, False)

                # if there was a collision
                if userHit:
                    self.powerUpSprites.remove(powerUp)  # remove object
                    powerUp.pickUp(self.userShip3)
                    self.powerUpSnd.play()  # no sound yet!!
            # =============================================================

            # if user is dead
            if self.userShip3.shield <= 0:
                self.userShip3.shield = 0  # round shield to 0
                self.modeBack = 2
                self.gameState = "gameOver"  # change state to gameOver
        # ====================================================================

        # Game Over ==========================================================
        elif self.gameState == "gameOver":
            pass
        # ====================================================================
        else:
            pass  # throw exception!

    def draw(self, screen):

        # Menu ===============================================================
        if self.gameState == "menu":
            self.menu.draw(screen)
        # Mode====================================================================
        if self.gameState == "mode":
            self.mode.draw(screen)
        # Pause ==============================================================
        if self.gameState == "pause":
            self.pause.draw(screen)

        # Volume =============================================================
        if self.gameState == "volume":
            self.volume.draw(screen)
        # ====================================================================

        # Credits ============================================================
        if self.gameState == "credits":
            self.credits.draw(screen)
        # ====================================================================

        # Game ===============================================================
        elif self.gameState == "game_Normal":
            # erase screen
            screen.fill(BLACK)

            # draw background - since the background is scrolling
            # we shall draw two side by side to prevent the background from ending
            # this way it repeats itself
            screen.blit(self.backg.image, (self.backg.x, self.backg.y))
            screen.blit(self.backg.image,
                        (self.backg.x + self.backg.width, self.backg.y))

            # draw sprites onto the screen
            self.userSprites1.draw(screen)
            self.laserSprites.draw(screen)
            self.aiSprites.draw(screen)
            self.powerUpSprites.draw(screen)

            # drawing text
            font = pygame.font.SysFont("Arial", 25)
            shieldTxt = font.render("Shield: " + str(self.userShip1.shield),
                                    True, WHITE)
            scoreTxt = font.render("Score: " + str(self.score), True, WHITE)
            screen.blit(shieldTxt, [0, 0])
            screen.blit(scoreTxt, [0, 30])

            # animations
            self.backg.scroll(1)  # update background
            self.userShip1.animate()  # update animation
            for enemy in self.aiSprites:
                enemy.animate()  # update animation
            for powerUp in self.powerUpSprites:
                powerUp.animate()

        elif self.gameState == "game_Hard":
            # erase screen
            screen.fill(BLACK)

            # draw background - since the background is scrolling
            # we shall draw two side by side to prevent the background from ending
            # this way it repeats itself
            screen.blit(self.backg.image, (self.backg.x, self.backg.y))
            screen.blit(self.backg.image,
                        (self.backg.x + self.backg.width, self.backg.y))

            # draw sprites onto the screen
            self.userSprites2.draw(screen)
            self.laserSprites.draw(screen)
            self.aiSprites.draw(screen)
            self.powerUpSprites.draw(screen)

            # drawing text
            font = pygame.font.SysFont("Arial", 25)
            shieldTxt = font.render("Shield: " + str(self.userShip2.shield),
                                    True, WHITE)
            scoreTxt = font.render("Score: " + str(self.score), True, WHITE)
            screen.blit(shieldTxt, [0, 0])
            screen.blit(scoreTxt, [0, 30])

            # animations
            self.backg.scroll(1)  # update background
            self.userShip2.animate()  # update animation
            for enemy in self.aiSprites:
                enemy.animate()  # update animation
            for powerUp in self.powerUpSprites:
                powerUp.animate()

        elif self.gameState == "game_Hell":
            # erase screen
            screen.fill(BLACK)

            # draw background - since the background is scrolling
            # we shall draw two side by side to prevent the background from ending
            # this way it repeats itself
            screen.blit(self.backg.image, (self.backg.x, self.backg.y))
            screen.blit(self.backg.image,
                        (self.backg.x + self.backg.width, self.backg.y))

            # draw sprites onto the screen
            self.userSprites3.draw(screen)
            self.laserSprites.draw(screen)
            self.aiSprites.draw(screen)
            self.powerUpSprites.draw(screen)

            # drawing text
            font = pygame.font.SysFont("Arial", 25)
            shieldTxt = font.render("Shield: " + str(self.userShip3.shield),
                                    True, WHITE)
            scoreTxt = font.render("Score: " + str(self.score), True, WHITE)
            screen.blit(shieldTxt, [0, 0])
            screen.blit(scoreTxt, [0, 30])

            # animations
            self.backg.scroll(1)  # update background
            self.userShip3.animate()  # update animation
            for enemy in self.aiSprites:
                enemy.animate()  # update animation
            for powerUp in self.powerUpSprites:
                powerUp.animate()

        # ====================================================================

        # Game Over ==========================================================

        elif self.gameState == "gameOver":

            # display game over and continue text
            font80 = pygame.font.SysFont("Arial", 80)
            font30 = pygame.font.SysFont("Arial", 30)
            gameOverTxt = font80.render("Game Over!", True, WHITE)
            continueTxt = font30.render(
                "(Press Enter to restart, go to menu ESC)", True, WHITE)

            screen.blit(gameOverTxt, [
                WINDOW_WIDTH / 2 - gameOverTxt.get_width() / 2,
                WINDOW_HEIGHT / 2 - gameOverTxt.get_height() / 2
            ])
            screen.blit(continueTxt, [
                WINDOW_WIDTH / 2 - continueTxt.get_width() / 2,
                WINDOW_HEIGHT / 2 - continueTxt.get_height() / 2 + 55
            ])
            pygame.display.update()
        else:

            pass  # throw exception!!
示例#31
0
文件: core.py 项目: aalopes/cometZ
    def __init__(self):

        # variables -----------------------------------------------

        # load background
        self.backg = Background(BKG_FOLDER + "stars.png")
        
        # set initial score
        self.score = 0
        
        # load sound and music volume from file
        # if there's a problem with the file, simply create a new one with default values
        try:
            volume = pickle.load( open( "volume.p", "rb" ) )
        except:
            volume = { "sound": 100, "music": 30 }
            pickle.dump( volume, open( "volume.p", "wb" ) )

        # sounds
        self.laserSnd   = pygame.mixer.Sound(SND_FOLDER + "laser.wav")
        self.explodeSnd = pygame.mixer.Sound(SND_FOLDER + "explosion.wav")    
        self.powerUpSnd = pygame.mixer.Sound(SND_FOLDER + "powerUp.wav")
        
        # put everything into a list so it's easier to change the volume
        # the list elements are the same objects as the initial ones
        # as python copies by reference and not by value (I would have
        # preferred to use pointers, to avoid ambiguity, but oh well...)
        self.sounds = [self.laserSnd,self.explodeSnd,self.powerUpSnd]       

        # set volume for all sound objects                
        for snd in self.sounds:
            snd.set_volume(volume["sound"]/100.) # set new volume
        
        # music
        self.music = pygame.mixer.music.load(MUS_FOLDER + "reachingForTheSun.mp3")
        pygame.mixer.music.play(-1) # loop
        pygame.mixer.music.set_volume(volume["music"]/100.)
        
        # creating user ship
        self.userShip = ShipY001()
        self.userShip.speed = 10
   
        # group of all sprites
        self.userSprites    = pygame.sprite.Group()
        self.laserSprites   = pygame.sprite.Group()
        self.aiSprites      = pygame.sprite.Group()
        self.powerUpSprites = pygame.sprite.Group()
        
        
        # add to groups
        self.userSprites.add(self.userShip)
        
        # Creating main menu
        self.menu = Menu(["Quit","Credits","Volume","Play"],self.backg)

        # Creating pause menu (could be generated later, but shouldn't impact performance)
        self.pause = Menu(["Quit","Volume","Restart","Continue"],self.backg)
        
        # Creating volume menu (could be generated later, but shouldn't impact performance)
        self.volume = Volume(self.backg,volume)
        self.volumeBack = 0 # some stupid flag to tell us whether we came from the main menu
                            # of from the pause menu 

        
        # Creating credits
        self.credits = Credits(["Sound: Obtained from Freesound",
                       "Music: 'Reaching for the Sun' by Deshiel and Bacon92",
                       "Graphics: Filipa Silva",
                       "Code: Alexandre Lopes"],
                       self.backg)
        
        # gameState
        # Available states: menu, credits ,game, gameOver
        self.gameState = "menu"
示例#32
0
#p2=Player([pygame.image.load("j1a.bmp"),pygame.image.load("j1b.bmp")],40,350,0)
p1imahora = 1
#fondo = pygame.image.load("estadio.bmp")

#Menu
#menu = Menu(['100m lisos','110m vallas', 'Salto de longitud', None, u'Créditos', 'Salir'])
menu = Menu(['100m lisos', 'Salto de longitud', None, u'Créditos', 'Salir'])
while True:
    game = menu.show(screen, clock)

    if game == 'Salir':
        #print 'Salir'
        sys.exit(0)
    elif game == u'Créditos':
        #print 'Créditos'
        play = Credits()
        play.play(screen, clock)
    elif game == '100m lisos':
        #print '100m lisos'
        play = Game100m()
        play.play(screen, clock)
    elif game == '110m vallas':
        #print '110m vallas'
        play = Game110mhurdles()
        play.play(screen, clock)
    elif game == 'Salto de longitud':
        #print 'Salto de longitud'
        play = Gamelongjump()
        play.play(screen, clock)

##Game
示例#33
0
文件: core.py 项目: aalopes/cometZ
class Game():

    def __init__(self):

        # variables -----------------------------------------------

        # load background
        self.backg = Background(BKG_FOLDER + "stars.png")
        
        # set initial score
        self.score = 0
        
        # load sound and music volume from file
        # if there's a problem with the file, simply create a new one with default values
        try:
            volume = pickle.load( open( "volume.p", "rb" ) )
        except:
            volume = { "sound": 100, "music": 30 }
            pickle.dump( volume, open( "volume.p", "wb" ) )

        # sounds
        self.laserSnd   = pygame.mixer.Sound(SND_FOLDER + "laser.wav")
        self.explodeSnd = pygame.mixer.Sound(SND_FOLDER + "explosion.wav")    
        self.powerUpSnd = pygame.mixer.Sound(SND_FOLDER + "powerUp.wav")
        
        # put everything into a list so it's easier to change the volume
        # the list elements are the same objects as the initial ones
        # as python copies by reference and not by value (I would have
        # preferred to use pointers, to avoid ambiguity, but oh well...)
        self.sounds = [self.laserSnd,self.explodeSnd,self.powerUpSnd]       

        # set volume for all sound objects                
        for snd in self.sounds:
            snd.set_volume(volume["sound"]/100.) # set new volume
        
        # music
        self.music = pygame.mixer.music.load(MUS_FOLDER + "reachingForTheSun.mp3")
        pygame.mixer.music.play(-1) # loop
        pygame.mixer.music.set_volume(volume["music"]/100.)
        
        # creating user ship
        self.userShip = ShipY001()
        self.userShip.speed = 10
   
        # group of all sprites
        self.userSprites    = pygame.sprite.Group()
        self.laserSprites   = pygame.sprite.Group()
        self.aiSprites      = pygame.sprite.Group()
        self.powerUpSprites = pygame.sprite.Group()
        
        
        # add to groups
        self.userSprites.add(self.userShip)
        
        # Creating main menu
        self.menu = Menu(["Quit","Credits","Volume","Play"],self.backg)

        # Creating pause menu (could be generated later, but shouldn't impact performance)
        self.pause = Menu(["Quit","Volume","Restart","Continue"],self.backg)
        
        # Creating volume menu (could be generated later, but shouldn't impact performance)
        self.volume = Volume(self.backg,volume)
        self.volumeBack = 0 # some stupid flag to tell us whether we came from the main menu
                            # of from the pause menu 

        
        # Creating credits
        self.credits = Credits(["Sound: Obtained from Freesound",
                       "Music: 'Reaching for the Sun' by Deshiel and Bacon92",
                       "Graphics: Filipa Silva",
                       "Code: Alexandre Lopes"],
                       self.backg)
        
        # gameState
        # Available states: menu, credits ,game, gameOver
        self.gameState = "menu"
        
        # -----------------------------------------------
        
    def handle(self,event):
    
        # some flags (this could be re-done in a better way, but for now it works)
        wasPressedNow = 0 # this is for some stupid hack, see below
        # Menu ===============================================================
        if self.gameState == "menu":
        
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.menu.press() == 3:     # play pressed
                        self.gameState = "game"    # begin game
                    elif self.menu.press() == 2:   # volume pressed
                        self.gameState = "volume"  # show volume menu
                        wasPressedNow = 1
                        self.volumeBack = 1
                    elif self.menu.press() == 1:   # credits pressed
                        self.gameState = "credits" # show credits
                        wasPressedNow = 1 # stupid hack to prevent event from being
                                          # read here and in the credits
                                          # probably the best solution would be to change
                                          # the way everything is structured
                                          # but this proved to be easier
                    elif self.menu.press() == 0: # quit pressed
                        pygame.quit()
                        sys.exit()
                    else:
                        pass # throw exception
                if event.key == pygame.K_DOWN:
                    self.menu.down()
                if event.key == pygame.K_UP:
                    self.menu.up()
        #  ===================================================================
        
        # Pause===============================================================
        if self.gameState == "pause":
        
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.pause.press() == 3:   # continue pressed
                        self.gameState = "game"   # change state back to game
                    elif self.pause.press() == 2: # restart pressed
                        self.__init__()           # return to initial state
                        self.gameState = "game"   # change state back to game
                    elif self.pause.press() == 1:   # volume pressed
                        self.gameState = "volume"  # show volume menu
                        self.volumeBack = 0
                        wasPressedNow = 1
                    elif self.pause.press() == 0: # quit pressed
                        pygame.quit()
                        sys.exit()
                    else:
                        pass # throw exception
                if event.key == pygame.K_DOWN:
                    self.pause.down()
                if event.key == pygame.K_UP:
                    self.pause.up()
        #  ===================================================================
         
        # Volume =============================================================
        if self.gameState == "volume" and wasPressedNow == 0:
        
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.volume.press() == 0:     # back pressed
                        if self.volumeBack == 1:      # then we should go back to menu
                            self.gameState = "menu"
                        elif self.volumeBack == 0:    # then we should go back to the pause menu
                            self.gameState = "pause"
                    else:
                        pass # throw exception
                # move "cursor" down
                if event.key == pygame.K_DOWN:
                    self.volume.down()
                # move "cursor" up
                if event.key == pygame.K_UP:
                    self.volume.up()
                    
                # raise music volume if it is selected
                if event.key == pygame.K_RIGHT and self.volume.press() == 2:
                    pygame.mixer.music.set_volume(self.volume.right()) # update volume
                    
                    # newVolume = pygame.mixer.music.get_volume() + .1 # get current volume and increment
                    # if newVolume > 1.:    # if it exceeds the maximum
                        # newVolume = 1.
                    # pygame.mixer.music.set_volume(newVolume)
                    # #save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(), 
                                  # "music": pygame.mixer.music.get_volume()}, 
                                  # open( "volume.p", "wb" ) )
                                  
                # lower music volume if it is selected
                if event.key == pygame.K_LEFT and self.volume.press() == 2:
                    pygame.mixer.music.set_volume(self.volume.left()) # update volume
                    
                    # if newVolume < 0.:    # if it exceeds the maximum
                        # newVolume = 0.
                    # pygame.mixer.music.set_volume(newVolume)
                    # # save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(), 
                                  # "music": pygame.mixer.music.get_volume()}, 
                                  # open( "volume.p", "wb" ) )

                # raise volume if it is selected
                if event.key == pygame.K_RIGHT and self.volume.press() == 1:
                    newVolume = self.volume.right()
                    for snd in self.sounds:
                        snd.set_volume(newVolume) # set new volume
                        
                    # newVolume = self.sounds[0].get_volume() + .1 # get current volume and increment
                    # if newVolume > 1.:    # if it exceeds the maximum
                        # newVolume = 1.
                    # # set now for every sound object we have
                
                    # # save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(), 
                                  # "music": pygame.mixer.music.get_volume()}, 
                                  # open( "volume.p", "wb" ) )
                         
                        
                # lower volume if it is selected
                if event.key == pygame.K_LEFT and self.volume.press() == 1:
                    newVolume = self.volume.left()
                    for snd in self.sounds:
                        snd.set_volume(newVolume) # set new volume              
                
                    # newVolume = self.sounds[0].get_volume() - .1 # get current volume and increment
                    # if newVolume < 0.:    # if it exceeds the maximum
                        # newVolume = 0.
                    # # set now for every sound object we have
                    # for snd in self.sounds:
                        # snd.set_volume(newVolume) # set new volume
                    # # save new volume to file
                    # pickle.dump( {"sound": self.sounds[0].get_volume(), 
                                  # "music": pygame.mixer.music.get_volume()}, 
                                  # open( "volume.p", "wb" ) )
                    
        #  ===================================================================
        
        # Credits=============================================================
        if self.gameState == "credits" and wasPressedNow == 0:
        
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    self.gameState = "menu" # return to menu
                else:
                    pass # throw exception
        #  ===================================================================
        
        # Game ===============================================================
        elif self.gameState == "game":
        
            if event.type == QUIT:
                        pygame.quit()
                        sys.exit()
            # only on KEYDOWN event
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    x = self.userShip.rect.x
                    y = self.userShip.rect.y
                    self.laserSprites.add(Laser(x+12,y+28))
                    self.laserSnd.play()
                elif event.key == pygame.K_ESCAPE:
                    self.gameState = "pause"
        #  ===================================================================
        # Game Over ==========================================================

        elif self.gameState == "gameOver":
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            # only on KEYDOWN event - restart game with return or quit with escape
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    self.__init__()
                    self.gameState = "game"
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

        else:
            pass # throw exception!  
        #  ===================================================================

    def keys(self,keys):
        #  Game ==============================================================
    
        if self.gameState == "game":
        
            if keys[pygame.K_UP]:
                if self.userShip.rect.y >= 0: 
                    # prevent sprite from leaving window
                    self.userShip.up()
            if keys[pygame.K_DOWN]:
                if self.userShip.rect.y + self.userShip.rect.height <= WINDOW_HEIGHT: 
                    # prevent sprite from leaving window
                    self.userShip.down()
            if keys[pygame.K_LEFT]:
                if self.userShip.rect.x >= 0:
                    # prevent sprite from leaving window                    
                    self.userShip.left()
            if keys[pygame.K_RIGHT]:
                if self.userShip.rect.x + self.userShip.rect.width <= WINDOW_WIDTH:
                    # prevent sprite from leaving window
                    self.userShip.right()
        #  ===================================================================

    def update(self):
        # Menu ===============================================================
        if self.gameState == "menu":
            pass
        # ====================================================================

        # Pause ==============================================================
        if self.gameState == "pause":
            pass
        # ====================================================================
        
        # Volume ==============================================================
        if self.gameState == "volume":
            pass
        # ====================================================================
        
        # Credits ============================================================
        if self.gameState == "credits":
            pass
        # ====================================================================
        
        # Game ===============================================================
        elif self.gameState == "game":
        
            # Spawning ====================================================

            # Spawn X001 enemy ships at random in a random y position
            # Probability: 1 in 60 per frame.
            if randint(1,60) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX001(WINDOW_WIDTH, 0,-6)
                # random y position on the screen
                enemyObj.rect.y = randint(0, WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)
            
            # Spawn X002 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame. 
            if randint(1,120) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX002(WINDOW_WIDTH, 0,-4)
                # random y position on the screen
                enemyObj.rect.y = randint(0, WINDOW_HEIGHT - enemyObj.rect.height)
                self.aiSprites.add(enemyObj)            

            # Spawn X003 enemy ships at random in a random y position
            # Probability: 1 in 120 per frame. 
            if randint(1,120) == 1:
                # create temporary instance so we can grab the height of the sprite
                enemyObj = EnemyShipX003(WINDOW_WIDTH, 0,-4)
                # random y position on the screen
                enemyObj.yInitial = randint(0, WINDOW_HEIGHT - enemyObj.rect.height)
                enemyObj.rect.y   =  enemyObj.yInitial
                self.aiSprites.add(enemyObj) 
                 
            # =============================================================

                
            # Movement ====================================================
            # Move enemy ships forward according to their speed
            for enemy in self.aiSprites:
                enemy.update()
                
            # Move lasers forward according to their speed
            for laser in self.laserSprites:
                laser.update()
                
            #Move powerUps forward according to their speed
            for powerUp in self.powerUpSprites:
                powerUp.update()
            # =============================================================
            
            # Erasing =====================================================
            # Erase lasers that are out of the screen
            for laser in self.laserSprites:
                if laser.rect.x > WINDOW_WIDTH:
                    self.laserSprites.remove(laser)
                    
            # Erase enemy ships that are out of the screen
            for enemy in self.aiSprites:
                if enemy.rect.x < -10:
                    self.aiSprites.remove(enemy)
                    
            # Erase powerUps that are out of the screen
            for powerUp in self.powerUpSprites:
                if powerUp.rect.x < -10:
                    self.powerUpSprites.remove(powerUp)
            # =============================================================

            # Collisions ==================================================
            
            # check for collisions between user lasers and enemy sprites
            for laser in self.laserSprites:
                enemyHitList = pygame.sprite.spritecollide(laser,self.aiSprites,True) 
                
                # if there was a collision
                if enemyHitList:
                    self.laserSprites.remove(laser)             # remove laser
                    self.explodeSnd.play()
                # iterate over all enemy ships that collided
                for enemy in enemyHitList:
                    thereIsPowerUp = 0 # enemy ship has not spawned power up
                    self.score = self.score + enemy.score # add to score
                    # Spawn Health 25 at random in the place of destroyed enemy ship
                    # Probability: 1 per 50 destroyed enemies
                    if randint(1,50) == 1:
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health25(WINDOW_WIDTH, 0,-5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj) 
                        thereIsPowerUp = 1 # to prevent enemy ship from spawning two powerups
                    # Spawn Health 100 random in the place of destroyed enemy ship
                    # but only if enemy ship has not spawned another powerUp
                    # Probability: 1 per 125 destroyed enemies
                    if randint(1,125) == 1 and thereIsPowerUp != 1: 
                        # create temporary instance so we can grab the height of the sprite
                        powerUpObj = Health100(WINDOW_WIDTH, 0,-5)
                        powerUpObj.rect.x = enemy.rect.x
                        powerUpObj.rect.y = enemy.rect.y
                        self.powerUpSprites.add(powerUpObj) 
                                        
                    
            
            # check for collisions between enemyShips and the user
            for enemy in self.aiSprites:
                userHit = pygame.sprite.spritecollide(enemy,self.userSprites,False,
                                                      pygame.sprite.collide_mask)
                
                # if there was a collision
                if userHit:
                    self.aiSprites.remove(enemy) # remove object
                    self.userShip.shield -= 25
                    self.score = self.score + enemy.score # add to score
                    self.explodeSnd.play()
                    
            # check for collisions between powerUps and the user
            for powerUp in self.powerUpSprites:
                userHit = pygame.sprite.spritecollide(powerUp,self.userSprites,False)
                
                # if there was a collision
                if userHit:
                    self.powerUpSprites.remove(powerUp) # remove object
                    powerUp.pickUp(self.userShip)
                    self.powerUpSnd.play()                # no sound yet!!
            # =============================================================
                    
            # if user is dead
            if self.userShip.shield <= 0:
                self.userShip.shield = 0        # round shield to 0
                self.gameState = "gameOver"     # change state to gameOver            
        # ====================================================================
        
        # Game Over ==========================================================
        elif self.gameState == "gameOver":            
            pass
        # ====================================================================
        else:
            pass # throw exception!
            
    def draw(self,screen):
    
        # Menu ===============================================================
        if self.gameState == "menu":
            self.menu.draw(screen)
        # ====================================================================

        # Pause ==============================================================
        if self.gameState == "pause":
            self.pause.draw(screen)
        # ====================================================================
        
        # Volume =============================================================
        if self.gameState == "volume":
            self.volume.draw(screen)
        # ====================================================================
        
        # Credits ============================================================
        if self.gameState == "credits":           
            self.credits.draw(screen)
        # ====================================================================
        
        # Game ===============================================================
        elif self.gameState == "game":
            # erase screen
            screen.fill(BLACK)

            # draw background - since the background is scrolling
            # we shall draw two side by side to prevent the background from ending
            # this way it repeats itself
            screen.blit(self.backg.image,(self.backg.x,self.backg.y))
            screen.blit(self.backg.image,(self.backg.x + self.backg.width,self.backg.y))
                           
            # draw sprites onto the screen
            self.userSprites.draw(screen)
            self.laserSprites.draw(screen)
            self.aiSprites.draw(screen)
            self.powerUpSprites.draw(screen)

            
            # drawing text
            font = pygame.font.SysFont("Arial", 25)
            shieldTxt = font.render("Shield: " + str(self.userShip.shield), True, WHITE)
            scoreTxt = font.render("Score: " + str(self.score), True, WHITE)
            screen.blit(shieldTxt, [0,0])
            screen.blit(scoreTxt,  [0,30])           
            
            # animations
            self.backg.scroll(1)          # update background
            self.userShip.animate()       # update animation
            for enemy in self.aiSprites:
                enemy.animate()       # update animation
            for powerUp in self.powerUpSprites:
                powerUp.animate()
        # ====================================================================
    
        # Game Over ==========================================================

        elif self.gameState == "gameOver":
        
            # display game over and continue text
            font80      = pygame.font.SysFont("Arial", 80)
            font30      = pygame.font.SysFont("Arial", 30)
            gameOverTxt = font80.render("Game Over!", True, WHITE)
            continueTxt = font30.render("(Press Enter to restart, Escape to exit)", True, WHITE)
            
            screen.blit(gameOverTxt, [WINDOW_WIDTH/2-gameOverTxt.get_width()/2, 
                        WINDOW_HEIGHT/2-gameOverTxt.get_height()/2])
            screen.blit(continueTxt, [WINDOW_WIDTH/2-continueTxt.get_width()/2, 
                        WINDOW_HEIGHT/2-continueTxt.get_height()/2+55])
            pygame.display.update()
        else:
        
            pass # throw exception!!
 def showCredits(self):
     credits = Credits(self)
     credits.show()
示例#35
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""

    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set background color to black
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()

        #
        # 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()
        # check if particles should be enabled
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()
        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            # 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)
        elif base.appRunner:
            # As when the application is started as appRunner instance
            # it doesn't respect our loadPrcFile configurations specific
            # to the window, hence we need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                #TODO: Check for all window specific variables like
                #      fullscreen, screen size, title and window
                #      decoration that you have in your configuration
                #      and set them by your own.
                if mainConfig.getVariableName(dec) == "fullscreen":
                    if not mainConfig.getDeclaration(dec).getBoolWord(0): break
                    # 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)
                    break

        # 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):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Start", self.request, ["CharSelection"])
        self.accept("Menu-Credits", self.request, ["Credits"])
        self.accept("Menu-Quit", self.quit)
        self.ignore("KoScreen-Back")
        self.koScreen.hide()
        self.menu.show()
        if self.menuMusic.status() != AudioSound.PLAYING:
            self.menuMusic.play()
        if self.fightMusic.status() == AudioSound.PLAYING:
            self.fightMusic.stop()

    def exitMenu(self):
        self.ignore("Menu-Start")
        self.ignore("Menu-Credits")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterCredits(self):
        self.accept("Credits-Back", self.request, ["Menu"])
        self.koScreen.hide()
        self.credits.show()

    def exitCredits(self):
        self.ignore("Credits-Back")
        self.credits.hide()

    def enterCharSelection(self):
        self.accept("CharSelection-Back", self.request, ["Menu"])
        self.accept("CharSelection-Start", self.request, ["LevelSelection"])
        self.charSelection.show()

    def exitCharSelection(self):
        self.ignore("CharSelection-Start")
        self.ignore("CharSelection-Back")
        self.charSelection.hide()
        self.selectedChar1 = self.charSelection.selectedCharacter1
        self.selectedChar2 = self.charSelection.selectedCharacter2

    def enterLevelSelection(self):
        self.accept("LevelSelection-Back", self.request, ["CharSelection"])
        self.accept("LevelSelection-Start", self.request, ["Game"])
        self.levelSelection.show()

    def exitLevelSelection(self):
        self.ignore("LevelSelection-Start")
        self.ignore("LevelSelection-Back")
        self.levelSelection.hide()

    def enterGame(self):
        # main game code should be called here
        self.arena = Arena(self.levelSelection.selectedLevel)
        self.arena.start()
        self.camera.setPos(0, -5, 1.25)
        self.player = Player(0, self.selectedChar1, "p1")
        self.player2 = Player(1, self.selectedChar2, "p2")
        self.player.setEnemy(self.player2.collisionNodeName)
        self.player2.setEnemy(self.player.collisionNodeName)
        self.player.start(self.arena.getStartPos(1))
        self.player2.start(self.arena.getStartPos(2))
        self.taskMgr.add(self.updateWorldCam, "world camera update task")
        self.accept("gameOver", self.gameOver)
        self.hud.show()
        def lifeChanged(charId, health):
            base.messenger.send(
                "hud_setLifeBarValue",
                [charId, health])
        self.accept("lifeChanged", lifeChanged)
        hide_cursor()
        if self.fightMusic.status() != AudioSound.PLAYING:
            self.fightMusic.play()
        if self.menuMusic.status() == AudioSound.PLAYING:
            self.menuMusic.stop()

    def exitGame(self):
        # cleanup for game code
        self.taskMgr.remove("world camera update task")
        self.player.stop()
        self.player2.stop()
        del self.player
        del self.player2
        self.arena.stop()
        self.ignore("gameOver")
        self.ignore("lifeChanged")
        self.hud.hide()

    #
    # FSM PART END
    #

    #
    # BASIC FUNCTIONS
    #
    def gameOver(self, LoosingCharId):
        show_cursor()
        winningChar = 1
        if LoosingCharId == 0:
            winningChar = 2
        self.accept("KoScreen-Back", self.request, ["Credits"])
        self.koScreen.show(winningChar)

    def updateWorldCam(self, task):
        playerVec = self.player.getPos() - self.player2.getPos()
        playerDist = playerVec.length()
        x = self.player.getX() + playerDist / 2.0
        self.camera.setX(x)

        zoomout = False
        if not self.cam.node().isInView(self.player.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not self.cam.node().isInView(self.player2.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not zoomout:
            if self.camera.getY() < -5:
                camPosUpdate = 2 * globalClock.getDt()
                self.camera.setY(self.camera, camPosUpdate)
        return task.cont

    def __escape(self):
        if self.state == "Menu":
            self.quit()
        elif self.state == "LevelSelection":
            self.request("CharSelection")
        else:
            self.request("Menu")

    def quit(self):
        """This function will stop the application"""
        self.userExit()

    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

        #TODO: get values of configurations here
        particles = "#f" if not base.particleMgrEnabled else "#t"
        volume = str(round(base.musicManager.getVolume(), 2))
        mute = "#f" if base.AppHasAudioFocus else "#t"
        #TODO: add any configuration variable name that you have added
        customConfigVariables = [
            "", "particles-enabled", "audio-mute", "audio-volume"]
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(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: particles-enabled and audio-mute are custom variables and
            #       have to be loaded by hand at startup
            # Particles
            page.makeDeclaration("particles-enabled", particles)
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", mute)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("%s Pandaconfig"%appName)
            # 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")
            # particles
            page.makeDeclaration("particles-enabled", "#t")
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", "#f")
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
示例#36
0
    def __init__(self, app, files=[]):

        Gtk.Window.__init__(self, title="Saludame", application=app)

        self.__new_game = ''
        self.__data = {}

        self.set_icon_from_file(os.path.join(BASEPATH, "assets/saludame.svg"))
        self.set_resizable(False)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.maximize()

        self.size = (800, 600)

        self.headerBar = Gtk.HeaderBar()
        self.headerBar.get_style_context().add_class("header")
        self.headerBar.set_show_close_button(True)
        self.headerBar.set_title(_("Saludame"))
        self.set_titlebar(self.headerBar)

        self.startup_window = StartupWindow(self._start_cb, self._load_last_cb)
        self.pygame_canvas = PygameCanvas()
        self.health_library = ContentWindow()
        self.guides = GuidesWindow()
        self.credits = Credits()

        self.notebook = Gtk.Notebook()
        self.notebook.get_style_context().add_class("mynotebook")

        self.notebook.append_page(self.startup_window,
                                  Gtk.Label(_("Activity")))
        self.notebook.append_page(self.pygame_canvas, Gtk.Label(_("Game")))
        self.notebook.append_page(self.health_library,
                                  Gtk.Label(_("Health Library")))
        self.notebook.append_page(self.guides, Gtk.Label(_("Guides")))
        self.notebook.append_page(self.credits, Gtk.Label(_("Credits")))

        self.add(self.notebook)

        logging.debug("Create main")

        self.game = Main()
        self.game.set_game_over_callback(self.game_over_callback)
        game.set_library_function = self.set_library

        self.healt_toolbar = self.health_library.get_toolbar()
        self.game_toolbar = self.get_game_toolbar()
        self.headerBar.pack_start(self.healt_toolbar)
        self.headerBar.pack_start(self.game_toolbar)

        self.notebook.connect('switch_page', self.__switch_page)
        self.connect("delete-event", self.__salir)

        self.connect("realize", self.__realize)

        self.show_all()

        self.notebook.get_children()[1].hide()
        self.healt_toolbar.hide()
        self.game_toolbar.hide()

        self.notebook.set_current_page(0)
 def showCredits(self):
     credits = Credits(self)
     credits.show()
示例#38
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        base.notify.info("Version {}".format(versionstring))
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # get the displays width and height for later usage
        self.dispWidth = self.pipe.getDisplayWidth()
        self.dispHeight = self.pipe.getDisplayHeight()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if particles should be enabled
        # NOTE: If you use the internal physics engine, this always has
        #       to be enabled!
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # 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(self.dispWidth, self.dispHeight)
            # request the new properties
            base.win.requestProperties(props)
            # Set the config variables so we correctly store the
            # new size and fullscreen setting later
            winSize = ConfigVariableString("win-size")
            winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
            fullscreen = ConfigVariableBool("fullscreen")
            fullscreen.setValue(True)
            # Render a frame to make sure the fullscreen is applied
            # before we do anything else
            self.taskMgr.step()
            # make sure to propagate the new aspect ratio properly so
            # the GUI and other things will be scaled appropriately
            aspectRatio = self.dispWidth / self.dispHeight
            self.adjustWindowAspectRatio(aspectRatio)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        # automatically safe configuration at application exit
        #base.exitFunc = self.__writeConfig

        #
        # INITIALIZE GAME CONTENT
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # EVENT HANDLING
        #
        # By default we accept the escape key
        self.accept("escape", self.__escape)

        #
        # ENTER GAMES INITIAL FSM STATE
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Start", self.request, ["CharSelection"])
        self.accept("Menu-Credits", self.request, ["Credits"])
        self.accept("Menu-Quit", self.userExit)
        self.ignore("KoScreen-Back")
        self.koScreen.hide()
        self.menu.show()
        if self.menuMusic.status() != AudioSound.PLAYING:
            self.menuMusic.play()
        if self.fightMusic.status() == AudioSound.PLAYING:
            self.fightMusic.stop()

    def exitMenu(self):
        self.ignore("Menu-Start")
        self.ignore("Menu-Credits")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterCredits(self):
        self.accept("Credits-Back", self.request, ["Menu"])
        self.koScreen.hide()
        self.credits.show()

    def exitCredits(self):
        self.ignore("Credits-Back")
        self.credits.hide()

    def enterCharSelection(self):
        self.accept("CharSelection-Back", self.request, ["Menu"])
        self.accept("CharSelection-Start", self.request, ["LevelSelection"])
        self.charSelection.show()

    def exitCharSelection(self):
        self.ignore("CharSelection-Start")
        self.ignore("CharSelection-Back")
        self.charSelection.hide()
        self.selectedChar1 = self.charSelection.selectedCharacter1
        self.selectedChar2 = self.charSelection.selectedCharacter2

    def enterLevelSelection(self):
        self.accept("LevelSelection-Back", self.request, ["CharSelection"])
        self.accept("LevelSelection-Start", self.request, ["Game"])
        self.levelSelection.show()

    def exitLevelSelection(self):
        self.ignore("LevelSelection-Start")
        self.ignore("LevelSelection-Back")
        self.levelSelection.hide()

    def enterGame(self):
        # main game code should be called here
        self.arena = Arena(self.levelSelection.selectedLevel)
        self.arena.start()
        self.camera.setPos(0, -5, 1.25)
        self.player = Player(0, self.selectedChar1, "p1")
        self.player2 = Player(1, self.selectedChar2, "p2")
        self.player.setEnemy(self.player2.collisionNodeName)
        self.player2.setEnemy(self.player.collisionNodeName)
        self.player.start(self.arena.getStartPos(1))
        self.player2.start(self.arena.getStartPos(2))
        self.taskMgr.add(self.updateWorldCam, "world camera update task")
        self.accept("gameOver", self.gameOver)
        self.hud.show()

        def lifeChanged(charId, health):
            base.messenger.send("hud_setLifeBarValue", [charId, health])

        self.accept("lifeChanged", lifeChanged)
        hide_cursor()
        if self.fightMusic.status() != AudioSound.PLAYING:
            self.fightMusic.play()
        if self.menuMusic.status() == AudioSound.PLAYING:
            self.menuMusic.stop()

    def exitGame(self):
        # cleanup for game code
        self.taskMgr.remove("world camera update task")
        self.player.stop()
        self.player2.stop()
        del self.player
        del self.player2
        self.arena.stop()
        self.ignore("gameOver")
        self.ignore("lifeChanged")
        self.hud.hide()

    #
    # FSM PART END
    #

    #
    # BASIC FUNCTIONS
    #
    def gameOver(self, LoosingCharId):
        show_cursor()
        winningChar = 1
        if LoosingCharId == 0:
            winningChar = 2
        self.accept("KoScreen-Back", self.request, ["Credits"])
        self.koScreen.show(winningChar)

    def updateWorldCam(self, task):
        playerVec = self.player.getPos() - self.player2.getPos()
        playerDist = playerVec.length()
        x = self.player.getX() + playerDist / 2.0
        self.camera.setX(x)

        zoomout = False
        if not self.cam.node().isInView(self.player.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not self.cam.node().isInView(self.player2.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not zoomout:
            if self.camera.getY() < -5:
                camPosUpdate = 2 * globalClock.getDt()
                self.camera.setY(self.camera, camPosUpdate)
        return task.cont

    def __escape(self):
        """Handle user escape key klicks"""
        if self.state == "Menu":
            # In this state, we will stop the application
            self.userExit()
        elif self.state == "LevelSelection":
            self.request("CharSelection")
        else:
            # In every other state, we switch back to the Menu state
            self.request("Menu")

    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

        #
        #TODO: add any configuration variable names that you have added
        #      to the dictionaries in the next lines. Set the current
        #      configurations value as value in this dictionary and it's
        #      name as key.
        configVariables = {
            # set the window size in the config file
            "win-size":
            ConfigVariableString(
                "win-size", "{} {}".format(self.dispWidth,
                                           self.dispHeight)).getValue(),
            # set the default to fullscreen in the config file
            "fullscreen":
            "#t"
            if ConfigVariableBool("fullscreen", True).getValue() else "#f",
            # particles
            "particles-enabled":
            "#t" if self.particleMgrEnabled else "#f",
            # audio
            "audio-volume":
            str(round(self.musicManager.getVolume(), 2)),
            "audio-music-active":
            "#t"
            if ConfigVariableBool("audio-music-active").getValue() else "#f",
            "audio-sfx-active":
            "#t"
            if ConfigVariableBool("audio-sfx-active").getValue() else "#f",
            # logging
            "notify-output":
            os.path.join(basedir, "game.log"),
            # window
            "framebuffer-multisample":
            "#t" if ConfigVariableBool("framebuffer-multisample").getValue()
            else "#f",
            "multisamples":
            str(ConfigVariableInt("multisamples", 8).getValue()),
            "texture-anisotropic-degree":
            str(ConfigVariableInt("texture-anisotropic-degree").getValue()),
            "textures-auto-power-2":
            "#t" if ConfigVariableBool("textures-auto-power-2",
                                       True).getValue() else "#f",
        }

        page = None
        # Check if we have an existing configuration file
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(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 configVariables.keys():
                    removeDecls.append(page.modifyDeclaration(dec))
            for dec in removeDecls:
                page.deleteDeclaration(dec)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("Application Config")

        # always write custom configurations
        for key, value in configVariables.items():
            page.makeDeclaration(key, value)
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
示例#39
0
    def __init__(self):

        # variables -----------------------------------------------

        # load background
        self.backg = Background(BKG_FOLDER + "stars.png")

        # set initial score
        self.score = 0

        # load sound and music volume from file
        # if there's a problem with the file, simply create a new one with default values
        try:
            volume = pickle.load(open("volume.p", "rb"))
        except:
            volume = {"sound": 100, "music": 30}
            pickle.dump(volume, open("volume.p", "wb"))

        # sounds
        self.laserSnd = pygame.mixer.Sound(SND_FOLDER + "laser.wav")
        self.explodeSnd = pygame.mixer.Sound(SND_FOLDER + "explosion.wav")
        self.powerUpSnd = pygame.mixer.Sound(SND_FOLDER + "powerUp.wav")

        # put everything into a list so it's easier to change the volume
        # the list elements are the same objects as the initial ones
        # as python copies by reference and not by value (I would have
        # preferred to use pointers, to avoid ambiguity, but oh well...)
        self.sounds = [self.laserSnd, self.explodeSnd, self.powerUpSnd]

        # set volume for all sound objects
        for snd in self.sounds:
            snd.set_volume(volume["sound"] / 100.)  # set new volume

        # music
        self.music = pygame.mixer.music.load(MUS_FOLDER +
                                             "reachingForTheSun.mp3")
        pygame.mixer.music.play(-1)  # loop
        pygame.mixer.music.set_volume(volume["music"] / 100.)

        # creating user ship
        self.userShip1 = ShipY001()
        self.userShip2 = ShipY002()
        self.userShip3 = ShipY003()
        self.userShip1.speed = 10
        self.userShip2.speed = 10
        self.userShip3.speed = 10
        # group of all sprites
        self.userSprites1 = pygame.sprite.Group()
        self.userSprites2 = pygame.sprite.Group()
        self.userSprites3 = pygame.sprite.Group()
        self.laserSprites = pygame.sprite.Group()
        self.aiSprites = pygame.sprite.Group()
        self.powerUpSprites = pygame.sprite.Group()

        # add to groups
        self.userSprites1.add(self.userShip1)
        self.userSprites2.add(self.userShip2)
        self.userSprites3.add(self.userShip3)

        # Creating main menu
        self.menu = Menu(["Quit", "Credits", "Volume", "Play"], self.backg)

        # Creating game_mode
        self.mode = Menu(["HELL", "HARD", "NORMAL"], self.backg)
        self.modeBack = 0

        # Creating pause menu (could be generated later, but shouldn't impact performance)
        self.pause = Menu(["Quit", "Volume", "Restart", "Continue"],
                          self.backg)

        # Creating volume menu (could be generated later, but shouldn't impact performance)
        self.volume = Volume(self.backg, volume)
        self.volumeBack = 0  # some stupid flag to tell us whether we came from the main menu
        # of from the pause menu

        # Creating credits
        self.credits = Credits([
            "Sound: Obtained from Freesound",
            "Music: 'Reaching for the Sun' by Deshiel and Bacon92",
            "Graphics: Filipa Silva", "Code: Alexandre Lopes"
        ], self.backg)

        # gameState
        # Available states: menu, credits ,game, gameOver
        self.gameState = "menu"
示例#40
0
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        base.notify.info("Version {}".format(versionstring))
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # get the displays width and height for later usage
        self.dispWidth = self.pipe.getDisplayWidth()
        self.dispHeight = self.pipe.getDisplayHeight()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if particles should be enabled
        # NOTE: If you use the internal physics engine, this always has
        #       to be enabled!
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # 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(self.dispWidth, self.dispHeight)
            # request the new properties
            base.win.requestProperties(props)
            # Set the config variables so we correctly store the
            # new size and fullscreen setting later
            winSize = ConfigVariableString("win-size")
            winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
            fullscreen = ConfigVariableBool("fullscreen")
            fullscreen.setValue(True)
            # Render a frame to make sure the fullscreen is applied
            # before we do anything else
            self.taskMgr.step()
            # make sure to propagate the new aspect ratio properly so
            # the GUI and other things will be scaled appropriately
            aspectRatio = self.dispWidth / self.dispHeight
            self.adjustWindowAspectRatio(aspectRatio)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        # automatically safe configuration at application exit
        #base.exitFunc = self.__writeConfig

        #
        # INITIALIZE GAME CONTENT
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # EVENT HANDLING
        #
        # By default we accept the escape key
        self.accept("escape", self.__escape)

        #
        # ENTER GAMES INITIAL FSM STATE
        #
        self.request("Menu")
示例#41
0
def credits(screen):
    return Credits(screen,menu)
示例#42
0
class SaludameWindow(Gtk.ApplicationWindow):
    def __init__(self, app, files=[]):

        Gtk.Window.__init__(self, title="Saludame", application=app)

        self.__new_game = ''
        self.__data = {}

        self.set_icon_from_file(os.path.join(BASEPATH, "assets/saludame.svg"))
        self.set_resizable(False)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.maximize()

        self.size = (800, 600)

        self.headerBar = Gtk.HeaderBar()
        self.headerBar.get_style_context().add_class("header")
        self.headerBar.set_show_close_button(True)
        self.headerBar.set_title(_("Saludame"))
        self.set_titlebar(self.headerBar)

        self.startup_window = StartupWindow(self._start_cb, self._load_last_cb)
        self.pygame_canvas = PygameCanvas()
        self.health_library = ContentWindow()
        self.guides = GuidesWindow()
        self.credits = Credits()

        self.notebook = Gtk.Notebook()
        self.notebook.get_style_context().add_class("mynotebook")

        self.notebook.append_page(self.startup_window,
                                  Gtk.Label(_("Activity")))
        self.notebook.append_page(self.pygame_canvas, Gtk.Label(_("Game")))
        self.notebook.append_page(self.health_library,
                                  Gtk.Label(_("Health Library")))
        self.notebook.append_page(self.guides, Gtk.Label(_("Guides")))
        self.notebook.append_page(self.credits, Gtk.Label(_("Credits")))

        self.add(self.notebook)

        logging.debug("Create main")

        self.game = Main()
        self.game.set_game_over_callback(self.game_over_callback)
        game.set_library_function = self.set_library

        self.healt_toolbar = self.health_library.get_toolbar()
        self.game_toolbar = self.get_game_toolbar()
        self.headerBar.pack_start(self.healt_toolbar)
        self.headerBar.pack_start(self.game_toolbar)

        self.notebook.connect('switch_page', self.__switch_page)
        self.connect("delete-event", self.__salir)

        self.connect("realize", self.__realize)

        self.show_all()

        self.notebook.get_children()[1].hide()
        self.healt_toolbar.hide()
        self.game_toolbar.hide()

        self.notebook.set_current_page(0)

    def __realize(self, widget):
        GLib.timeout_add(300, self.__get_allocation)

    def __get_allocation(self):
        a = self.startup_window.get_allocation()
        self.size = (a.width, a.height)
        self.startup_window.set_welcome(self.size)

    def __switch_page(self, widget, widget_child, indice):
        tab = self.notebook.get_tab_label(self.notebook.get_children()[indice])
        item = tab.get_text().decode(
            "utf-8")  # convert to unicode because GTK is always utf-8

        if item == _("Game"):
            self.healt_toolbar.hide()
            self.game_toolbar.show_all()

            if self.__new_game == 'new':
                self.game.started = False
                self.game.gender = self.__data.get('gender', '')
                self.game.name = self.__data.get('name', '')
                r = self.startup_window.get_allocation()
                GLib.timeout_add(200, self.game.main, (r.width, r.height),
                                 False)

            elif self.__new_game == 'load':
                self.game.started = False
                r = self.startup_window.get_allocation()
                GLib.timeout_add(200, self.game.main, (r.width, r.height),
                                 True)

            else:
                self.game.windows_controller.reload_main = True  # Repaints the whole screen

            self.__new_game = ''
            self.__data = {}

        elif item == _("Health Library"):
            self.healt_toolbar.show_all()
            self.game_toolbar.hide()
        else:
            self.healt_toolbar.hide()
            self.game_toolbar.hide()

        if item == _("Credits"):
            self.credits.reload()

    def _start_cb(self, gender, name):
        self.__new_game = 'new'
        self.__data = {'gender': gender, 'name': name}
        self.startup_window.set_welcome()
        self.notebook.get_children()[1].show()
        self.notebook.set_current_page(1)

    def set_library(self, link, anchor=None):
        self.notebook.set_current_page(2)
        self.health_library.set_url(link, anchor)

    def _load_last_cb(self, button):
        self.__new_game = 'load'
        self.notebook.get_children()[1].show()
        self.notebook.set_current_page(1)

    def game_over_callback(self):
        self.startup_window.set_welcome()
        self.notebook.get_children()[1].hide()
        self.notebook.set_current_page(0)

    def __salir(self, widget=None, senial=None):
        sys.exit(0)

    def get_game_toolbar(self):
        toolbar = Gtk.Toolbar()

        # Music Volume scale
        min = 0
        max = 10
        step = 1
        default = 3

        image = Gtk.Image()
        image.set_from_file(
            os.path.join(BASEPATH, "assets/music/music_icon.png"))
        image.show()

        tool_item = Gtk.ToolItem()
        tool_item.set_expand(False)
        tool_item.add(image)
        tool_item.show()
        toolbar.insert(tool_item, -1)

        adj = Gtk.Adjustment(default, min, max, step)
        scale = Gtk.HScale()
        scale.set_adjustment(adj)
        scale.set_size_request(240, 15)
        scale.set_draw_value(False)
        scale.connect("value-changed", self.game.volume_changed)
        scale.show()

        tool_item = Gtk.ToolItem()
        tool_item.set_expand(False)
        tool_item.add(scale)
        tool_item.show()
        toolbar.insert(tool_item, -1)

        toolbar.show()
        return toolbar