Ejemplo n.º 1
0
 def player_hit(self):
     """Method called when the player is hit by an ennemy ship or bullet.
     Make a recovery time for the ship after collision"""
     if not(self.playership.recover):
         AudioManager.play_sound("explosion")
         self.life -= 1
         self.playership.recover = True
         self.score_multiplier = 1
Ejemplo n.º 2
0
 def destroy(self):
     """Called when the ennemy is destroyed. Might spawn a bonus."""
     AudioManager.play_sound("explosion2")
     if random.random() < POWERUP_SPAWN_RATE:
         ef = get_random_powerup()()
         hitbox = Rectangle(self.hitbox.x, self.hitbox.y, 32, 32)
         pw = WorldPowerUp(hitbox, ef,
                           random.random() < POWERUP_MYSTERY_RATE)
         self.world.powerups.append(pw)
Ejemplo n.º 3
0
 def apply_effect(self, effect):
     AudioManager.play_sound("powerup")
     if effect.effecttype is not None and effect.effecttype in self.powerup_sockets:
         self.powerup_sockets[effect.effecttype].remove(self)
         self.powerup_sockets.pop(effect.effecttype)
     effect.apply(self)
     self.powerup_sockets[effect.effecttype] = effect
     if effect.time > 0:
         print("BITE")
         self.time_effects[effect] = effect.time
Ejemplo n.º 4
0
 def handle_event(self, event):
     if event.type == SDL_QUIT:
         sys.exit("Closing the game...")
         self.running = False
     elif event.type == SDL_KEYDOWN and event.key.repeat == 0:
         key = event.key.keysym.sym
         if key == SDLK_UP:
             self.world.playership.vely = -self.playership.maxspeed
         elif key == SDLK_DOWN:
             self.world.playership.vely = self.playership.maxspeed
         elif key == SDLK_LEFT:
             self.world.playership.velx = -self.playership.maxspeed
         elif key == SDLK_RIGHT:
             self.world.playership.velx = self.playership.maxspeed
         elif key == SDLK_SPACE:
             self.shooting = True
         elif key == SDLK_p and self.playership.shootingdelay > 0:
             self.playership.shootingdelay /= 2
         elif key == SDLK_m:
             self.playership.shootingdelay *= 2
         elif key == SDLK_ESCAPE:
             self.running = False
         elif key == SDLK_F1:
             self.debug_info = not self.debug_info
         elif key == SDLK_F2:
             # self.pause = not self.pause
             AudioManager.play_sound("bleep")
             pauseState = Pause(self.graphics, self)
             pauseState.run()
             AudioManager.play_sound("bleep")
             self.clock.tick()
         elif key == SDLK_e:
             self.test_effect1.apply(self.playership)
         elif key == SDLK_r:
             self.test_effect2.apply(self.playership)
     elif event.type == SDL_KEYUP:
         key = event.key.keysym.sym
         if key == SDLK_RIGHT:
             if self.playership.velx > 0:
                 self.playership.velx = 0
         elif key == SDLK_LEFT:
             if self.playership.velx < 0:
                 self.playership.velx = 0
         elif key == SDLK_DOWN:
             if self.playership.vely > 0:
                 self.playership.vely = 0
         elif key == SDLK_UP:
             if self.playership.vely < 0:
                 self.playership.vely = 0
         elif key == SDLK_SPACE:
             self.shooting = False
Ejemplo n.º 5
0
 def __init__(self, window, view, parent_object = None):
     QGraphicsScene.__init__(self, window)
     self.application = window.application
     self.window = window
     self.view = view
     self.parent_object = parent_object
     if parent_object is None:
         self.update_timer = QTimer(self)
         self.update_timer.timeout.connect(self.update_loop)
         # MMF 1.5 is 50 FPS
         self.update_timer.start((1 / 50.0) * 1000)
         self.values = {}
         self.strings = {}
         self.players = [Player(START_LIVES) for _ in xrange(4)]
         self.audio = AudioManager()
         start_index = 0
         if FAST_CONNECT:
             start_index = 4
         self.set_frame(start_index, True)
     else:
         scene = parent_object.scene
         self.values = scene.values
         self.strings = scene.strings
         self.players = scene.players
         self.audio = scene.audio
     self.key_presses = []
     self.key_downs = []
     self.mouse_downs = []
