Exemple #1
0
 def createPlayer(cls, parentId, name):
     game = GameService.getById(parentId)
     player = Player(name=name, position=ndb.GeoPt(0, 0), parentId=parentId)
     player.put()
     game.playerIds.append(player.key.id())
     game.put()
     return player
Exemple #2
0
 def __init__(self, name, camera, lights=[], objects=[], frame_count=30):
     self.name = name
     self.player = Player(name)
     self.camera = camera
     self.objects = objects
     self.lights = lights
     self.frame_count = frame_count
Exemple #3
0
 def __init__(self, videoManager, audioManager, playerReps):
     self.gameMode = self.gameModeAwaitingCalibrationConfirm
     self.defaultFont = videoManager.getDefaultFont()
     self.audioManager = audioManager
     self.videoManager = videoManager
     self.player1 = Player.Player(playerReps)
     self.player2 = Player.Player(playerReps)
Exemple #4
0
 def protocol_handler(self, protocol):
     """
     处理服务端发来的协议
     """
     if protocol['protocol'] == 'ser_login':
         # 登录协议的相关逻辑
         if not protocol['result']:
             # 登录失败,继续调用登录方法
             print("登录失败:", protocol['msg'])
             return
         # 登录成功
         # 创建玩家
         self.game.role = Player(self.game.hero,
                                 protocol['player_data']['role_id'],
                                 CharWalk.DIR_DOWN,
                                 protocol['player_data']['x'],
                                 protocol['player_data']['y'],
                                 name=protocol['player_data']['nickname'],
                                 uuid=protocol['player_data']['uuid'])
         # 把玩家存到全局对象中,后面有用
         g.player = self.game.role
         g.scene_id = 2  # 切换场景
     elif protocol['protocol'] == 'ser_player_list':
         # 玩家列表
         print(protocol)
         for player_data in protocol['player_list']:
             player = Player(self.game.hero,
                             player_data['role_id'],
                             CharWalk.DIR_DOWN,
                             player_data['x'],
                             player_data['y'],
                             name=player_data['nickname'],
                             uuid=player_data['uuid'])
             self.game.other_player.append(player)
     elif protocol['protocol'] == 'ser_move':
         # 其他玩家移动了
         for p in self.game.other_player:
             if p.uuid == protocol['player_data']['uuid']:
                 p.goto(protocol['player_data']['x'],
                        protocol['player_data']['y'])
                 break
     elif protocol['protocol'] == 'ser_online':
         # 有其他玩家上线
         player_data = protocol['player_data']
         player = Player(self.game.hero,
                         player_data['role_id'],
                         CharWalk.DIR_DOWN,
                         player_data['x'],
                         player_data['y'],
                         name=player_data['nickname'],
                         uuid=player_data['uuid'])
         self.game.other_player.append(player)
     elif protocol['protocol'] == 'ser_chat':
         # 聊天
         self.game.chat_history.insert(
             0, "【%s】 " % protocol["nickname"] + protocol['text'])
         if len(self.game.chat_history) > 5:
             self.game.chat_history.pop()
Exemple #5
0
 def createPlayer(cls, parentId, name):
     game = GameService.getById(parentId)
     player = Player(name = name,
                     position = ndb.GeoPt(0, 0),
                     parentId = parentId)
     player.put()
     game.playerIds.append(player.key.id())
     game.put()
     return player
Exemple #6
0
def test_simple_hit_while_game_stopped(game_state, game_logic):
    player = Player(1, 1)
    initialHealth = player.health

    sentPlayer = Player(1, 2)
    damage = 2

    game_logic.hit(game_state, player, sentPlayer, damage)

    assert initialHealth == player.health
Exemple #7
0
def test_team_hit(game_state, game_logic):
    game_state.startGame()
    player = Player(1, 1)
    initialHealth = player.health

    sentPlayer = Player(1, 2)
    damage = 2

    game_logic.hit(game_state, player, sentPlayer, damage)

    assert initialHealth - damage == player.health
Exemple #8
0
def test_simple_hit_from_dead_player(game_state, game_logic):
    game_state.startGame()
    player = Player(1, 1)
    initialHealth = player.health

    sentPlayer = Player(1, 2)
    sentPlayer.health = 0
    damage = 2

    game_logic.hit(game_state, player, sentPlayer, damage)

    assert initialHealth == player.health
def test_simple_hit_from_dead_player(game_state, game_logic):
    game_state.startGame()
    player = Player(1, 1)
    initialHealth = player.health
  
    sentPlayer = Player(1, 2)
    sentPlayer.health = 0
    damage = 2
  
    game_logic.hit(game_state, player, sentPlayer, damage)
  
    assert initialHealth == player.health