Ejemplo n.º 6
0
    def __init__(self):
        """Create the main menu."""
        super(Bombercan, self).__init__('BomberCan', 500, 500, 80)

        # Play BGM
        self.audio = AudioManager()
        self.audio.play('bombercan.wav', loop=True)
            
        # Display the main menu
        self.menu = MenuScene(
                parent=self,
                style={},
                audio=self.audio,
                key_up=self.key_up,
                key_down=self.key_down,
                on_game_start=self.game_start
                )

        # Prepare the end scene
        self.end = EndScene(
                parent=self,
                style={},
                key_up=self.key_up,
                key_down=self.key_down,
                on_game_reset=self.game_reset
                )

        self.game_reset()
Ejemplo n.º 7
0
 def update(self, delta):
     if self.pause:
         AudioManager.set_music_volume(0.1)
         return
     if self.shooting:
         self.world.playership.shoot()
     if not(self.pause):
         AudioManager.set_music_volume(1)
     self.world.update(delta)
     self.running = self.running and not self.world.gameover
     self.debug_fps = 1 / delta
     if self.world.standby_ennemies == [] and self.world.active_ennemies == [] and self.world.bullets == []:
         self.timerEnd += delta
         if self.timerEnd >= 3:
             self.score.add_score(self.world.score)
             self.score.save()
             self.running = False
Ejemplo n.º 8
0
 def update(self, delta):
     if self.pause:
         AudioManager.set_music_volume(0.1)
         return
     if self.shooting:
         self.world.playership.shoot()
     if not(self.pause):
         AudioManager.set_music_volume(1)
     self.world.update(delta)
     self.running = self.running and not self.world.gameover
     self.debug_fps = 1 / delta
     # new ennemies
     if self.world.active_ennemies == [] and self.world.standby_ennemies == [] and self.currentlevel < 4:
         self.currentlevel += 1
         level = Level(self.currentlevel, self.world, self.world.camera.y, 20)
         self.world.standby_ennemies = level.level
     elif self.world.active_ennemies == [] and self.world.standby_ennemies == [] and self.currentlevel == 4:
         level = Level(self.currentlevel, self.world, self.world.camera.y, 20)
         self.world.standby_ennemies = level.level
Ejemplo n.º 9
0
 def __init__(self):
     ShowBase.__init__(self)
     self.camera.setPosHpr(0, -12, 8, 0, -35, 0)
     self.disableMouse()
     self.tourBlanc = True
     self.Plateau = Plateau(self.render, self.loader)
     self.IA = bloc_IA(self.Plateau)
     self.son = AudioManager(self.loader)
     self.menu = Menu(self.loader, self.Plateau, self.son, self.IA)
     #mise en place des raccourcis
     self.accept('1', lambda: self.Plateau.jouerMouvement(0))
     self.accept('2', lambda: self.Plateau.jouerMouvement(1))
     self.accept('3', lambda: self.Plateau.jouerMouvement(2))
     self.accept('4', lambda: self.Plateau.jouerMouvement(3))
     self.accept('5', lambda: self.Plateau.jouerMouvement(4))
     self.accept('6', lambda: self.Plateau.jouerMouvement(5))
     self.accept('7', lambda: self.Plateau.jouerMouvement(6))
     self.accept('8', lambda: self.Plateau.jouerMouvement(7))
     self.accept('9', lambda: self.Plateau.jouerMouvement(8))
     self.accept('r', self.Plateau.reset)
     self.accept('a', self.Plateau.annulerMouvement)
     self.accept('d', self.Plateau.dechargerGraphismes)
     self.accept('c', self.Plateau.chargerGraphismes)
     self.accept('t', self.test)
Ejemplo n.º 10
0
    def __init__(self, token=None, cs=BrianCS, use_voice_receive_hooks=False):

        """
        Create a new bot instance.

        token is the bot token to authenticate with.
            If it is None, the token will be read from the configuration file instead.
        cs is the class of the conversation simulator to use. It must be a subclass of
            conversation.ConversationSimulator(). Defaults to conversation.BrianCS().
        """

        super().__init__()

        self._autosave_active = False
        self._connected_futures = []

        self.event(self.on_message)
        self.event(self.on_ready)

        self.command_parser = cmdsys.CommandParser()
        self.config = ConfigManager(path=self.CFG_PATH / "bot.xml", requireVersion=2)
        self.db = DatabaseManager(path=self.CFG_PATH / "db")
        self.db.register_model(BlockedUser)
        self.db.register_model(BlockedChannel)
        self.db.register_model(PinChannel)
        self.db.register_model(AuditLogChannel)
        self.db.register_model(TimeoutRole)
        self.db.register_model(TimeoutCount)
        self.db.register_model(PinReactionSettings)
        self.db.register_model(VoiceClientSettings)

        self.audio = AudioManager(self)
        self.cs = cs(self, self.config)
        self.voice_receive =  None
        if use_voice_receive_hooks:
            rhasspy_address = (self.config.getElementText("bot.network.rhasspy.host"), self.config.getElementInt("bot.network.rhasspy.port"))
            self.voice_receive = ConnectionListener(self, RhasspyRE(rhasspy_address))
            self.logger.warn("Voice receive hooks have been ENABLED. This is considered an experimental feature and should be used with great caution.")

        self.cidsl_parser = interaction.DSLParser()
        self.cidsl = interaction.DSLInterpreter(self)
        self.cidsl.registerAudioEngine(self.audio)
        for i in os.listdir("chat/scripts"):
            p = os.path.join("chat/scripts", i)
            if (not os.path.isfile(p)) or (not p.endswith(".ci")):
                continue
            f = open(p, "r")
            self.logger.debug("Loading CIDSL script at %s..." % p)
            try:
                self.cidsl.compile(self.cidsl_parser.parse("\n".join(f.readlines())))
            except:
                self.logger.exception("Exception occured while loading CIDSL script at %s: " % p)
            f.close()

        cmdsys.environment.update_environment({
            "client": self,
            "config": self.config,
            "database": self.db,
            "audio": self.audio,
            "conversation_simulator": self.cs,
            "voice_receive": self.voice_receive,
            "cidsl": self.cidsl
            })

        self.load_commands()

        self.token = token or self.config.getElementText("bot.token")