Exemple #10
0
 def protocol_handler(self, protocol):
     """
     处理服务端发来的协议
     """
     if protocol['protocol'] == 'ser_login':
         # 登录协议的相关逻辑
         if not protocol['result']:
             # 登录失败,继续调用登录方法
             print("登录失败:", protocol['msg'])
             self.login()
             return
         # 登录成功
         # 创建玩家
         self.game.role = Player(self.game.hero,
                                 protocol['player_data']['role_id'],
                                 CharWalk.DIR_DOWN,
                                 protocol['player_data']['x'],
                                 protocol['player_data']['y'],
                                 name=protocol['player_data']['nickname'],
                                 uuid=protocol['player_data']['uuid'])
         # 把玩家存到全局对象中,后面有用
         g.player = self.game.role
         self.game.game_state = 1  # 设置游戏的登录状态为已登录
     elif protocol['protocol'] == 'ser_player_list':
         # 玩家列表
         print(protocol)
         for player_data in protocol['player_list']:
             player = Player(self.game.hero,
                             player_data['role_id'],
                             CharWalk.DIR_DOWN,
                             player_data['x'],
                             player_data['y'],
                             name=player_data['nickname'],
                             uuid=player_data['uuid'])
             self.game.other_player.append(player)
     elif protocol['protocol'] == 'ser_move':
         # 其他玩家移动了
         for p in self.game.other_player:
             if p.uuid == protocol['player_data']['uuid']:
                 p.goto(protocol['player_data']['x'],
                        protocol['player_data']['y'])
                 break
     elif protocol['protocol'] == 'ser_online':
         # 有其他玩家上线
         player_data = protocol['player_data']
         player = Player(self.game.hero,
                         player_data['role_id'],
                         CharWalk.DIR_DOWN,
                         player_data['x'],
                         player_data['y'],
                         name=player_data['nickname'],
                         uuid=player_data['uuid'])
         self.game.other_player.append(player)
Exemple #11
0
def play():
    players = (Player(), Player())
    game = Game(15, 15)

    while True:
        for player in players:
            move = player.random_search(game)
            game.make_move(move)
            game.display()

            if game.terminal_test():
                print("Game over")
                return

            sleep(1)
Exemple #12
0
 def do_player(self, arg):
     player = world.find_player(arg)
     if not player:
         player = Player(name=arg)
         world.add_player(player)
     self.set_player(player)
     self.player.location.look(self.player)
Exemple #13
0
    def play_file(self, filename, args=[]):
        if self.mplayer.is_alive():
            self.mplayer.quit()
            self.mplayer = Player(args=stdargs + args)
        
        del self.playlist[:]
        self.playlist.append(filename)
        if not self.mplayer.filename:
            self.mplayer.loadfile(self.playlist[0])
        print self.mplayer.info
        if self.audio_source_merge_id:
             self.uimanager.remove_ui(self.audio_source_merge_id)
        AUDIO_INFO = """
        <ui>
          <popup name='PopupMenu'>
            <menu action='PopupAudioMenu'>
                <separator />
        """

        for key in self.mplayer.info['audio']:
            AUDIO_INFO += "<menuitem action='PopupAudioSource" + key + "'/>"

        AUDIO_INFO += """
            </menu>
          </popup>
        </ui>
        """
        action_group = Gtk.ActionGroup("audio_source_actions")
        self.add_audio_source_actions(action_group)
        self.uimanager.insert_action_group(action_group)
        self.audio_source_merge_id = self.uimanager.add_ui_from_string(AUDIO_INFO)

        self.resize(self.mplayer.width, self.mplayer.height)
        pass
Exemple #14
0
    def handleMsg(self, fullLine):
        event = proto.parseEvent(fullLine)
        msgStr = event.msgStr

        try:
            (teamID, playerID) = proto.TEAMPLAYER.parse(msgStr)
            self.main.player = Player(teamID, playerID)
            return True
        except proto.MessageParseException:
            pass

        try:
            (duration, ) = proto.STARTGAME.parse(msgStr)
            self.main.gameState.setGameTime(int(duration))
            self.main.gameState.startGame()
            return True
        except proto.MessageParseException:
            pass

        try:
            proto.STOPGAME.parse(msgStr)
            self.main.gameState.stopGame()
            return True
        except proto.MessageParseException:
            pass

        try:
            proto.DELETED.parse(msgStr)
            #just treat this as the game stopping for us.
            self.main.gameState.stopGame()
            return True
        except proto.MessageParseException:
            pass

        return False
Exemple #15
0
def main():
    # Parse arguments

    parser = argparse.ArgumentParser()
    parser.add_argument('--players', '-p', type=int, default=3)
    parser.add_argument('--log', '-l', action='store_true')
    parser.add_argument('--replay', '-r', action='store_true')

    args = parser.parse_args()

    player_names = ["Costas", "Cam", "Jeff", "Evan", "Alex"]

    if not 3 <= args.players <= 5:
        print("Invalid number of players requested ({}); " + \
              "must be between 3 and 5 inclusive".format(args.players))
        sys.exit(1)
    assert 3 <= len(player_names) <= 5

    players = [
        Player(name, i + 1)
        for i, name in enumerate(player_names[:args.players])
    ]

    g = game.Game(args.log, args.replay)
    success = map(g.add, players)
    assert all(success)

    try:
        g.start()
    except KeyboardInterrupt:
        print()
Exemple #16
0
 def deletePlayer(cls, playerId):
     player = Player.get_by_id(playerId, parent=None)
     parentGame = Game.get_by_id(player.parentId)
     parentGame.playerIds.remove(playerId)
     parentGame.put()
     memcache.delete(str(playerId), namespace='players')
     player.key.delete()
Exemple #17
0
 def deletePlayer(cls, playerId):
     player = Player.get_by_id(playerId, parent=None)
     parentGame = Game.get_by_id(player.parentId)
     parentGame.playerIds.remove(playerId)
     parentGame.put()
     memcache.delete(str(playerId), namespace='players')
     player.key.delete()
Exemple #18
0
def dual_play(agents, board=None, verbose=False, graphic=False):
    """
    Play with 2 players.
    Params:
      agents:  { Player.black: agent1, Player.white: agent2 }.
      board:   initial board state. Start player will be determined here.
      verbose: if true, then return value will be in the form of training data.
    Returns:
      if verbose set to True:
        [(state_inputs, final_score, action_probs)]
        Each element is a numpy.array.
      else:
        winner
    """
    if board is None:
        board = Board()
    elif board.status["is_end"]:
        board.reset()

    if verbose is True:
        result = []
    else:
        result = Player.none

    while True:
        # set the current agent
        cur_agent = agents[board.status["cur_player"]]

        # evaluate board state and get action
        if verbose is True:
            _, action_probs, next_move = cur_agent.eval_state(board)
            result.append([
                board.encoded_states(),
                board.status["cur_player"], 
                action_probs
            ])
        else:
            next_move = cur_agent.get_action(board)
        # update board
        board.apply_move(next_move)
        if graphic:
            print(board)

        # end judge
        if board.status["is_end"]:
            winner = board.status["winner"]
            if graphic:
                print("Game ends. winner is {}.".format(winner))
            # format output result
            if verbose is True:
                result = [(
                    state[0],
                    np.array(Player.calc_score(state[1], winner)), 
                    state[2]
                ) for state in result]
            else:
                result = winner

            return result
Exemple #19
0
def test_shot_until_dead(game_state, game_logic):
    game_state.startGame()
    player = Player(1, 1)
    initialHealth = player.health

    sentPlayer = Player(2, 1)
    damage = (
        player.health //
        2) + 1  # this will fail if the player only starts with 2 health :-(

    game_logic.hit(game_state, player, sentPlayer, damage)
    assert initialHealth - damage == player.health

    game_logic.hit(game_state, player, sentPlayer, damage)
    assert 0 == player.health

    game_logic.hit(game_state, player, sentPlayer, damage)
    assert 0 == player.health
Exemple #20
0
    def play(self, option):
        """Initialize level, player and handle the game events

        Variables:
            keymap(dict): { key(pygame.Key): direction(str) }

        Args:
            option(int): Option selected by the player in the menu
        """
        keymap = {
            pygame.K_LEFT: "W",
            pygame.K_RIGHT: "E",
            pygame.K_UP: "N",
            pygame.K_DOWN: "S"
        }

        self.in_game = True
        level = Level(option)
        player = Player(level)
        guard = NPC(level, "G")
        self.display.game(level)
        self.sound.play("GAME")

        while self.in_game:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_m:
                        self.sound.mute()
                    if event.key == pygame.K_ESCAPE:
                        self.in_menu = True
                        self.in_game = False
                        self.sound.stop()
                    if event.key in keymap:
                        player.move(level, keymap[event.key],
                                    self.display, self.sound)
                        if player.y == guard.y and player.x == guard.x:
                            if len(player.inventory) == 3:
                                self.display.end("W")
                            else:
                                self.display.end("L")
                            self.in_game = False
                            self.in_menu = True
                            self.sound.stop()
            self.display.hud(player)
Exemple #21
0
 def on_drag_data_received(self, widget, drag_context, x, y, data, info, time):
     del self.playlist[:]
     for uri in data.get_uris():
         path = self.get_file_path_from_dnd_dropped_uri(uri)
         self.playlist.append(path)
     if self.mplayer.is_alive():
         self.mplayer.quit()
         self.mplayer = Player(args=stdargs)
     self.mplayer.loadfile(self.playlist[0])
     print self.playlist
     return True
Exemple #22
0
    def test_simple_hit_while_game_stopped(self):
        player = Player(1, 1)
        initialHealth = player.health

        sentTeam = 1
        sentPlayer = 2
        damage = 2

        self.gl.hit(self.gameState, player, sentTeam, sentPlayer, damage)

        self.assertEqual(initialHealth, player.health)
 def reset(self):
     '''reset everything'''
     self.player = Player(1000)
     self.currentCity = self.citys["A"]
     self.currentMarket = self.market_a
     self.indexM = 0
     self.indexP = 0
     self.refresh()
     self.isMarket = False
     self.switch_display()
     self.update_MW()
     self.initializeWarehouse()
     self.day = 0
     self.place = self.currentCity.getName()
     self.day_string.set("Day: " + str(self.day))
     self.place_string.set("Place: " + self.place)
     self.deselect()
     self.bus_rb.select()
     self.bus_rb.invoke()
     self.show(self.market_f)