Ejemplo n.º 11
0
class ProtosBot(Client):

    """
    ProtOS Discord Bot
    """

    logger = logging.getLogger("Bot")

    CMD_PATH = Path("commands")
    CFG_PATH = Path("config")
    SOUND_DIR = Path("sounds")

    def __init__(self, token=None, cs=BrianCS, use_voice_receive_hooks=False):

        """
        Create a new bot instance.

        token is the bot token to authenticate with.
            If it is None, the token will be read from the configuration file instead.
        cs is the class of the conversation simulator to use. It must be a subclass of
            conversation.ConversationSimulator(). Defaults to conversation.BrianCS().
        """

        super().__init__()

        self._autosave_active = False
        self._connected_futures = []

        self.event(self.on_message)
        self.event(self.on_ready)

        self.command_parser = cmdsys.CommandParser()
        self.config = ConfigManager(path=self.CFG_PATH / "bot.xml", requireVersion=2)
        self.db = DatabaseManager(path=self.CFG_PATH / "db")
        self.db.register_model(BlockedUser)
        self.db.register_model(BlockedChannel)
        self.db.register_model(PinChannel)
        self.db.register_model(AuditLogChannel)
        self.db.register_model(TimeoutRole)
        self.db.register_model(TimeoutCount)
        self.db.register_model(PinReactionSettings)
        self.db.register_model(VoiceClientSettings)

        self.audio = AudioManager(self)
        self.cs = cs(self, self.config)
        self.voice_receive =  None
        if use_voice_receive_hooks:
            rhasspy_address = (self.config.getElementText("bot.network.rhasspy.host"), self.config.getElementInt("bot.network.rhasspy.port"))
            self.voice_receive = ConnectionListener(self, RhasspyRE(rhasspy_address))
            self.logger.warn("Voice receive hooks have been ENABLED. This is considered an experimental feature and should be used with great caution.")

        self.cidsl_parser = interaction.DSLParser()
        self.cidsl = interaction.DSLInterpreter(self)
        self.cidsl.registerAudioEngine(self.audio)
        for i in os.listdir("chat/scripts"):
            p = os.path.join("chat/scripts", i)
            if (not os.path.isfile(p)) or (not p.endswith(".ci")):
                continue
            f = open(p, "r")
            self.logger.debug("Loading CIDSL script at %s..." % p)
            try:
                self.cidsl.compile(self.cidsl_parser.parse("\n".join(f.readlines())))
            except:
                self.logger.exception("Exception occured while loading CIDSL script at %s: " % p)
            f.close()

        cmdsys.environment.update_environment({
            "client": self,
            "config": self.config,
            "database": self.db,
            "audio": self.audio,
            "conversation_simulator": self.cs,
            "voice_receive": self.voice_receive,
            "cidsl": self.cidsl
            })

        self.load_commands()

        self.token = token or self.config.getElementText("bot.token")

    def load_commands(self):

        """
        (Re)loads commands.
        """

        self.commands = cmdsys.load_commands(self.CMD_PATH)
        for command in self.commands:
            command.client = self

    def run(self):

        """
        Run the bot instance. This call will block.
        """

        self.logger.debug("Starting...")
        super().run(self.token)

    def wait_for_connection(self):

        if self.is_ready():
            f = asyncio.Future()
            f.set_result(True)
            return f
        f = asyncio.Future()
        self._connected_futures.append(f)
        return f

    def log_message(self, msg: Message):

        """
        Logs the message to the console window.
        Includes pretty printer options for server, channel, names/nicknames and role color
        """
        
        logger = self.logger.getChild("MessageLog")

        s = cmdutils.translateString(msg.content)
        a = cmdutils.translateString(msg.author.name)
        if hasattr(msg.author, "nick") and msg.author.nick:
            a = cmdutils.translateString(msg.author.nick) + "/" + a
            
        for i in msg.attachments: #display attachments
            s += "\n    => with attachment:"
            for j in i.items():
                s += "\n       " + j[0] + ": " + str(j[1])

        if isinstance(msg.channel, discord.abc.PrivateChannel): #We received a DM instead of a server message, this means most of our code is not required
            if isinstance(msg.channel, discord.DMChannel):    
                name = msg.channel.recipient.name
            else:
                name = getattr(msg.channel, "name", msg.channel.recipients[0].name)
            
            logger.info("[DM][%s](%s): %s" % (name, a, s))
            return

        color = msg.author.colour.to_rgb() if hasattr(msg.author, "colour") else (0, 0, 0)
        logger.info("[%s][%s](%s): %s" % (msg.guild.name, msg.channel.name, cmdutils.colorText(a, color), s))

    async def on_ready(self):

        """
        Event handler for ready events.

        Finishes initialization and schedules periodic tasks.
        """

        self.logger.info(S_TITLE_VERSION)
        self.logger.info("-"*50)
        self.logger.info("Ready.")

        await asyncio.sleep(3) #wait a short amount of time until we have received all data
        
        self.logger.debug("Starting autosave scheduler...")
        self.loop.create_task(self._autosave())

        game = Game(name= "%s | %s%s" % (S_VERSION, self.config.getElementText("bot.prefix"), "about"))
        await self.change_presence(activity=game)

        for f in self._connected_futures:
            f.set_result(True)

    async def on_message(self, msg: Message):

        """
        Event handler for messages.

        Handles command dispatch through text chat as well as interaction with CIDSL and conversation simulators.
        """

        self.log_message(msg)

        if msg.content.startswith(self.config.getElementText("bot.prefix")):
            responseHandle = ChatResponse(self, msg)
            await self.command_parser.parse_command(responseHandle, self.commands, self)

        else:

            if self.user.mentioned_in(msg) and not msg.author.id == self.user.id:

                await msg.channel.trigger_typing() #makes it seem more real (TODO: we need a way to terminate this if the following code throws an error)

                if self.cidsl.run(msg):
                    return

                #use our MegaHal implementation to get a response

                if self.config.getElementText("bot.chat.aistate") == "off": #AI turned off
                    await msg.channel.send(msg.author.mention + ", Sorry, this feature is unavailable right now. Please try again later.")
                    return

                if msg.guild:
                    #Check if this channel is blocked for AI
                    if len(self.db.get_db_by_message(msg).query(BlockedChannel).filter(channel_id=msg.channel.id)) > 0: #YOU'RE BANNED
                        await msg.channel.send(msg.author.mention + ", " + interaction.confused.getRandom())
                        return

                if not ("<@" + str(self.user.id) + ">" in msg.content or "<@!" + str(self.user.id) + ">" in msg.content): #cheking for group mentions
                    #must be either @here or @everyone... make this a rare occurance
                    if random.random() > 0.01: #only process every 100th message
                        return


                response = await self.cs.respond(msg)

                if self.config.getElementText("bot.chat.aistate") == "passive": #AI in passive mode
                    return

                if isinstance(response, bytes):
                    await msg.channel.send(msg.author.mention + ", " + response.decode()) #post our answer
                else:
                    await msg.channel.send(msg.author.mention + ", " + response)

            elif len(msg.content) > 0 and (not msg.author.id == self.user.id): #we don't want the bot to listen to its own messages

                if self.config.getElementText("bot.chat.aistate") == "off": #AI turned off
                    return

                if msg.guild:
                    #Check if this channel is blocked for AI
                    if len(self.db.get_db_by_message(msg).query(BlockedChannel).filter(channel_id=msg.channel.id)) > 0: #YOU'RE BANNED
                        return

                await self.cs.observe(msg)

                c = msg.content.lower()
                if " ram " in c or c.startswith("ram ") or c.endswith(" ram") or c == "ram": #Make the bot sometimes respond to its name when it comes up

                    for i in msg.guild.emojis: #Always try to add a "Ram" emoji if available
                        if i.name.lower() == "ram":
                            await msg.add_reaction(i)
                            break

                    if random.random() <= 0.001: #Responds with a probability of 1:1000
                        await msg.channel.send(interaction.mentioned.getRandom()) #IT HAS BECOME SELF AWARE!!!

    async def on_voice_state_update(self, what, before, after):

        before_channel = before.channel
        after_channel = after.channel

        #Voice line handling
        if (after_channel and after_channel != before_channel): #if the user is connected and has changed his voice channel (this may mean he just joined)
            if what.guild.voice_client and (after_channel == what.guild.voice_client.channel): #we are in the same channel as our target

                #Use new dynamic voiceline handling (voicelines are compared by User ID / Filename instead of a dictionary lookup
                #This isn't necessarily any faster but it is more convenient and doesn't require a restart to assign voicelines
                dir = os.listdir(self.SOUND_DIR / "voicelines")
                for i in dir:
                    if os.path.isdir(self.SOUND_DIR / "voicelines" / i) and  i == str(what.id): #we have a voiceline folder for this member
                        files = os.listdir(self.SOUND_DIR / "voicelines" / i)
                        if not files: #no voicelines found, return
                            return
                        filepath = self.SOUND_DIR / "voicelines" / i / random.choice(files)
                        sound = FFMPEGSound(filepath.as_posix())
                        self.audio.playSound(sound, after_channel, sync=False)
                        return

    async def _autosave(self):

        """
        Periodic autosave task.
        Runs every 5 minutes and writes changes made to the config and the CS to the filesystem.
        """

        logger = self.logger.getChild("Autosave")

        if self._autosave_active:
            logger.warn("Autosave task was triggered but is already running!")
            return

        self._autosave_active = True

        while not self.is_closed():
            await asyncio.sleep(300)

            logger.info("Periodic backup task triggered.")
            await self.save()

        self._autosave_active = False

    async def save(self):

        """
        Save the current configuration.
        """

        self.logger.debug("Saving data...")
        self.config.save()
        await self.cs.setOpt("SAVE", None)
        self.logger.debug("Backup complete!")

    async def shutdown(self, reason=""):

        """
        Shut down the bot.
        This coroutine will correctly deinitialize all submodules and run all cleanup functions
        before shutting down the event loop and exiting.

        reason specifies an optional string to log when shutting the bot down.
        """

        self.logger.info("Shutting down with reason: %s" % reason)

        await cmdsys.cleanUp()

        await self.save()
        await self.logout()
        await self.close()
Ejemplo n.º 12
0
 def __init__(self, x, y, velx=0, vely=-900, damage=8):
     self.hitbox = Rectangle(x, y, 8, 8)
     self.velx = velx  # px/s
     self.vely = vely
     self.damage = damage
     AudioManager.play_sound("laser")
Ejemplo n.º 13
0
    def handle_event(self, event):
        if event.type == SDL_QUIT:
            self.running = False
        elif event.type == SDL_DROPFILE:
            self.clock.tick()
        elif event.type == SDL_KEYDOWN and event.key.repeat == 0:
            if event.key.keysym.sym == SDLK_ESCAPE:
                self.running = False
            elif event.key.keysym.sym == SDLK_F1:
                self.debug_info = not self.debug_info

    def draw(self):
        pass

    def stop(self):
        self.running = False


if __name__ == "__main__":
    ext.init()
    graphics = Graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
    AllSprite.load_sprites(graphics)
    AudioManager.init_audio()
    load_audio()
    FontManager.load_font("ressources/Rebellion.ttf", "rebel", 28)
    FontManager.load_font("ressources/DejaVuSansMono.ttf", "dejavu", 20)
    game = Menu(graphics)
    game.run()
    ext.quit()
Ejemplo n.º 14
0
    if AUDIO:
        s.shutdown()
    quit()