Exemple #24
0
    def test_team_hit(self):
        self.gameState.startGame()
        player = Player(1, 1)
        initialHealth = player.health

        sentTeam = 1
        sentPlayer = 2
        damage = 2

        self.gl.hit(self.gameState, player, sentTeam, sentPlayer, damage)

        self.assertEqual(initialHealth - damage, player.health)
Exemple #25
0
  def getOrCreatePlayer(self, sentTeam, sentPlayer):
    if not (sentTeam, sentPlayer) in self.players:
      self.players[(sentTeam, sentPlayer)] = Player(sentTeam, sentPlayer)
      if sentTeam > self.teamCount:
        self.teamCount = sentTeam
        self.teamCountChanged.emit(self.teamCount)
      if sentPlayer > self.largestTeam:
        self.largestTeam = sentPlayer
        self.largestTeamChanged.emit(self.largestTeam)

      self.playerAdded.emit(sentTeam, sentPlayer)
    return self.players[(sentTeam, sentPlayer)]
    def getOrCreatePlayer(self, sentTeamStr, sentPlayerStr):
        sentTeam = int(sentTeamStr)
        sentPlayer = int(sentPlayerStr)

        if not (sentTeam, sentPlayer) in self.players:
            self.players[(sentTeam, sentPlayer)] = Player(sentTeam, sentPlayer)
            if sentTeam > self.teamCount:
                self.teamCount = sentTeam
            if sentPlayer > self.largestTeam:
                self.largestTeam = sentPlayer

            self.playerAdded.emit(sentTeam, sentPlayer)
        return self.players[(sentTeam, sentPlayer)]
Exemple #27
0
 def __init__(self, size, name, player_positions) -> None:
     self.id: str = str(uuid.uuid1())
     self.name: str = name
     self.instances[self.id] = self
     players = [Player(str(i), row, col) for i, (row, col) in enumerate(player_positions, 1)]
     self.game: WallGame = WallGame(size, players)
     self.manager = PlayerManager(self.game.players)
     self.status: RoomStatus = RoomStatus.waiting
     self.players_initial_poses: Dict[str, Tuple] = {player: (player.row, player.col)
                                                     for player in self.manager.players}
     if len(self.players_initial_poses) != len(self.manager.players):
         raise ValueError('duplicated player_positions')
     self.task = None
Exemple #28
0
def init_players(n):
    ''' Initilize a list of Player objects with n players

    Args:
        n (int): The number of players to be initialized

    Returns:
        (list): A list of Player objects with player_id(s) start from 0 and are consequent
    '''

    players = []
    for idx in range(n):
        players.append(Player(idx))
    return players
Exemple #29
0
    def test_shot_until_dead(self):
        self.gameState.startGame()
        player = Player(1, 1)
        initialHealth = player.health

        sentTeam = 2
        sentPlayer = 1
        damage = (
            player.health // 2
        ) + 1  # this will fail if the player only starts with 2 health :-(

        self.gl.hit(self.gameState, player, sentTeam, sentPlayer, damage)
        self.assertEqual(initialHealth - damage, player.health)

        self.gl.hit(self.gameState, player, sentTeam, sentPlayer, damage)
        self.assertEqual(0, player.health)
        #TODO assert death signal

        self.gl.hit(self.gameState, player, sentTeam, sentPlayer, damage)
        self.assertEqual(0, player.health)
Exemple #30
0
    def getPlayersForGame(cls, gameId):
        game = Game.get_by_id(int(gameId));

        # Initialize string representations of player and entity IDs
        game.makeStringValuedIds()

        # Get all cached buddies
        buddyDictionary = memcache.get_multi( game.playerIdStrings, key_prefix='player' )

        # Go through all buddy-keys of the parent game
        for playerId in game.playerIdStrings:
            # if one is missing, reload from the database and add to the buddy dictionary
            if playerId not in buddyDictionary:
                buddyDictionary[playerId] = Player.get_by_id( int(playerId), parent=None )

        # Now we're sure everybody is there. No Child Left Behind.
        # Everybody is in the dictionary. A good time to write it to the cache again
        memcache.set_multi(buddyDictionary)

        # The caller is only interested in the values of the dictionary.
        return buddyDictionary.values()
Exemple #31
0
    def getPlayersForGame(cls, gameId):
        game = Game.get_by_id(int(gameId))

        # Initialize string representations of player and entity IDs
        game.makeStringValuedIds()

        # Get all cached buddies
        buddyDictionary = memcache.get_multi(game.playerIdStrings,
                                             key_prefix='player')

        # Go through all buddy-keys of the parent game
        for playerId in game.playerIdStrings:
            # if one is missing, reload from the database and add to the buddy dictionary
            if playerId not in buddyDictionary:
                buddyDictionary[playerId] = Player.get_by_id(int(playerId),
                                                             parent=None)

        # Now we're sure everybody is there. No Child Left Behind.
        # Everybody is in the dictionary. A good time to write it to the cache again
        memcache.set_multi(buddyDictionary)

        # The caller is only interested in the values of the dictionary.
        return buddyDictionary.values()