if FULLSCREEN:
    screen = pg.display.set_mode((WIDTH, HEIGHT), pg.FULLSCREEN)
else:
    screen = pg.display.set_mode((WIDTH, HEIGHT))

FONT = pg.font.Font(load_resource("JetBrainsMono-Medium.ttf"), 12)
BACKGROUND = pg.image.load(load_resource("gameboard.jpg")).convert()
pg.display.set_caption(f"ALTAR CLIENT username = {USERNAME}")

if AUDIO:
    audio = AudioManager()


def main():
    clock = pg.time.Clock()

    ###########
    # GUI ITEMS
    ###########

    drop_c = DropZone(ZONE_COORS[0])
    drop_r = DropZone(ZONE_COORS[1])
    drop_l = DropZone(ZONE_COORS[2])
    hand = HandZone((685, 850))
    discard = DiscardSpace((50, 50))
    draw = DrawSpace((WIDTH - 150, 50))
Ejemplo n.º 15
0
class MainScene(QGraphicsScene):
    frame = None
    loop_count = 0
    parent_scene = None
    current_dt = 0.0
    next_frame = None
    def __init__(self, window, view, parent_object = None):
        QGraphicsScene.__init__(self, window)
        self.application = window.application
        self.window = window
        self.view = view
        self.parent_object = parent_object
        if parent_object is None:
            self.update_timer = QTimer(self)
            self.update_timer.timeout.connect(self.update_loop)
            # MMF 1.5 is 50 FPS
            self.update_timer.start((1 / 50.0) * 1000)
            self.values = {}
            self.strings = {}
            self.players = [Player(START_LIVES) for _ in xrange(4)]
            self.audio = AudioManager()
            start_index = 0
            if FAST_CONNECT:
                start_index = 4
            self.set_frame(start_index, True)
        else:
            scene = parent_object.scene
            self.values = scene.values
            self.strings = scene.strings
            self.players = scene.players
            self.audio = scene.audio
        self.key_presses = []
        self.key_downs = []
        self.mouse_downs = []
    
    def update_loop(self):
        try:
            if self.next_frame is not None:
                self.set_frame(self.next_frame, True)
                self.next_frame = None
                return
            self.loop_count += 1
            current_time = get_time()
            dt = current_time - self.current_time
            self.current_time = current_time
            self.audio.update(dt)
            self.make_update(dt)
        except:
            import traceback
            traceback.print_exc()
            self.exit()

    def make_update(self, dt):
        self.current_dt = dt
        self.frame.update(dt)
        for instance in self.frame.instances:
            instance.update(dt)
        self.update()
        self.key_presses = []

    def exit(self):
        if self.parent_object is not None:
            self.parent_object.on_exit(self)
            return
        self.audio.delete()
        self.application.quit()
    
    def set_frame(self, index, force = False):
        if not force:
            self.next_frame = index
            return
        if self.frame:
            self.frame.destroy()
        self.frame = FRAMES[index](self)
        self.current_time = get_time()
        
    def drawBackground(self, painter, rect):
        frame = self.frame
        painter.beginNativePainting()
        painter.setRenderHint(QPainter.Antialiasing)
        r, g, b = frame.background
        GL.glClearColor(r / 255.0, g / 255.0, b / 255.0, 1.0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        width, height = int(self.width()), int(self.height())
        GL.glViewport(0, 0, width, height)
        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GL.glOrtho(0, width, height, 0, -1, 1)
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glLoadIdentity()
        frame.draw(painter)
        painter.endNativePainting()
    
    def get_mouse_position(self):
        p = self.view.mapToScene(self.view.mapFromGlobal(QCursor.pos()))
        return p.x(), p.y()
    
    def keyPressEvent(self, event):
        key = event.key()
        QGraphicsScene.keyPressEvent(self, event)
        self.key_presses.append(key)
        self.key_downs.append(key)
    
    def keyReleaseEvent(self, event):
        QGraphicsScene.keyReleaseEvent(self, event)
        self.key_downs.remove(event.key())
    
    def mousePressEvent(self, event):
        QGraphicsScene.mousePressEvent(self, event)
        pos = event.scenePos()
        button = event.button()
        self.frame.on_mouse_press(pos.x(), pos.y(), button)
        self.mouse_downs.append(button)

    def mouseDoubleClickEvent(self, event):
        QGraphicsScene.mouseDoubleClickEvent(self, event)
        self.mouse_downs.append(event.button())

    def mouseReleaseEvent(self, event):
        QGraphicsScene.mouseReleaseEvent(self, event)
        button = event.button()
        self.mouse_downs.remove(button)
Ejemplo n.º 16
0
class Bombercan(Game):
    """The main class of this game."""
    def __init__(self):
        """Create the main menu."""
        super(Bombercan, self).__init__('BomberCan', 500, 500, 80)

        # Play BGM
        self.audio = AudioManager()
        self.audio.play('bombercan.wav', loop=True)
            
        # Display the main menu
        self.menu = MenuScene(
                parent=self,
                style={},
                audio=self.audio,
                key_up=self.key_up,
                key_down=self.key_down,
                on_game_start=self.game_start
                )

        # Prepare the end scene
        self.end = EndScene(
                parent=self,
                style={},
                key_up=self.key_up,
                key_down=self.key_down,
                on_game_reset=self.game_reset
                )

        self.game_reset()

    def game_reset(self):
        """Show the main menu."""
        self.top_node=self.menu
        self.top_node.do_resize_recursive()

    def game_end(self):
        """Show the end roll."""
        self.top_node=self.end
        self.top_node.do_resize_recursive()

    def game_start(self, mode, stage_num=0):
        """Setup the stage to start the game.
        
        @param mode: 0 for story mode, 1 for free game
        @param stage_num: specify the number of stage in story mode

        """
        if mode == 0:
            def _goto_next_stage():
                # After the player won this stage, start the next stage,
                # or show the end roll if all stage are cleared.
                if stage_num + 1 >= len(stagesetting.stage):
                    self.game_end()
                else:
                    self.game_start(0, stage_num + 1)

            settings = stagesetting.stage[stage_num]
            self.stage = StageScene(
                    parent=self,
                    style={},
                    audio=self.audio,
                    map_size=settings['size'], 
                    margin=(20, 20, 20, 20),
                    key_up=self.key_up,
                    key_down=self.key_down,
                    on_game_reset=self.game_reset,
                    on_game_win=_goto_next_stage
                )

            # Parse the setting
            self.stage.parse(settings['str'], settings['blocks'])

        elif mode == 1:
            self.stage = StageScene(
                    parent=self,
                    style={},
                    audio=self.audio,
                    map_size=(15, 15), 
                    margin=(20, 20, 20, 20),
                    key_up=self.key_up,
                    key_down=self.key_down,
                    on_game_reset=self.game_reset,
                    on_game_win=self.game_reset
                )

            # Randomly generate a stage
            self.stage.generate(20, 60)

        # Show the stage
        self.top_node=self.stage
        self.top_node.do_resize_recursive()

    @printfps()
    def on_tick(self, interval):
        """Do nothing but print the fps."""
        pass