Exemple #32
0
class Scene:
    def __init__(self, name, camera, lights=[], objects=[], frame_count=30):
        self.name = name
        self.player = Player(name)
        self.camera = camera
        self.objects = objects
        self.lights = lights
        self.frame_count = frame_count

    def prepare(self):
        print("Preparing scene...")
        for object in self.objects:
            print(f"Building bounding box for {object}")
            object.compute_bounding_box(self.camera.brightness / len(palette))

    def render_frame(self, silent=False):
        self.camera.render(self.objects, self.lights)
        if not silent:
            print(self.camera.canvas)
        self.player.frame(self.camera.canvas)
        self.camera.canvas.clear()

    def post_frame_hook(self, index):
        print(f"Frame #{index}")

    def advance(self, index):
        for object in self.objects + self.lights + [self.camera]:
            if hasattr(object, "advance") and callable(object.advance):
                object.advance(object, index)

    def render(self, silent=False):
        self.prepare()
        for index in range(self.frame_count):
            self.render_frame(silent)
            self.post_frame_hook(index)
            self.advance(index)
        self.player.save()

    def start(self):
        if not self.player:
            self.render()
        self.player.play()
Exemple #33
0
    def updateCachedPosition(cls, keyId, lat, lon):
        player = Player.get_by_id(keyId, parent=None)

        player.position = ndb.GeoPt(lat, lon)
        memcache.set(player.key.urlsafe(), player, 10)
Exemple #34
0
 def getGameForPlayer(cls, playerId):
     player = Player.get_by_id(playerId, parent=None)
     return Game.get_by_id(player.parentId, parent=None)
Exemple #35
0
from core import Player, WaveSynth, Note, Offset, Beat, Sample

p = Player(Player.BackendType.vorbis,Offset(44100),220,"prelude_py.ogg")

ws = WaveSynth(p.sample_rate(), p.freq_reference(),"wavesynth_dump.log")

note_length = Beat(1,2) 
note_intensity = Sample.max_intensity()/2
scale_degrees = [0, 2, 4, 7]
octave_count = 4
notes = []

def note_start(note_length):
    count = 0
    while True:
        yield count*note_length
        count+=1

note_s = note_start(note_length)

for octave in range(octave_count):
    for v in scale_degrees:
        notes.append(
            Note(v,octave,note_intensity,note_s.__next__(),note_length))

note_count = len(notes)
scale_degrees = [12, 7, 4, 2]

for octave in reversed(range(octave_count)):
    for v in scale_degrees:
        notes.append(
Exemple #36
0
class ShellPlayer(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Shell Player")

        self.set_default_size(640, 360)
        self.set_position(Gtk.WindowPosition.CENTER)

        action_group = Gtk.ActionGroup("shell_player_actions")

        self.add_popup_menu_actions(action_group)
        self.add_file_menu_actions(action_group)
        self.add_view_menu_actions(action_group)
        self.add_video_menu_actions(action_group)
        self.add_audio_menu_actions(action_group)
        self.add_subtitles_menu_actions(action_group)

        self.uimanager = self.create_ui_manager()
        self.uimanager.insert_action_group(action_group)

        ui_css = """GtkEventBox {
                        background:black;
                    }
                    """
        css_provider = Gtk.CssProvider()
        screen = Gdk.Screen.get_default()
        context = Gtk.StyleContext()        
        css_provider.load_from_data(ui_css)
        context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        eventbox = Gtk.EventBox()
        eventbox.connect("draw", self.on_expose_event)
        
        eventbox.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.LINK)
        eventbox.drag_dest_add_uri_targets()

        self.connect("key-press-event", self.on_key_press_event)
        self.connect("motion-notify-event", self.on_motion_notify_event)
        self.connect("scroll-event", self.on_scroll_wheel_event)
        eventbox.connect("button-press-event", self.on_button_press_event)
        eventbox.connect("drag-data-received", self.on_drag_data_received)
        self.set_events(Gdk.EventMask.LEAVE_NOTIFY_MASK
             | Gdk.EventMask.BUTTON_PRESS_MASK
             | Gdk.EventMask.BUTTON_RELEASE_MASK
             | Gdk.EventMask.POINTER_MOTION_MASK
             | Gdk.EventMask.POINTER_MOTION_HINT_MASK
             | Gdk.EventMask.SCROLL_MASK)
        box.pack_start(eventbox, True, True, 0)

        manager = Gtk.RecentManager.get_default()
        self.recentchooser = Gtk.RecentChooserMenu()
        recentfilter = Gtk.RecentFilter()
        recentfilter.set_name('Video Files')
        recentfilter.add_mime_type('video/*')        
        self.recentchooser.add_filter(recentfilter)
        self.recentchooser.connect("item-activated", self.display_info)

        self.uimanager.get_widget("/PopupMenu/PopupFileMenu/PopupFileRecent").set_submenu(self.recentchooser)

        self.popup = self.uimanager.get_widget("/PopupMenu")

        self.add(box)

        self.mplayer = None
        self.above = False
        self.fullscreened = False
        self.compactness = 0
        self.resize_grip = 10
        self.playlist = []
        self.audio_source_merge_id = None

    def play_file(self, filename, args=[]):
        if self.mplayer.is_alive():
            self.mplayer.quit()
            self.mplayer = Player(args=stdargs + args)
        
        del self.playlist[:]
        self.playlist.append(filename)
        if not self.mplayer.filename:
            self.mplayer.loadfile(self.playlist[0])
        print self.mplayer.info
        if self.audio_source_merge_id:
             self.uimanager.remove_ui(self.audio_source_merge_id)
        AUDIO_INFO = """
        <ui>
          <popup name='PopupMenu'>
            <menu action='PopupAudioMenu'>
                <separator />
        """

        for key in self.mplayer.info['audio']:
            AUDIO_INFO += "<menuitem action='PopupAudioSource" + key + "'/>"

        AUDIO_INFO += """
            </menu>
          </popup>
        </ui>
        """
        action_group = Gtk.ActionGroup("audio_source_actions")
        self.add_audio_source_actions(action_group)
        self.uimanager.insert_action_group(action_group)
        self.audio_source_merge_id = self.uimanager.add_ui_from_string(AUDIO_INFO)

        self.resize(self.mplayer.width, self.mplayer.height)
        pass

    def choose_file(self, mime):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        self.add_filters(dialog, mime)

        response = dialog.run()
        filename = None
        if response == Gtk.ResponseType.OK:
            filename = dialog.get_filename()
        elif response == Gtk.ResponseType.CANCEL:
            pass
        dialog.destroy()
        return filename

    def on_file_clicked(self, widget):
        filename = self.choose_file({'Media Files':['video/*', 'audio/*'], 'Any Files':['*']})
        if filename:
            self.play_file(filename)
        else:
            print 'canceled or wrong filename'

    def add_filters(self, dialog, mime):
        filter_text = Gtk.FileFilter()

        for key in mime:
            filefilter = Gtk.FileFilter()
            filefilter.set_name(key)
            for mime_type in mime[key]:
                filefilter.add_mime_type(mime_type)            
            dialog.add_filter(filefilter)

    def on_folder_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a folder", self,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             "Select", Gtk.ResponseType.OK))
        dialog.set_default_size(800, 400)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print "Select clicked"
            print "Folder selected: " + dialog.get_filename()
        elif response == Gtk.ResponseType.CANCEL:
            print "Cancel clicked"

        dialog.destroy()

    def add_popup_menu_actions(self, action_group):
        #settings button
        action_group.add_actions([
            ("PopupMenu", None, "Popup"),
            ("PopupSettings", Gtk.STOCK_PREFERENCES, None, None, None,
             self.on_menu_others)
        ])
        #quit button
        action_filequit = Gtk.Action("PopupQuit", "Quit", None, Gtk.STOCK_QUIT)
        action_filequit.connect("activate", self.on_menu_file_quit)
        action_group.add_action_with_accel(action_filequit, "Escape")

    def add_file_menu_actions(self, action_group):
        action_group.add_action(Gtk.Action("PopupFileMenu", "File", None, None))

        action_group.add_actions([
            ("PopupFileOpen", Gtk.STOCK_OPEN, None, None, None,
             self.on_file_clicked),
            ("PopupFileClose", Gtk.STOCK_CLOSE, None, None, None,
             self.on_folder_clicked),
            ("PopupFileRecent", None, 'Open Recent', None, None,
             None)
        ])

    def add_view_menu_actions(self, action_group):
        action_group.add_action(Gtk.Action("PopupViewMenu", "View", None, None))

        on_top = Gtk.ToggleAction("PopupViewOnTop", "On Top", None, None)
        on_top.connect("toggled", self.on_keep_on_top)
        action_group.add_action(on_top)

        borderless = Gtk.ToggleAction("PopupViewBorderless", "No Frame", None, None)
        borderless.set_active(True)
        borderless.connect("toggled", self.on_border_switch)
        action_group.add_action(borderless)

    def add_video_menu_actions(self, action_group):
        action_group.add_action(Gtk.Action("PopupVideoMenu", "Video", None, None))

        action_group.add_actions([
            ("PopupVideoSettings", None, "Settings", None, None,
             self.on_menu_others),
            ("PopupVideoAspect", None, "Aspect", None, None,
             self.on_menu_others)
        ])

    def add_audio_menu_actions(self, action_group):
        action_group.add_action(Gtk.Action("PopupAudioMenu", "Audio", None, None))

        action_group.add_actions([
            ("PopupAudioExternal", None, "External Audio", None, None,
             self.on_audio_external),
            ("PopupAudioUnload", None, "Unload External Audio", None, None,
             self.on_audio_unload)
        ])

    def add_audio_source_actions(self, action_group):
        for key in self.mplayer.info['audio']:
            info = ""
            lang = ""
            if 'info' in self.mplayer.info['audio'][key]:
                info = self.mplayer.info['audio'][key]['info']
            if 'lang' in self.mplayer.info['audio'][key]:
                lang = self.mplayer.info['audio'][key]['lang']
            action_group.add_actions([
                ("PopupAudioSource" + key, None, 'Audio: ' + key + ' ' + info + ' ' + lang, None, None,
                 self.on_audio_source)
            ])
        pass

    def add_subtitles_menu_actions(self, action_group):
        action_group.add_action(Gtk.Action("PopupSubtitlesMenu", "Subtitles", None, None))

        action_group.add_actions([
            ("PopupSubtitlesExternal", None, "Load External", None, None,
             self.on_menu_others),
            ("PopupSubtitlesSource", None, "Select Builtin", None, None,
             self.on_menu_others)
        ])

    def display_info(self, widget):
        selected = self.recentchooser.get_current_item().get_uri()
        path = self.get_file_path_from_dnd_dropped_uri(selected)
        self.play_file(path)

    def on_keep_on_top(self, widget):
        self.set_keep_above(not self.above)
        self.above = not self.above

    def on_border_switch(self, widget):
        self.set_decorated(not self.get_decorated())

    def on_audio_external(self, widget):
        if self.mplayer.is_alive() and self.mplayer.filename:
            self.mplayer.pause()
            audiofile = self.choose_file({'Media Files':['audio/*'], 'Any Files':['*']})
            if audiofile:
                filename = self.mplayer.path
                position = int(self.mplayer.time_pos)
                self.play_file(None, ['-audiofile', audiofile, '-ss', position, filename])
            else:
                self.mplayer.pause()
        pass

    def on_audio_unload(self, widget):
        if self.mplayer.is_alive() and self.mplayer.filename:
            filename = self.mplayer.path
            position = int(self.mplayer.time_pos)
            self.play_file(None, ['-ss', position, filename])
        pass

    def on_audio_source(self, widget):
        s = widget.get_name()
        if s[-2:].isdigit():
            idx = s[-2:]
        else:
            idx = s[-1]        
        if self.mplayer.switch_audio != idx:
            self.mplayer.pause()
            self.mplayer._run_command('switch_audio', idx)
            self.mplayer.pause()
        return True

    def create_ui_manager(self):
        uimanager = Gtk.UIManager()

        # Throws exception if something went wrong
        uimanager.add_ui_from_string(UI_INFO)

        # Add the accelerator group to the toplevel window
        accelgroup = uimanager.get_accel_group()
        self.add_accel_group(accelgroup)
        return uimanager

    def on_menu_file_quit(self, widget):
        if self.mplayer:
            self.mplayer.quit()
        Gtk.main_quit()

    def on_menu_others(self, widget):
        print "Menu item " + widget.get_name() + " was selected"

    def on_menu_choices_toggled(self, widget):
        if widget.get_active():
            print widget.get_name() + " activated"
        else:
            print widget.get_name() + " deactivated"

    def on_button_press_event(self, widget, event):
        # Check if right mouse button was preseed
        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
            self.popup.popup(None, None, None, None, event.button, event.time)
            return True # event has been handled

        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
            some, x, y, mods = self.get_screen().get_root_window().get_pointer()
            mouse_position = self.get_pointer()
            window_size = (self.get_window().get_width(), self.get_window().get_height())
            if mouse_position[0] < self.resize_grip and mouse_position[1] < self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.NORTH_WEST, event.button, x, y, event.time)
                return True
            if mouse_position[0] > window_size[0] - self.resize_grip and mouse_position[1] > window_size[1] - self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.SOUTH_EAST, event.button, x, y, event.time)
                return True
            if mouse_position[0] < self.resize_grip and mouse_position[1] > window_size[1] - self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.SOUTH_WEST, event.button, x, y, event.time)
                return True
            if mouse_position[0] > window_size[0] - self.resize_grip and mouse_position[1] < self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.NORTH_EAST, event.button, x, y, event.time)
                return True
            if mouse_position[0] < self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.WEST, event.button, x, y, event.time)
                return True
            if mouse_position[0] > window_size[0] - self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.EAST, event.button, x, y, event.time)
                return True
            if mouse_position[1] > window_size[1] - self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.SOUTH, event.button, x, y, event.time)
                return True
            if mouse_position[1] < self.resize_grip:
                self.begin_resize_drag(Gdk.WindowEdge.NORTH, event.button, x, y, event.time)
                return True            
            self.begin_move_drag(event.button, x, y, event.time)
            return True

        if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1:
            if not self.fullscreened:
                self.fullscreen()
                self.fullscreened = True
            else:
                self.unfullscreen()
                self.fullscreened = False
            return True

    def on_key_press_event(self, widget, event):
        if event.keyval == Gdk.KEY_space:
            if self.mplayer.filename:
                self.mplayer.pause()
            else:
                if len(self.playlist) > 0:
                    self.play_file(self.playlist[0])
            return True
        if event.keyval == Gdk.KEY_r:
            return True
        if event.keyval == Gdk.KEY_l:
            metadata = self.mplayer.metadata or {}
            print metadata
            return True
        if event.state == Gdk.ModifierType.MOD1_MASK and event.keyval == Gdk.KEY_1:
            if self.mplayer.filename:
                self.resize(self.mplayer.width / 2, self.mplayer.height / 2)
            return True
        if event.state == Gdk.ModifierType.MOD1_MASK and event.keyval == Gdk.KEY_2:
            if self.mplayer.filename:
                self.resize(self.mplayer.width / 1.75, self.mplayer.height / 1.75)
            return True
        if event.state == Gdk.ModifierType.MOD1_MASK and event.keyval == Gdk.KEY_3:
            if self.mplayer.filename:
                self.resize(self.mplayer.width, self.mplayer.height)
            return True
        if event.keyval == Gdk.KEY_1:
            self.compactness = 0
            self.set_decorated(False)
            return True
        if event.keyval == Gdk.KEY_2:
            self.compactness = 1
            self.set_decorated(True)
            return True

        # else pass event to mplayer
        if self.mplayer.is_alive():
            self.mplayer.key_down_event(int(event.keyval))
            return True

    def on_motion_notify_event(self, widget, event):
        if self.compactness == 0:
            if event.type == Gdk.EventType.MOTION_NOTIFY:
                mouse_position = self.get_pointer()
                window_size = (self.get_window().get_width(), self.get_window().get_height())
                if mouse_position[0] < self.resize_grip and mouse_position[1] < self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.TOP_LEFT_CORNER))
                    return True
                if mouse_position[0] > window_size[0] - self.resize_grip and mouse_position[1] > window_size[1] - self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.BOTTOM_RIGHT_CORNER))
                    return True
                if mouse_position[0] < self.resize_grip and mouse_position[1] > window_size[1] - self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.BOTTOM_LEFT_CORNER))
                    return True
                if mouse_position[0] > window_size[0] - self.resize_grip and mouse_position[1] < self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.TOP_RIGHT_CORNER))
                    return True
                if mouse_position[0] < self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.LEFT_SIDE))
                    return True
                if mouse_position[0] > window_size[0] - self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.RIGHT_SIDE))
                    return True
                if mouse_position[1] > window_size[1] - self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.BOTTOM_SIDE))
                    return True
                if mouse_position[1] < self.resize_grip:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.TOP_SIDE))
                    return True
                if self.get_window().get_cursor() != None and self.get_window().get_cursor().get_cursor_type() != Gdk.CursorType.ARROW:
                    self.get_window().set_cursor (Gdk.Cursor(Gdk.CursorType.ARROW))
                    return True
                # else pass event to mplayer
                if self.mplayer.is_alive():
                    self.mplayer.set_mouse_pos(mouse_position[0], mouse_position[1])
                    return True
        pass


    def on_scroll_wheel_event(self, widget, event):
        if event.direction == Gdk.ScrollDirection.UP:
            if self.mplayer.filename:
                vol = self.mplayer.volume + 10
                self.mplayer.volume = vol if vol < 100 else 100
            return True
        if event.direction == Gdk.ScrollDirection.DOWN:
            if self.mplayer.filename:
                vol = self.mplayer.volume - 10
                self.mplayer.volume = vol if vol >= 0 else 0
            return True
        pass

    def on_drag_data_received(self, widget, drag_context, x, y, data, info, time):
        del self.playlist[:]
        for uri in data.get_uris():
            path = self.get_file_path_from_dnd_dropped_uri(uri)
            self.playlist.append(path)
        if self.mplayer.is_alive():
            self.mplayer.quit()
            self.mplayer = Player(args=stdargs)
        self.mplayer.loadfile(self.playlist[0])
        print self.playlist
        return True

    def get_file_path_from_dnd_dropped_uri(self, uri):
        path = ""
        if uri.startswith('file:\\\\\\'): # windows
            path = uri[8:] # 8 is len('file:///')
        elif uri.startswith('file://'): # nautilus, rox
            path = uri[7:] # 7 is len('file://')
        elif uri.startswith('file:'): # xffm
            path = uri[5:] # 5 is len('file:')

        path = urllib.url2pathname(path) # escape special chars
        path = path.strip('\r\n\x00') # remove \r\n and NULL

        return path

    def on_expose_event(self, widget, event):        
        # print('kok')
        # ctx = self.get_window().cairo_create()
        # Gtk.paint_resize_grip(self.get_default_style(), ctx, Gtk.StateType.NORMAL, self, "", Gdk.WindowEdge.WEST, -10, -10,
        #     0, 0)
        pass
Exemple #37
0
 def getBuddies(cls, playerId):
     player = Player.get_by_id(playerId, parent=None)
     return GameService.getPlayersForGame(player.parentId)
Exemple #38
0
 def allPlayers(cls):
     return Player.query()
Exemple #39
0
    def updateCachedPosition(cls, keyId, lat, lon):
        player = Player.get_by_id(keyId, parent = None)

        player.position = ndb.GeoPt(lat, lon)
        memcache.set(player.key.urlsafe(), player, 10)
Exemple #40
0
 def allPlayers(cls):
     return Player.query()
Exemple #41
0
 def getBuddies(cls, playerId):
     player = Player.get_by_id(playerId, parent=None)
     return GameService.getPlayersForGame(player.parentId)
Exemple #42
0
 def getGameForPlayer(cls, playerId):
     player = Player.get_by_id(playerId, parent=None)
     return Game.get_by_id(player.parentId, parent=None)